Table of Contents

Class PANNsModel<T>

Namespace
AiDotNet.Audio.Fingerprinting
Assembly
AiDotNet.dll

PANNs (Pretrained Audio Neural Networks) - Large-scale pretrained CNN models for audio pattern recognition.

public class PANNsModel<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

T

The numeric type used for calculations.

Inheritance
PANNsModel<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

PANNs are convolutional neural networks pretrained on AudioSet (2 million audio clips, 527 classes). They provide state-of-the-art audio embeddings that can be used for:

  • Audio tagging (multi-label classification)
  • Sound event detection (localization in time)
  • Audio fingerprinting and retrieval
  • Transfer learning for custom audio tasks

For Beginners: PANNs are like ImageNet-pretrained models but for audio!

Just as image models can recognize cats, dogs, and cars after seeing millions of images, PANNs can recognize 527 different sounds after hearing 2 million audio clips:

  • Musical instruments (piano, guitar, drums)
  • Human sounds (speech, laughter, coughing)
  • Environmental sounds (rain, thunder, traffic)
  • Animal sounds (dog bark, bird song)
  • And many more!

Use cases:

  • "What sounds are in this audio?" (audio tagging)
  • "When does the dog bark?" (sound event detection)
  • "Find similar sounding audio" (audio retrieval)
  • Build custom sound classifiers with less training data

Reference: Kong, Q., et al. (2020). PANNs: Large-Scale Pretrained Audio Neural Networks for Audio Pattern Recognition.

Constructors

PANNsModel(NeuralNetworkArchitecture<T>, int, PANNsArchitecture, int, int, int, int, int, double, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Initializes a new instance of the PANNsModel<T> class for native training mode.

public PANNsModel(NeuralNetworkArchitecture<T> architecture, int sampleRate = 32000, PANNsArchitecture architectureType = PANNsArchitecture.Cnn14, int numClasses = 527, int embeddingDim = 2048, int numMelBands = 64, int windowSize = 1024, int hopSize = 320, double dropout = 0.2, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

sampleRate int

Sample rate of input audio (default: 32000 Hz).

architectureType PANNsArchitecture

CNN architecture variant (default: Cnn14).

numClasses int

Number of output classes (default: 527 for AudioSet).

embeddingDim int

Embedding dimension (default: 2048).

numMelBands int

Number of mel spectrogram bands (default: 64).

windowSize int

STFT window size (default: 1024).

hopSize int

STFT hop size (default: 320).

dropout double

Dropout rate (default: 0.2).

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

Optimizer for training. If null, a default Adam optimizer is used.

lossFunction ILossFunction<T>

Loss function. If null, BCE loss is used for multi-label.

PANNsModel(NeuralNetworkArchitecture<T>, string, int, int, int, OnnxModelOptions?)

Initializes a new instance of the PANNsModel<T> class for ONNX inference mode.

public PANNsModel(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 32000, int numClasses = 527, int embeddingDim = 2048, OnnxModelOptions? onnxOptions = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

modelPath string

Path to the ONNX model file.

sampleRate int

Sample rate of input audio (default: 32000 Hz).

numClasses int

Number of output classes (default: 527 for AudioSet).

embeddingDim int

Embedding dimension (default: 2048).

onnxOptions OnnxModelOptions

Optional ONNX model options.

Exceptions

FileNotFoundException

Thrown when the ONNX model file is not found.

Properties

ArchitectureType

Gets the architecture type.

public PANNsArchitecture ArchitectureType { get; }

Property Value

PANNsArchitecture

EmbeddingDimension

Gets the embedding dimension.

public int EmbeddingDimension { get; }

Property Value

int

FingerprintLength

Gets the fingerprint length in bits or elements.

public int FingerprintLength { get; }

Property Value

int

Name

Gets the name of the fingerprinting algorithm.

public string Name { get; }

Property Value

string

NumClasses

Gets the number of output classes (527 for AudioSet).

public int NumClasses { get; }

Property Value

int

Methods

Classify(Tensor<T>, double)

Classifies audio into AudioSet categories.

public Dictionary<string, double> Classify(Tensor<T> audio, double threshold = 0.5)

Parameters

audio Tensor<T>

Audio tensor to classify.

threshold double

Probability threshold for positive labels (default: 0.5).

Returns

Dictionary<string, double>

Dictionary of label to probability for labels above threshold.

ComputeSimilarity(AudioFingerprint<T>, AudioFingerprint<T>)

Computes the similarity between two fingerprints.

public double ComputeSimilarity(AudioFingerprint<T> fp1, AudioFingerprint<T> fp2)

Parameters

fp1 AudioFingerprint<T>

First fingerprint.

fp2 AudioFingerprint<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

data byte[]

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

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.

ExtractEmbedding(Tensor<T>)

Extracts audio embedding.

public Tensor<T> ExtractEmbedding(Tensor<T> audio)

Parameters

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

query AudioFingerprint<T>

The query fingerprint.

reference AudioFingerprint<T>

The reference fingerprint to search in.

minMatchLength int

Minimum 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

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

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

GetTopK(Tensor<T>, int)

Gets top-k predictions.

public List<(string Label, double Probability)> GetTopK(Tensor<T> audio, int k = 5)

Parameters

audio Tensor<T>

Audio tensor to classify.

k int

Number of top predictions to return.

Returns

List<(string Label, double Confidence)>

Top-k predictions with probabilities.

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

modelOutput Tensor<T>

Returns

Tensor<T>

Predict(Tensor<T>)

Predicts audio class logits.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

Returns

Tensor<T>

PreprocessAudio(Tensor<T>)

Preprocesses raw audio waveform for model input.

protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)

Parameters

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

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 model on audio-label pairs.

public override void Train(Tensor<T> input, Tensor<T> expected)

Parameters

input Tensor<T>
expected Tensor<T>

Remarks

Note: Full training from scratch is not yet implemented. PANNs models are designed to be used as pre-trained feature extractors. For best results: - Use ONNX mode with pre-trained weights for inference - Fine-tune only the final classification layers if needed

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> gradients)

Parameters

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