Table of Contents

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

T

The numeric type used for calculations.

Inheritance
Wav2Vec2LanguageIdentifier<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
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

architecture NeuralNetworkArchitecture<T>

Neural network architecture configuration.

supportedLanguages IReadOnlyList<string>

List of language codes to identify.

options Wav2Vec2LidOptions

Wav2Vec2 LID options.

optimizer IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training.

lossFunction ILossFunction<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

architecture NeuralNetworkArchitecture<T>

Neural network architecture configuration.

modelPath string

Path to the ONNX model file.

options Wav2Vec2LidOptions

Wav2Vec2 LID options.

Properties

HiddenSize

Gets the hidden size of the transformer.

public int HiddenSize { get; }

Property Value

int

SupportedLanguages

Gets the list of languages this model can identify.

public IReadOnlyList<string> SupportedLanguages { get; }

Property Value

IReadOnlyList<string>

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

bool

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

audio1 Tensor<T>

First audio sample.

audio2 Tensor<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

reader BinaryReader

The 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

languageCode string

ISO 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

audio Tensor<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

audio Tensor<T>

Audio tensor containing speech.

topN int

Number 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

audio Tensor<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

audio Tensor<T>

Audio tensor that may contain multiple languages.

windowSizeMs int

Analysis 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

modelOutput Tensor<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

input Tensor<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

rawAudio Tensor<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

writer BinaryWriter

The 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

input Tensor<T>

The input data.

expectedOutput Tensor<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:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. 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

parameters Vector<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.