Class ASTModel<T>
- Namespace
- AiDotNet.Audio.Fingerprinting
- Assembly
- AiDotNet.dll
AST (Audio Spectrogram Transformer) - A pure attention-based model for audio classification.
public class ASTModel<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, IAudioFingerprinter<T>
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
ASTModel<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
The Audio Spectrogram Transformer applies Vision Transformer (ViT) architecture directly to audio spectrograms. It treats audio as a 2D image (time x frequency) and processes it using self-attention mechanisms, achieving state-of-the-art results on audio classification.
Key features:
- Pure attention-based architecture (no convolutions)
- Transfer learning from ImageNet-pretrained ViT
- Excellent for audio event detection and classification
- Captures long-range temporal dependencies
For Beginners: AST treats audio like an image and uses the same technology that powers modern image recognition!
How it works:
- Audio is converted to a spectrogram (a "picture" of sound frequencies over time)
- The spectrogram is divided into small patches (like puzzle pieces)
- Each patch is processed through attention layers that learn relationships
- The model predicts what sounds are present
Why it's powerful:
- Attention can capture patterns across the entire audio clip
- Benefits from decades of vision model research
- Highly accurate for both short and long audio
Use cases:
- Audio event detection (gunshot, glass breaking, baby crying)
- Environmental sound classification
- Music genre classification
- Speech command recognition
Reference: Gong, Y., Chung, Y. A., & Glass, J. (2021). AST: Audio Spectrogram Transformer.
Constructors
ASTModel(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, int, double, double, bool, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Initializes a new instance of the ASTModel<T> class for native training mode.
public ASTModel(NeuralNetworkArchitecture<T> architecture, int sampleRate = 16000, int numClasses = 527, int embeddingDim = 768, int numLayers = 12, int numHeads = 12, int patchSize = 16, int numMelBands = 128, int targetLength = 1024, double mlpRatio = 4, double dropout = 0, bool useDistillation = true, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>The neural network architecture defining input/output dimensions.
sampleRateintSample rate of input audio (default: 16000 Hz).
numClassesintNumber of output classes (default: 527 for AudioSet).
embeddingDimintEmbedding dimension (default: 768 for base model).
numLayersintNumber of transformer layers (default: 12).
numHeadsintNumber of attention heads (default: 12).
patchSizeintPatch size for embedding (default: 16).
numMelBandsintNumber of mel frequency bands (default: 128).
targetLengthintTarget spectrogram length in frames (default: 1024).
mlpRatiodoubleMLP hidden dimension ratio (default: 4.0).
dropoutdoubleDropout rate (default: 0.0).
useDistillationboolWhether to use knowledge distillation token (default: true).
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimizer for training. If null, a default Adam optimizer is used.
lossFunctionILossFunction<T>Loss function. If null, cross-entropy is used.
ASTModel(NeuralNetworkArchitecture<T>, string, int, int, int, OnnxModelOptions?)
Initializes a new instance of the ASTModel<T> class for ONNX inference mode.
public ASTModel(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 16000, int numClasses = 527, int embeddingDim = 768, OnnxModelOptions? onnxOptions = null)
Parameters
architectureNeuralNetworkArchitecture<T>The neural network architecture defining input/output dimensions.
modelPathstringPath to the ONNX model file.
sampleRateintSample rate of input audio (default: 16000 Hz).
numClassesintNumber of output classes (default: 527 for AudioSet).
embeddingDimintEmbedding dimension (default: 768).
onnxOptionsOnnxModelOptionsOptional ONNX model options.
Exceptions
- FileNotFoundException
Thrown when the ONNX model file is not found.
Properties
EmbeddingDimension
Gets the embedding dimension.
public int EmbeddingDimension { get; }
Property Value
FingerprintLength
Gets the fingerprint length in bits or elements.
public int FingerprintLength { get; }
Property Value
Name
Gets the name of the fingerprinting algorithm.
public string Name { get; }
Property Value
NumClasses
Gets the number of output classes.
public int NumClasses { get; }
Property Value
NumLayers
Gets the number of transformer layers.
public int NumLayers { get; }
Property Value
PatchSize
Gets the patch size used for embedding.
public int PatchSize { get; }
Property Value
Methods
Classify(Tensor<T>, int)
Classifies audio into categories.
public List<(string Label, double Probability)> Classify(Tensor<T> audio, int topK = 5)
Parameters
audioTensor<T>Audio tensor to classify.
topKintNumber of top predictions to return.
Returns
- List<(string Label, double Confidence)>
Top-k predictions with probabilities.
ComputeSimilarity(AudioFingerprint<T>, AudioFingerprint<T>)
Computes the similarity between two fingerprints.
public double ComputeSimilarity(AudioFingerprint<T> fp1, AudioFingerprint<T> fp2)
Parameters
fp1AudioFingerprint<T>First fingerprint.
fp2AudioFingerprint<T>Second fingerprint.
Returns
- double
Similarity score (0-1, higher is more similar).
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.
Deserialize(byte[])
Deserializes the neural network from a byte array.
public override void Deserialize(byte[] data)
Parameters
databyte[]The byte array containing the serialized neural network data.
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.
ExtractEmbedding(Tensor<T>)
Extracts audio embedding from the CLS token.
public Tensor<T> ExtractEmbedding(Tensor<T> audio)
Parameters
audioTensor<T>Audio tensor [samples] or [batch, samples].
Returns
- Tensor<T>
Audio embedding [batch, embeddingDim].
FindMatches(AudioFingerprint<T>, AudioFingerprint<T>, int)
Finds matching segments between two fingerprints.
public IReadOnlyList<FingerprintMatch> FindMatches(AudioFingerprint<T> query, AudioFingerprint<T> reference, int minMatchLength = 10)
Parameters
queryAudioFingerprint<T>The query fingerprint.
referenceAudioFingerprint<T>The reference fingerprint to search in.
minMatchLengthintMinimum length of matching segment.
Returns
- IReadOnlyList<FingerprintMatch>
List of matching segments with time offsets.
Fingerprint(Tensor<T>)
Generates a fingerprint from audio data.
public AudioFingerprint<T> Fingerprint(Tensor<T> audio)
Parameters
audioTensor<T>Audio samples as a tensor (mono audio).
Returns
- AudioFingerprint<T>
The audio fingerprint.
Fingerprint(Vector<T>)
Generates a fingerprint from audio data.
public AudioFingerprint<T> Fingerprint(Vector<T> audio)
Parameters
audioVector<T>Audio samples as a vector (mono audio).
Returns
- AudioFingerprint<T>
The audio fingerprint.
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.
InitializeLayers()
Initializes the neural network layers.
protected override void InitializeLayers()
PostprocessOutput(Tensor<T>)
Postprocesses model output.
protected override Tensor<T> PostprocessOutput(Tensor<T> modelOutput)
Parameters
modelOutputTensor<T>
Returns
- Tensor<T>
Predict(Tensor<T>)
Predicts classification logits.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>
Returns
- Tensor<T>
PreprocessAudio(Tensor<T>)
Preprocesses raw audio waveform for model input.
protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)
Parameters
rawAudioTensor<T>
Returns
- Tensor<T>
Serialize()
Serializes the neural network to a byte array.
public override byte[] Serialize()
Returns
- byte[]
A byte array representing the serialized neural network.
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 model on audio-label pairs.
public override void Train(Tensor<T> input, Tensor<T> expected)
Parameters
inputTensor<T>expectedTensor<T>
UpdateParameters(Vector<T>)
Updates the network's parameters with new values.
public override void UpdateParameters(Vector<T> gradients)
Parameters
gradientsVector<T>
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.