Class ConvTasNet<T>
- Namespace
- AiDotNet.Audio.Enhancement
- Assembly
- AiDotNet.dll
Conv-TasNet: A fully-convolutional time-domain audio separation network.
public class ConvTasNet<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, IAudioEnhancer<T>
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
ConvTasNet<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
Conv-TasNet (Convolutional Time-domain Audio Separation Network) is a pioneering neural network architecture that operates directly in the time domain, avoiding the phase reconstruction problems of frequency-domain methods.
The architecture consists of three main components:
- Encoder: Converts waveform to a learned representation using 1D convolutions
- Separator: Temporal Convolutional Network (TCN) that estimates source masks
- Decoder: Reconstructs separated waveforms from masked representations
For Beginners: Conv-TasNet is like having multiple microphones that each focus on one speaker in a noisy room. Give it a recording with multiple people talking, and it separates them into individual clean tracks!
Traditional methods convert audio to frequency domain, process it, then convert back. Conv-TasNet works directly on the waveform, which avoids problems with phase reconstruction and often produces cleaner results.
Common use cases:
- Separating speakers in meeting recordings
- Isolating vocals from music
- Removing background noise
- Speech enhancement for hearing aids
- Denoising phone calls
Reference: Luo, Y., & Mesgarani, N. (2019). Conv-TasNet: Surpassing Ideal Time-Frequency Magnitude Masking for Speech Separation.
Constructors
ConvTasNet(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, int, int, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Initializes a new instance of the ConvTasNet<T> class for native training mode.
public ConvTasNet(NeuralNetworkArchitecture<T> architecture, int sampleRate = 8000, int encoderDim = 512, int kernelSize = 16, int bottleneckDim = 128, int hiddenDim = 512, int numBlocks = 8, int numRepeats = 3, int tcnKernelSize = 3, int numSources = 2, 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: 8000 Hz for speech).
encoderDimintNumber of encoder basis functions (default: 512).
kernelSizeintEncoder kernel size in samples (default: 16, about 2ms at 8kHz).
bottleneckDimintBottleneck dimension in TCN (default: 128).
hiddenDimintHidden dimension in TCN blocks (default: 512).
numBlocksintNumber of TCN blocks per repeat (default: 8).
numRepeatsintNumber of TCN repeats (default: 3).
tcnKernelSizeintKernel size for TCN convolutions (default: 3).
numSourcesintNumber of sources to separate (default: 2).
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimizer for training. If null, a default Adam optimizer is used.
lossFunctionILossFunction<T>Loss function. If null, SI-SNR loss is used.
ConvTasNet(NeuralNetworkArchitecture<T>, string, int, int, int, int, OnnxModelOptions?)
Initializes a new instance of the ConvTasNet<T> class for ONNX inference mode.
public ConvTasNet(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 8000, int encoderDim = 512, int kernelSize = 16, int numSources = 2, 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: 8000 Hz).
encoderDimintEncoder dimension (default: 512).
kernelSizeintEncoder kernel size in samples (default: 16).
numSourcesintNumber of sources to separate (default: 2).
onnxOptionsOnnxModelOptionsOptional ONNX model options.
Exceptions
- FileNotFoundException
Thrown when the ONNX model file is not found.
Properties
EncoderDimension
Gets the encoder dimension (number of basis functions).
public int EncoderDimension { get; }
Property Value
EncoderKernelSize
Gets the encoder kernel size (window length in samples).
public int EncoderKernelSize { get; }
Property Value
EnhancementStrength
Gets or sets the enhancement strength (0.0 = no enhancement, 1.0 = maximum).
public double EnhancementStrength { get; set; }
Property Value
Remarks
Higher values provide more noise reduction but may introduce artifacts. Start with 0.5-0.7 for natural-sounding results.
LatencySamples
Gets the processing latency in samples.
public int LatencySamples { get; }
Property Value
Remarks
Important for real-time applications. Lower latency means faster response but potentially lower quality enhancement.
NumChannels
Gets the number of audio channels supported.
public int NumChannels { get; }
Property Value
NumSources
Gets the number of sources the network separates.
public int NumSources { get; }
Property Value
Methods
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 model state from a byte array.
public override void Deserialize(byte[] data)
Parameters
databyte[]
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.
Enhance(Tensor<T>)
Enhances audio quality by reducing noise and artifacts.
public Tensor<T> Enhance(Tensor<T> audio)
Parameters
audioTensor<T>Input audio tensor with shape [channels, samples] or [samples].
Returns
- Tensor<T>
Enhanced audio tensor with the same shape as input.
EnhanceWithReference(Tensor<T>, Tensor<T>)
Enhances audio with a reference signal for echo cancellation.
public Tensor<T> EnhanceWithReference(Tensor<T> audio, Tensor<T> reference)
Parameters
audioTensor<T>Input audio (microphone signal).
referenceTensor<T>Reference audio (speaker playback signal).
Returns
- Tensor<T>
Enhanced audio with echo removed.
Remarks
For Beginners: This is for video calls!
The problem: Your microphone picks up sound from your speakers, creating an echo for the other person.
Solution: We know what's playing from the speakers (reference), so we can subtract it from what the microphone picks up.
EstimateNoiseProfile(Tensor<T>)
Estimates the noise profile from a segment of audio.
public void EstimateNoiseProfile(Tensor<T> noiseOnlyAudio)
Parameters
noiseOnlyAudioTensor<T>Audio containing only noise (no signal).
Remarks
For Beginners: Some enhancers work better if you tell them what the noise sounds like. Record a few seconds of "silence" (just the background noise) and pass it here.
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 separated sources from input audio.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>Input audio tensor [batch, samples] or [samples].
Returns
- Tensor<T>
Separated sources tensor [batch, sources, samples] or [sources, samples].
PreprocessAudio(Tensor<T>)
Preprocesses raw audio waveform for model input.
protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)
Parameters
rawAudioTensor<T>
Returns
- Tensor<T>
ProcessChunk(Tensor<T>)
Processes audio in real-time streaming mode.
public Tensor<T> ProcessChunk(Tensor<T> audioChunk)
Parameters
audioChunkTensor<T>A small chunk of audio for real-time processing.
Returns
- Tensor<T>
Enhanced audio chunk (may have latency).
Remarks
For real-time applications like video calls. The enhancer maintains internal state between calls for continuity.
ResetState()
Resets the internal state of the different layers, clearing any remembered information.
public override void ResetState()
Remarks
This method resets the internal state (hidden state and cell state) of all layers in the network. This is useful when starting to process a new, unrelated sequence or when the network's memory should be cleared before making new predictions.
For Beginners: This clears the neural network's memory to start fresh.
Think of this like:
- Wiping the slate clean before starting a new task
- Erasing the neural network's "memory" so past inputs don't influence new predictions
- Starting fresh when processing a completely new sequence
For example, if you've been using an neural network to analyze one document and now want to analyze a completely different document, you would reset the state first to avoid having the first document influence the analysis of the second one.
Serialize()
Serializes the model state to a byte array.
public override byte[] Serialize()
Returns
- byte[]
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 a batch of mixture-source pairs.
public override void Train(Tensor<T> input, Tensor<T> expected)
Parameters
inputTensor<T>Mixture tensor [batch, samples].
expectedTensor<T>Target sources [batch, sources, samples].
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.