Class Wav2Vec2LanguageIdentifier<T>
- Namespace
- AiDotNet.Audio.LanguageIdentification
- Assembly
- AiDotNet.dll
Wav2Vec2 model fine-tuned for spoken language identification.
public class Wav2Vec2LanguageIdentifier<T> : AudioNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, ILanguageIdentifier<T>
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
Wav2Vec2LanguageIdentifier<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
Wav2Vec2 is Meta's self-supervised speech representation learning model that learns powerful representations directly from raw audio waveforms. When fine-tuned for language identification, it achieves state-of-the-art performance on many benchmarks.
Architecture overview: - Feature Encoder: 7 temporal convolution layers that process raw waveform - Transformer Encoder: 12-24 transformer blocks for contextual representations - Classification Head: Linear projection to language classes
For Beginners: Wav2Vec2 is like a very attentive listener that: 1. First breaks down the raw sound wave into small pieces (feature encoder) 2. Then looks at how all these pieces relate to each other (transformer) 3. Finally makes a decision about what language is being spoken (classifier)
Key advantages:
- Works directly on raw audio (no need for handcrafted features like MFCCs)
- Pre-trained on massive amounts of unlabeled speech data
- Can recognize languages even with limited labeled training data
Example usage:
var model = new Wav2Vec2LanguageIdentifier<float>(architecture, "wav2vec2_lid.onnx");
var result = model.IdentifyLanguage(audioTensor);
Console.WriteLine($"Language: {result.LanguageName}");
Constructors
Wav2Vec2LanguageIdentifier(NeuralNetworkArchitecture<T>, IReadOnlyList<string>, Wav2Vec2LidOptions?, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates a Wav2Vec2 language identifier for native training.
public Wav2Vec2LanguageIdentifier(NeuralNetworkArchitecture<T> architecture, IReadOnlyList<string> supportedLanguages, Wav2Vec2LidOptions? options = null, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>Neural network architecture configuration.
supportedLanguagesIReadOnlyList<string>List of language codes to identify.
optionsWav2Vec2LidOptionsWav2Vec2 LID options.
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimizer for training.
lossFunctionILossFunction<T>Loss function.
Wav2Vec2LanguageIdentifier(NeuralNetworkArchitecture<T>, string, Wav2Vec2LidOptions?)
Creates a Wav2Vec2 language identifier with ONNX model for inference.
public Wav2Vec2LanguageIdentifier(NeuralNetworkArchitecture<T> architecture, string modelPath, Wav2Vec2LidOptions? options = null)
Parameters
architectureNeuralNetworkArchitecture<T>Neural network architecture configuration.
modelPathstringPath to the ONNX model file.
optionsWav2Vec2LidOptionsWav2Vec2 LID options.
Properties
HiddenSize
Gets the hidden size of the transformer.
public int HiddenSize { get; }
Property Value
SupportedLanguages
Gets the list of languages this model can identify.
public IReadOnlyList<string> SupportedLanguages { get; }
Property Value
Remarks
Language codes typically follow ISO 639-1 (e.g., "en", "es", "zh") or ISO 639-3 for more specific variants.
SupportsTraining
Gets whether this network supports training.
public override bool SupportsTraining { get; }
Property Value
Remarks
In ONNX mode, training is not supported - the model is inference-only. In native mode, training is fully supported.
Methods
AreSameLanguage(Tensor<T>, Tensor<T>)
Checks if two audio samples are in the same language.
public (bool SameLanguage, T Confidence) AreSameLanguage(Tensor<T> audio1, Tensor<T> audio2)
Parameters
audio1Tensor<T>First audio sample.
audio2Tensor<T>Second audio sample.
Returns
- (bool SameLanguage, T Confidence)
True if same language, with confidence score.
CreateNewInstance()
Creates a new instance of the same type as this neural network.
protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()
Returns
- IFullModel<T, Tensor<T>, Tensor<T>>
A new instance of the same neural network type.
Remarks
For Beginners: This creates a blank version of the same type of neural network.
It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.
DeserializeNetworkSpecificData(BinaryReader)
Deserializes network-specific data that was not covered by the general deserialization process.
protected override void DeserializeNetworkSpecificData(BinaryReader reader)
Parameters
readerBinaryReaderThe BinaryReader to read the data from.
Remarks
This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.
For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.
GetLanguageDisplayName(string)
Gets the display name for a language code.
public string GetLanguageDisplayName(string languageCode)
Parameters
languageCodestringISO language code.
Returns
- string
Human-readable language name.
GetLanguageProbabilities(Tensor<T>)
Gets probabilities for all supported languages.
public IReadOnlyDictionary<string, T> GetLanguageProbabilities(Tensor<T> audio)
Parameters
audioTensor<T>Audio tensor containing speech.
Returns
- IReadOnlyDictionary<string, T>
Dictionary mapping language codes to probabilities.
GetModelMetadata()
Gets the metadata for this neural network model.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
GetTopLanguages(Tensor<T>, int)
Gets the top-N most likely languages.
public IReadOnlyList<(string Language, T Probability)> GetTopLanguages(Tensor<T> audio, int topN = 5)
Parameters
audioTensor<T>Audio tensor containing speech.
topNintNumber of languages to return.
Returns
- IReadOnlyList<(string Label, T Probability)>
List of (language, probability) pairs sorted by probability.
IdentifyLanguage(Tensor<T>)
Identifies the language spoken in audio.
public LanguageResult<T> IdentifyLanguage(Tensor<T> audio)
Parameters
audioTensor<T>Audio tensor containing speech.
Returns
- LanguageResult<T>
Detected language code and confidence.
IdentifyLanguageSegments(Tensor<T>, int)
Identifies language with time segmentation (for multilingual audio).
public IReadOnlyList<LanguageSegment<T>> IdentifyLanguageSegments(Tensor<T> audio, int windowSizeMs = 2000)
Parameters
audioTensor<T>Audio tensor that may contain multiple languages.
windowSizeMsintAnalysis window size in milliseconds.
Returns
- IReadOnlyList<LanguageSegment<T>>
Time-segmented language predictions.
Remarks
For Beginners: Use this when someone might switch languages mid-recording (code-switching). It tells you which language is spoken at each point in time.
InitializeLayers()
Initializes the layers of the neural network based on the architecture.
protected override void InitializeLayers()
Remarks
For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.
PostprocessOutput(Tensor<T>)
Postprocesses model output into the final result format.
protected override Tensor<T> PostprocessOutput(Tensor<T> modelOutput)
Parameters
modelOutputTensor<T>Raw output from the model.
Returns
- Tensor<T>
Postprocessed output in the expected format.
Predict(Tensor<T>)
Makes a prediction using the neural network.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>The input data to process.
Returns
- Tensor<T>
The network's prediction.
Remarks
For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).
PreprocessAudio(Tensor<T>)
Preprocesses raw audio for model input.
protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)
Parameters
rawAudioTensor<T>Raw audio waveform tensor [samples] or [batch, samples].
Returns
- Tensor<T>
Preprocessed audio features suitable for model input.
Remarks
For Beginners: Raw audio is just a series of numbers representing sound pressure. Neural networks often work better with transformed representations like mel spectrograms. This method converts raw audio into the format the model expects.
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe BinaryWriter to write the data to.
Remarks
This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.
For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.
Train(Tensor<T>, Tensor<T>)
Trains the neural network on a single input-output pair.
public override void Train(Tensor<T> input, Tensor<T> expectedOutput)
Parameters
inputTensor<T>The input data.
expectedOutputTensor<T>The expected output for the given input.
Remarks
This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.
For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)
The network then:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- Adjusts its internal values to do better next time
After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.
UpdateParameters(Vector<T>)
Updates the network's parameters with new values.
public override void UpdateParameters(Vector<T> parameters)
Parameters
parametersVector<T>The new parameter values to set.
Remarks
For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.
This is typically used by optimization algorithms that calculate better parameter values based on training data.