Class NeuralNoiseReducer<T>
- Namespace
- AiDotNet.Audio.Enhancement
- Assembly
- AiDotNet.dll
Neural network-based noise reducer for high-quality audio enhancement.
public class NeuralNoiseReducer<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
-
NeuralNoiseReducer<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
This model uses an encoder-bottleneck-decoder architecture inspired by U-Net to learn the mapping from noisy audio to clean audio. It operates in the time-frequency domain using STFT for analysis and synthesis. Note: The current implementation uses a simplified dense decoder; a full U-Net with transposed convolutions and skip connections is planned for future versions.
For Beginners: This is like a "magic eraser" for audio noise!
How it works:
- Converts audio to a spectrogram (picture of sound)
- Neural network learns to identify and remove noise patterns
- Converts cleaned spectrogram back to audio
Key features:
- Works on any type of noise (AC hum, fan noise, traffic, etc.)
- Preserves speech/music quality while removing noise
- Can be trained on your specific noise conditions
- Supports real-time streaming for live applications
Use cases:
- Podcast/video production (remove background noise)
- Voice calls (improve speech clarity)
- Music restoration (remove hiss/crackle from old recordings)
- Hearing aids (enhance speech in noisy environments)
Two modes of operation:
- ONNX Mode: Load a pre-trained model for instant use
- Native Mode: Train your own model on custom data
Constructors
NeuralNoiseReducer(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, double, ILossFunction<T>?)
Creates a NeuralNoiseReducer in native training mode.
public NeuralNoiseReducer(NeuralNetworkArchitecture<T> architecture, int sampleRate = 16000, int fftSize = 512, int hopSize = 256, int numChannels = 1, int numStages = 4, int baseFilters = 32, int bottleneckDim = 256, double enhancementStrength = 0.8, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>The neural network architecture (user-defined for full customization).
sampleRateintAudio sample rate (default: 16000).
fftSizeintFFT window size (default: 512).
hopSizeintHop size between frames (default: 256).
numChannelsintNumber of audio channels (default: 1).
numStagesintNumber of encoder/decoder stages (default: 4).
baseFiltersintBase filter count (default: 32).
bottleneckDimintBottleneck hidden dimension (default: 256).
enhancementStrengthdoubleEnhancement strength 0-1 (default: 0.8).
lossFunctionILossFunction<T>Loss function for training (default: L1 loss).
Remarks
For Beginners: Use this constructor when you want to train your own model. You'll need noisy/clean audio pairs for training.
NeuralNoiseReducer(NeuralNetworkArchitecture<T>, string, int, int, int, int, double)
Creates a NeuralNoiseReducer in ONNX inference mode using a pre-trained model.
public NeuralNoiseReducer(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 16000, int fftSize = 512, int hopSize = 256, int numChannels = 1, double enhancementStrength = 0.8)
Parameters
architectureNeuralNetworkArchitecture<T>The neural network architecture (user-defined for full customization).
modelPathstringPath to the ONNX model file.
sampleRateintAudio sample rate (default: 16000).
fftSizeintFFT window size (default: 512).
hopSizeintHop size between frames (default: 256).
numChannelsintNumber of audio channels (default: 1).
enhancementStrengthdoubleEnhancement strength 0-1 (default: 0.8).
Remarks
For Beginners: Use this constructor when you have a pre-trained model. Just point to the ONNX file and start enhancing audio immediately.
Properties
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; protected set; }
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.
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 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.
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.
ResetEnhancerState()
Resets the enhancer streaming state.
public void ResetEnhancerState()
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> expected)
Parameters
inputTensor<T>The input data.
expectedTensor<T>
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.