Class ECAPATDNNLanguageIdentifier<T>
- Namespace
- AiDotNet.Audio.LanguageIdentification
- Assembly
- AiDotNet.dll
ECAPA-TDNN (Emphasized Channel Attention, Propagation and Aggregation Time Delay Neural Network) for spoken language identification.
public class ECAPATDNNLanguageIdentifier<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
-
ECAPATDNNLanguageIdentifier<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
ECAPA-TDNN is a state-of-the-art architecture originally designed for speaker verification that has been adapted for language identification. It uses: - Time Delay Neural Network (TDNN) layers with dilated convolutions - Squeeze-Excitation (SE) blocks for channel attention - Multi-layer feature aggregation (MFA) for combining information across layers - Attentive statistics pooling for variable-length utterances
For Beginners: ECAPA-TDNN is like having a very sophisticated listener that can: 1. Hear patterns at different time scales (TDNN layers) 2. Focus on the most important sound characteristics (channel attention) 3. Combine information from multiple processing stages (MFA) 4. Handle audio of any length (attentive pooling)
This model is particularly good at:
- Identifying languages from short audio clips (3-10 seconds)
- Handling noisy or low-quality audio
- Distinguishing between similar languages (e.g., Spanish vs Portuguese)
Example usage:
var model = new ECAPATDNNLanguageIdentifier<float>(new ECAPATDNNOptions
{
SampleRate = 16000,
ModelPath = "ecapa_tdnn_lid.onnx"
});
var result = model.IdentifyLanguage(audioTensor);
Console.WriteLine($"Detected: {result.LanguageName} ({result.Confidence:P0})");
Constructors
ECAPATDNNLanguageIdentifier(NeuralNetworkArchitecture<T>, IReadOnlyList<string>, ECAPATDNNOptions?, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates an ECAPA-TDNN language identifier for native training.
public ECAPATDNNLanguageIdentifier(NeuralNetworkArchitecture<T> architecture, IReadOnlyList<string> supportedLanguages, ECAPATDNNOptions? 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 (e.g., ["en", "es", "fr"]).
optionsECAPATDNNOptionsECAPA-TDNN options.
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimizer for training. If null, Adam is used.
lossFunctionILossFunction<T>Loss function. If null, CrossEntropy is used.
ECAPATDNNLanguageIdentifier(NeuralNetworkArchitecture<T>, string, ECAPATDNNOptions?)
Creates an ECAPA-TDNN language identifier with ONNX model for inference.
public ECAPATDNNLanguageIdentifier(NeuralNetworkArchitecture<T> architecture, string modelPath, ECAPATDNNOptions? options = null)
Parameters
architectureNeuralNetworkArchitecture<T>Neural network architecture configuration.
modelPathstringPath to the ONNX model file.
optionsECAPATDNNOptionsLanguage identifier options.
Properties
EmbeddingDimension
Gets the embedding dimension produced by this model.
public int EmbeddingDimension { 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.