datasets

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const AnswerAccept = "accept"

AnswerAccept is the annotation answer of an example to train on. Prodigy exports also mark examples "reject" or "ignore"; the dataset skips those.

Variables

This section is empty.

Functions

func LabelNames added in v0.8.4

func LabelNames(idLabelMap map[int]string) []string

LabelNames returns the labels of an id2label map in id order.

func WordStartTokens added in v0.8.4

func WordStartTokens(words []string, input backends.TokenizedInput, sequenceLength int) []int

WordStartTokens returns, for each word, the index of its first non-special token among the first sequenceLength tokens, or -1 if it has none. input is the tokenization of the words joined with single spaces; its offsets are byte offsets into that string.

Types

type BatchCounter added in v0.9.0

type BatchCounter interface {
	// NumBatches returns the number of batches in one pass over the dataset. For a .jsonl file it
	// reads and parses the file once, without tokenizing, and leaves the current pass untouched.
	NumBatches() (int, error)
}

BatchCounter is implemented by the datasets that can say how many batches one pass over them yields. The trainer needs it to lay a learning-rate schedule over the whole run; see hugot.WithLearningRateSchedule.

type ClassificationProblem added in v0.8.4

type ClassificationProblem int

ClassificationProblem says whether each example has exactly one label or any number of them.

const (
	// SingleLabel examples have exactly one label each, set in TextClassificationExample.Label.
	// Training uses softmax cross-entropy.
	SingleLabel ClassificationProblem = iota
	// MultiLabel examples have any number of labels each, set in TextClassificationExample.Labels.
	// Training uses sigmoid (binary) cross-entropy per label.
	MultiLabel
)

func (ClassificationProblem) String added in v0.8.4

func (p ClassificationProblem) String() string

type ContrastiveDataset added in v0.8.4

type ContrastiveDataset struct {
	train.Dataset
	// contains filtered or unexported fields
}

ContrastiveDataset is a dataset for fine-tuning a feature extraction (embedding) pipeline with in-batch negatives, the multiple negatives ranking loss of sentence-transformers.

Within a batch, each anchor must pick out its own positive among all the positives of the batch (and all its hard negatives, if the examples have them). Only matching pairs are needed, no similarity scores. Larger batches give more negatives and usually better embeddings. Two examples in one batch whose positives both fit the other's anchor are taught to differ, so avoid duplicate or near-duplicate pairs within a batch.

func NewContrastiveDataset added in v0.8.4

func NewContrastiveDataset(ctx context.Context, trainingPath string, batchSize int, preprocessFunc ContrastivePreprocessFunc, fs fileutil.FileSystem) (*ContrastiveDataset, error)

NewContrastiveDataset creates a ContrastiveDataset reading from a .jsonl file, where each line has the format:

{"anchor":"how do I reset my password?","positive":"To reset your password, open Settings…"}

with an optional "negative". Either every example has a negative or none does. batchSize must be at least 2, so each anchor has at least one other positive to tell its own apart from.

func NewInMemoryContrastiveDataset added in v0.8.4

func NewInMemoryContrastiveDataset(examples []ContrastiveExample, batchSize int, preprocessFunc ContrastivePreprocessFunc) (*ContrastiveDataset, error)

NewInMemoryContrastiveDataset creates a ContrastiveDataset from a slice of examples.

func (*ContrastiveDataset) Close added in v0.8.4

func (s *ContrastiveDataset) Close() error

func (*ContrastiveDataset) Examples added in v0.8.4

func (s *ContrastiveDataset) Examples() ([]ContrastiveExample, error)

Examples reads the whole dataset and returns its examples, preprocessed if a preprocessing function was given. It rewinds the dataset first.

func (*ContrastiveDataset) Iter added in v0.8.4

Iter returns an iterator over the dataset. The examples are tokenized and converted to tensors for the training process.

func (*ContrastiveDataset) Name added in v0.8.4

func (s *ContrastiveDataset) Name() string

func (*ContrastiveDataset) NumBatches added in v0.9.0

func (s *ContrastiveDataset) NumBatches() (int, error)

NumBatches returns the number of batches in one pass over the dataset. See BatchCounter.

func (*ContrastiveDataset) Reset added in v0.8.4

func (s *ContrastiveDataset) Reset()

Reset resets the dataset to the beginning of the training data (after the epoch is done).

func (*ContrastiveDataset) SetShuffle added in v0.9.0

func (s *ContrastiveDataset) SetShuffle(seed uint64)

SetShuffle makes each pass over the dataset visit the examples in a new random order, drawn from seed. See Shuffler.

func (*ContrastiveDataset) SetTokenizationPipeline added in v0.8.4

func (s *ContrastiveDataset) SetTokenizationPipeline(pipeline backends.Pipeline) error

SetTokenizationPipeline sets the pipeline whose tokenizer the dataset uses.

func (*ContrastiveDataset) SetVerbose added in v0.8.4

func (s *ContrastiveDataset) SetVerbose(v bool)

func (*ContrastiveDataset) Validate added in v0.8.4

func (s *ContrastiveDataset) Validate() error

func (*ContrastiveDataset) YieldRaw added in v0.8.4

func (s *ContrastiveDataset) YieldRaw() ([]ContrastiveExample, error)

YieldRaw returns the next raw batch of examples from the dataset, preprocessed if a preprocessing function was given. It returns io.EOF, possibly with a final partial batch, at the end of the data.

type ContrastiveExample added in v0.8.4

type ContrastiveExample struct {
	Data     map[string]any `json:"-"`                  // to store any additional data for the example. Not used by the dataset.
	Anchor   string         `json:"anchor"`             // e.g. a query
	Positive string         `json:"positive"`           // the text that matches the anchor
	Negative string         `json:"negative,omitempty"` // an optional hard negative
}

ContrastiveExample is a single example for the contrastive dataset: an anchor (e.g. a query), a positive that matches it (e.g. the passage that answers it), and optionally a hard negative that looks related but does not match.

type ContrastivePreprocessFunc added in v0.8.4

type ContrastivePreprocessFunc func([]ContrastiveExample) ([]ContrastiveExample, error)

ContrastivePreprocessFunc can apply any custom preprocessing to a batch of examples before they are tokenized.

type Dataset

type Dataset interface {
	train.Dataset
	Validate() error
	SetTokenizationPipeline(pipeline backends.Pipeline) error
	SetVerbose(bool)
	Close() error
}

type EntitySpan added in v0.8.4

type EntitySpan struct {
	Label string `json:"label"`
	Start int    `json:"start"`
	End   int    `json:"end"`
}

EntitySpan is an entity annotated by character offsets into an example's Text, as exported by span-based annotation tools such as Prodigy (ner_manual). Start and End count characters (Unicode code points, as Python does), not bytes; End is exclusive.

type ExamplePreprocessFunc added in v0.3.5

type ExamplePreprocessFunc func([]SemanticSimilarityExample) ([]SemanticSimilarityExample, error)

ExamplePreprocessFunc can apply any custom preprocessing to a batch of examples before they are tokenized.

type SemanticSimilarityDataset

type SemanticSimilarityDataset struct {
	train.Dataset
	// contains filtered or unexported fields
}

SemanticSimilarityDataset is a dataset for fine-tuning a feature extraction pipeline for textual semantic similarity.

func NewInMemorySemanticSimilarityDataset added in v0.3.5

func NewInMemorySemanticSimilarityDataset(examples []SemanticSimilarityExample, batchSize int, preprocessFunc ExamplePreprocessFunc) (*SemanticSimilarityDataset, error)

NewInMemorySemanticSimilarityDataset creates a new SemanticSimilarityDataset in memory from a slice of examples. preprocessFunc here must be a function that takes a slice of SemanticSimilarityExample and returns a slice of SemanticSimilarityExample. This function can be used to apply any custom preprocessing to the example batch before they are passed to the model.

func NewSemanticSimilarityDataset added in v0.3.5

func NewSemanticSimilarityDataset(ctx context.Context, trainingPath string, batchSize int, preprocessFunc ExamplePreprocessFunc, fs fileutil.FileSystem) (*SemanticSimilarityDataset, error)

NewSemanticSimilarityDataset creates a new SemanticSimilarityDataset. The trainingPath must be a .jsonl file where each line has the following format: {"sentence1":"A plane is taking off.","sentence2":"An air plane is taking off.","score":1.0} The score is a float value between 0 and 1. preprocessFunc here must be a function that takes a slice of SemanticSimilarityExample and returns a slice of SemanticSimilarityExample. This function can be used to apply any custom preprocessing to the example batch before they are passed to the model.

func (*SemanticSimilarityDataset) Close added in v0.3.5

func (s *SemanticSimilarityDataset) Close() error

func (*SemanticSimilarityDataset) Examples added in v0.9.0

Examples reads the whole dataset and returns its examples, preprocessed if a preprocessing function was given. It rewinds the dataset first.

func (*SemanticSimilarityDataset) Iter added in v0.7.6

Iter returns an iterator over the dataset. The examples are tokenized and converted to tensors for the training process.

func (*SemanticSimilarityDataset) Name added in v0.7.6

func (*SemanticSimilarityDataset) NumBatches added in v0.9.0

func (s *SemanticSimilarityDataset) NumBatches() (int, error)

NumBatches returns the number of batches in one pass over the dataset. See BatchCounter.

func (*SemanticSimilarityDataset) Reset added in v0.3.5

func (s *SemanticSimilarityDataset) Reset()

Reset resets the dataset to the beginning of the training data (after the epoch is done).

func (*SemanticSimilarityDataset) SetShuffle added in v0.9.0

func (s *SemanticSimilarityDataset) SetShuffle(seed uint64)

SetShuffle makes each pass over the dataset visit the examples in a new random order, drawn from seed. See Shuffler.

func (*SemanticSimilarityDataset) SetTokenizationPipeline

func (s *SemanticSimilarityDataset) SetTokenizationPipeline(pipeline backends.Pipeline) error

func (*SemanticSimilarityDataset) SetVerbose

func (s *SemanticSimilarityDataset) SetVerbose(v bool)

func (*SemanticSimilarityDataset) Validate added in v0.3.5

func (s *SemanticSimilarityDataset) Validate() error

func (*SemanticSimilarityDataset) YieldRaw added in v0.3.5

YieldRaw returns the next raw batch of examples from the dataset, preprocessed if a preprocessing function was given. It returns io.EOF, possibly with a final partial batch, at the end of the data.

type SemanticSimilarityExample added in v0.3.5

type SemanticSimilarityExample struct {
	Data      map[string]any // to store any additional data for the example. Not used by the dataset.
	Sentence1 string         `json:"sentence1"`
	Sentence2 string         `json:"sentence2"`
	Score     float32        `json:"score"`
}

SemanticSimilarityExample is a single example for the semantic similarity dataset.

type Shuffler added in v0.9.0

type Shuffler interface {
	// SetShuffle makes each pass over the dataset visit the examples in a new random order, drawn
	// from seed: the same seed gives the same sequence of orders. Examples read with Examples are
	// always in their original order.
	SetShuffle(seed uint64)
}

Shuffler is implemented by the datasets that can visit their examples in a random order. The trainer shuffles its training dataset through it; see hugot.WithSeed and hugot.WithoutShuffle.

type SourceToken added in v0.8.4

type SourceToken struct {
	Text  string `json:"text"`
	Start int    `json:"start"`
	End   int    `json:"end"`
}

SourceToken is a token of an example's Text as the annotation tool split it (Prodigy's "tokens"), with character offsets like EntitySpan.

type TextClassificationDataset added in v0.8.4

type TextClassificationDataset struct {
	train.Dataset
	// contains filtered or unexported fields
}

TextClassificationDataset is a dataset for fine-tuning a text classification pipeline.

func NewInMemoryTextClassificationDataset added in v0.8.4

func NewInMemoryTextClassificationDataset(examples []TextClassificationExample, batchSize int, problem ClassificationProblem, preprocessFunc TextClassificationPreprocessFunc) (*TextClassificationDataset, error)

NewInMemoryTextClassificationDataset creates a TextClassificationDataset from a slice of examples.

func NewTextClassificationDataset added in v0.8.4

func NewTextClassificationDataset(ctx context.Context, trainingPath string, batchSize int, problem ClassificationProblem, preprocessFunc TextClassificationPreprocessFunc, fs fileutil.FileSystem) (*TextClassificationDataset, error)

NewTextClassificationDataset creates a TextClassificationDataset reading from a .jsonl file. For a SingleLabel dataset each line has the format:

{"text":"The film was a delight.","label":"POSITIVE"}

and for a MultiLabel dataset:

{"text":"Late, and the wrong size.","labels":["delivery","sizing"]}

Prodigy exports are read as well, and can be mixed with the lines above. A choice annotation (textcat.manual with several labels) gives the chosen labels, exactly one for a SingleLabel dataset:

{"text":"Late, and the wrong size.","accept":["delivery","sizing"],"answer":"accept"}

A binary annotation (textcat.manual with one label, or textcat.teach) says whether one label applies:

{"text":"The film was a delight.","label":"NEGATIVE","answer":"reject"}

Accepting a label makes it the class of a SingleLabel example. Rejecting one only says the text is not that class, which is a full label for a two-class model (the other class) and is skipped otherwise. A MultiLabel dataset can use binary annotations only when the model has that single label, since the other labels are unknown. Examples answered "ignore", and rejected choice annotations, are skipped.

Label names must exist in the id2label map of the model being trained. preprocessFunc, if not nil, is applied to each batch of examples before tokenization.

func (*TextClassificationDataset) Close added in v0.8.4

func (s *TextClassificationDataset) Close() error

func (*TextClassificationDataset) Examples added in v0.8.4

Examples reads the whole dataset and returns its examples, preprocessed if a preprocessing function was given. It rewinds the dataset first.

func (*TextClassificationDataset) Iter added in v0.8.4

Iter returns an iterator over the dataset. The examples are tokenized and converted to tensors for the training process.

func (*TextClassificationDataset) Name added in v0.8.4

func (*TextClassificationDataset) NumBatches added in v0.9.0

func (s *TextClassificationDataset) NumBatches() (int, error)

NumBatches returns the number of batches in one pass over the dataset. See BatchCounter.

func (*TextClassificationDataset) Problem added in v0.8.4

Problem reports whether the dataset is single-label or multi-label.

func (*TextClassificationDataset) Reset added in v0.8.4

func (s *TextClassificationDataset) Reset()

Reset resets the dataset to the beginning of the training data (after the epoch is done).

func (*TextClassificationDataset) SetShuffle added in v0.9.0

func (s *TextClassificationDataset) SetShuffle(seed uint64)

SetShuffle makes each pass over the dataset visit the examples in a new random order, drawn from seed. See Shuffler.

func (*TextClassificationDataset) SetTokenizationPipeline added in v0.8.4

func (s *TextClassificationDataset) SetTokenizationPipeline(pipeline backends.Pipeline) error

SetTokenizationPipeline sets the pipeline whose tokenizer and id2label map the dataset uses.

func (*TextClassificationDataset) SetVerbose added in v0.8.4

func (s *TextClassificationDataset) SetVerbose(v bool)

func (*TextClassificationDataset) Validate added in v0.8.4

func (s *TextClassificationDataset) Validate() error

func (*TextClassificationDataset) YieldRaw added in v0.8.4

YieldRaw returns the next raw batch of examples from the dataset, preprocessed if a preprocessing function was given. It returns io.EOF, possibly with a final partial batch, at the end of the data.

type TextClassificationExample added in v0.8.4

type TextClassificationExample struct {
	Data   map[string]any `json:"-"`                // to store any additional data for the example. Not used by the dataset.
	Text   string         `json:"text"`             // the input text
	Label  string         `json:"label,omitempty"`  // the label, for a SingleLabel dataset
	Labels []string       `json:"labels,omitempty"` // the labels, for a MultiLabel dataset; may be empty
	// Accept holds the labels chosen in a choice annotation (Prodigy textcat.manual). A non-nil
	// empty slice is a choice annotation with no label chosen.
	Accept []string `json:"accept,omitempty"`
	// Answer is the annotation answer: "accept", "reject" or "ignore". With a single Label it is a
	// binary annotation of whether that label applies.
	Answer string `json:"answer,omitempty"`
}

TextClassificationExample is a single example for the text classification dataset. Labels are given by name, and must be names in the model's id2label map.

Examples exported by Prodigy are read too: choice annotations give their labels in Accept, and binary annotations give one Label with an Answer. See TextClassificationExample.IsChoiceFormat.

func (TextClassificationExample) IsChoiceFormat added in v0.8.4

func (e TextClassificationExample) IsChoiceFormat() bool

IsChoiceFormat reports whether the example is a choice annotation, with its labels in Accept.

func (TextClassificationExample) Resolve added in v0.8.4

func (e TextClassificationExample) Resolve(problem ClassificationProblem, labels []string) (resolved TextClassificationExample, keep bool, err error)

Resolve returns the example in the dataset's own form, Label or Labels set from a Prodigy annotation if it is one, or keep false if the example should be skipped. labels are the model's labels.

type TextClassificationPreprocessFunc added in v0.8.4

type TextClassificationPreprocessFunc func([]TextClassificationExample) ([]TextClassificationExample, error)

TextClassificationPreprocessFunc can apply any custom preprocessing to a batch of examples before they are tokenized.

type TokenClassificationDataset added in v0.8.4

type TokenClassificationDataset struct {
	train.Dataset
	// contains filtered or unexported fields
}

TokenClassificationDataset is a dataset for fine-tuning a token classification (e.g. NER) pipeline.

Examples are word-level, but the model labels sub-word tokens. The words of each example are joined with single spaces and tokenized, and each word's tag is assigned to its first token. The remaining tokens of a word, the special tokens and the padding are masked out of the loss and the accuracy, which is the usual approach for fine-tuning NER models.

func NewInMemoryTokenClassificationDataset added in v0.8.4

func NewInMemoryTokenClassificationDataset(examples []TokenClassificationExample, batchSize int, preprocessFunc TokenClassificationPreprocessFunc) (*TokenClassificationDataset, error)

NewInMemoryTokenClassificationDataset creates a TokenClassificationDataset from a slice of examples.

func NewTokenClassificationDataset added in v0.8.4

func NewTokenClassificationDataset(ctx context.Context, trainingPath string, batchSize int, preprocessFunc TokenClassificationPreprocessFunc, fs fileutil.FileSystem) (*TokenClassificationDataset, error)

NewTokenClassificationDataset creates a TokenClassificationDataset reading from a .jsonl file, where each line has the format:

{"tokens":["EU","rejects","German","call"],"tags":["B-ORG","O","B-MISC","O"]}

or, when the pipeline has a word splitter, with the raw text in place of the tokens:

{"text":"EU rejects German call","tags":["B-ORG","O","B-MISC","O"]}

or as character spans, in the format Prodigy exports (ner_manual); examples whose "answer" is not "accept" are skipped:

{"text":"EU rejects German call","spans":[{"start":0,"end":2,"label":"ORG"}],"answer":"accept"}

preprocessFunc, if not nil, is applied to each batch of examples before tokenization.

func (*TokenClassificationDataset) Close added in v0.8.4

func (s *TokenClassificationDataset) Close() error

func (*TokenClassificationDataset) Examples added in v0.8.4

Examples reads the whole dataset and returns its examples, preprocessed if a preprocessing function was given. It rewinds the dataset first.

func (*TokenClassificationDataset) Iter added in v0.8.4

Iter returns an iterator over the dataset. The examples are tokenized and converted to tensors for the training process.

func (*TokenClassificationDataset) Name added in v0.8.4

func (*TokenClassificationDataset) NumBatches added in v0.9.0

func (s *TokenClassificationDataset) NumBatches() (int, error)

NumBatches returns the number of batches in one pass over the dataset. See BatchCounter.

func (*TokenClassificationDataset) Reset added in v0.8.4

func (s *TokenClassificationDataset) Reset()

Reset resets the dataset to the beginning of the training data (after the epoch is done).

func (*TokenClassificationDataset) SetShuffle added in v0.9.0

func (s *TokenClassificationDataset) SetShuffle(seed uint64)

SetShuffle makes each pass over the dataset visit the examples in a new random order, drawn from seed. See Shuffler.

func (*TokenClassificationDataset) SetTokenizationPipeline added in v0.8.4

func (s *TokenClassificationDataset) SetTokenizationPipeline(pipeline backends.Pipeline) error

SetTokenizationPipeline sets the pipeline whose tokenizer and id2label map the dataset uses.

func (*TokenClassificationDataset) SetVerbose added in v0.8.4

func (s *TokenClassificationDataset) SetVerbose(v bool)

func (*TokenClassificationDataset) Validate added in v0.8.4

func (s *TokenClassificationDataset) Validate() error

func (*TokenClassificationDataset) YieldRaw added in v0.8.4

YieldRaw returns the next raw batch of examples from the dataset, preprocessed if a preprocessing function was given. It returns io.EOF, possibly with a final partial batch, at the end of the data.

type TokenClassificationExample added in v0.8.4

type TokenClassificationExample struct {
	Data   map[string]any `json:"-"`              // to store any additional data for the example. Not used by the dataset.
	Text   string         `json:"text,omitempty"` // the raw sentence, split by the pipeline's word splitter
	Tokens []string       `json:"tokens"`         // the words of the sentence
	Tags   []string       `json:"tags"`           // one tag per word
	// Spans are the entities as character offsets into Text, instead of Tags. An empty, non-nil
	// slice is an annotated example with no entities.
	Spans []EntitySpan `json:"spans,omitempty"`
	// SourceTokens are the annotation tool's tokens of Text, used as the words when the pipeline
	// has no word splitter.
	SourceTokens []SourceToken `json:"-"`
	// Answer is the annotation answer; examples answered other than "accept" are skipped.
	Answer string `json:"answer,omitempty"`
}

TokenClassificationExample is a single example for the token classification dataset: a sentence split into words, and one tag per word. Tags are given by name, and must be names in the model's id2label map (for NER usually IOB tags such as "B-PER", "I-PER" and "O").

The words are given either directly as Tokens, or as raw Text that the pipeline's word splitter (pipelines.WithWordSplitter) splits, which guarantees training splits text exactly as inference will. If both are given, the splitter's words must equal Tokens.

Alternatively the entities are given as character Spans of Text, as span-based annotation tools such as Prodigy export them; see TokenClassificationExample.Resolve for how they become word tags.

func (TokenClassificationExample) IsAccepted added in v0.8.4

func (e TokenClassificationExample) IsAccepted() bool

IsAccepted reports whether the example should be trained on: it has no annotation answer, or the answer is "accept".

func (TokenClassificationExample) IsSpanFormat added in v0.8.4

func (e TokenClassificationExample) IsSpanFormat() bool

IsSpanFormat reports whether the example is annotated with character spans rather than word tags.

func (TokenClassificationExample) Resolve added in v0.8.4

func (e TokenClassificationExample) Resolve(pipeline *pipelines.TokenClassificationPipeline) (words, tags []string, err error)

Resolve returns the example's words and one tag per word.

Word-level examples give their tags directly, and their words as Tokens or as Text split by the pipeline's word splitter. Span-based examples are converted: the words are the pipeline's word splitter applied to Text when it has one, otherwise the annotation tool's SourceTokens; each span must start and end on word boundaries, and becomes IOB tags (B-LABEL on its first word, I-LABEL on the rest, O elsewhere).

func (*TokenClassificationExample) UnmarshalJSON added in v0.8.4

func (e *TokenClassificationExample) UnmarshalJSON(data []byte) error

UnmarshalJSON reads both example formats. Word-level lines give "tokens" as a list of words; span-based lines (Prodigy) give "tokens" as a list of objects with offsets, and "spans".

func (TokenClassificationExample) Words added in v0.8.4

Words returns the example's words: Text split by the pipeline's word splitter when Text is set, otherwise Tokens. For a span-annotated example they are the words TokenClassificationExample.Resolve tags.

type TokenClassificationPreprocessFunc added in v0.8.4

type TokenClassificationPreprocessFunc func([]TokenClassificationExample) ([]TokenClassificationExample, error)

TokenClassificationPreprocessFunc can apply any custom preprocessing to a batch of examples before they are tokenized.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL