Class SlowFast<T>
- Namespace
- AiDotNet.Video.ActionRecognition
- Assembly
- AiDotNet.dll
SlowFast Networks for Video Recognition.
public class SlowFast<T> : NeuralNetworkBase<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
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
SlowFast<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
For Beginners: SlowFast is a two-pathway network that processes video at two different frame rates simultaneously: - Slow pathway: Processes fewer frames (e.g., 4 fps) but with more channels to capture spatial details - Fast pathway: Processes more frames (e.g., 32 fps) but with fewer channels to capture motion
This design is inspired by how human vision has:
- Parvo cells: Slow but detailed spatial processing
- Magno cells: Fast but coarse motion processing
Example usage:
var arch = new NeuralNetworkArchitecture<double>(
inputType: InputType.ThreeDimensional,
inputHeight: 224, inputWidth: 224, inputDepth: 3);
var model = new SlowFast<double>(arch, numClasses: 400);
var predictions = model.Classify(videoFrames);
Technical Details: - Two-pathway design with lateral connections - Slow pathway: T frames, C channels - Fast pathway: αT frames, βC channels (α=8, β=1/8 typically) - Lateral connections fuse information between pathways
Reference: "SlowFast Networks for Video Recognition" ICCV 2019 https://arxiv.org/abs/1812.03982
Constructors
SlowFast(NeuralNetworkArchitecture<T>, int, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?, IActivationFunction<T>?, IReadOnlyList<ILayer<T>>?, IReadOnlyList<ILayer<T>>?, int, int, int, int)
Creates a SlowFast model using native layers for training and inference.
public SlowFast(NeuralNetworkArchitecture<T> architecture, int numClasses = 400, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null, IActivationFunction<T>? probabilityActivation = null, IReadOnlyList<ILayer<T>>? customFastLayers = null, IReadOnlyList<ILayer<T>>? customFusionLayers = null, int slowFrames = 4, int slowChannels = 64, int fastChannels = 8, int alpha = 8)
Parameters
architectureNeuralNetworkArchitecture<T>The network architecture configuration. If Architecture.Layers is provided, it will be used as the slow pathway and customFastLayers/customFusionLayers must also be provided.
numClassesintNumber of action classes (default: 400 for Kinetics-400).
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimizer for training (default: Adam).
lossFunctionILossFunction<T>Loss function for training (default: CrossEntropy).
probabilityActivationIActivationFunction<T>Activation for converting logits to probabilities (default: Softmax).
customFastLayersIReadOnlyList<ILayer<T>>Custom fast pathway layers (required if Architecture.Layers is provided).
customFusionLayersIReadOnlyList<ILayer<T>>Custom fusion layers (required if Architecture.Layers is provided).
slowFramesintNumber of frames for slow pathway (default: 4).
slowChannelsintBase channels for slow pathway (default: 64).
fastChannelsintBase channels for fast pathway (default: 8).
alphaintFrame rate ratio between fast and slow pathways (default: 8).
SlowFast(NeuralNetworkArchitecture<T>, string, int, IActivationFunction<T>?, int, int, int, int)
Creates a SlowFast model using a pretrained ONNX model for inference.
public SlowFast(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int numClasses = 400, IActivationFunction<T>? probabilityActivation = null, int slowFrames = 4, int slowChannels = 64, int fastChannels = 8, int alpha = 8)
Parameters
architectureNeuralNetworkArchitecture<T>The network architecture configuration.
onnxModelPathstringPath to the pretrained ONNX model file.
numClassesintNumber of action classes (default: 400 for Kinetics-400).
probabilityActivationIActivationFunction<T>Activation for converting logits to probabilities (default: Softmax).
slowFramesintNumber of frames for slow pathway (default: 4).
slowChannelsintBase channels for slow pathway (default: 64).
fastChannelsintBase channels for fast pathway (default: 8).
alphaintFrame rate ratio between fast and slow pathways (default: 8).
Properties
SupportsTraining
Indicates whether this network supports training (learning from data).
public override bool SupportsTraining { get; }
Property Value
Remarks
For Beginners: Not all neural networks can learn. Some are designed only for making predictions with pre-set parameters. This property tells you if the network can learn from data.
Methods
Classify(Tensor<T>)
Classifies video frames into action categories.
public Tensor<T> Classify(Tensor<T> videoFrames)
Parameters
videoFramesTensor<T>
Returns
- Tensor<T>
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 SlowFast-specific configuration data and reinitializes layers.
protected override void DeserializeNetworkSpecificData(BinaryReader reader)
Parameters
readerBinaryReader
Remarks
Restores configuration parameters and recreates training components from serialized type names. Custom layer definitions are NOT restored - default LayerHelper layers are used after deserialization.
Dispose(bool)
Releases the unmanaged resources and optionally releases the managed resources.
protected override void Dispose(bool disposing)
Parameters
disposingboolTrue to release both managed and unmanaged resources; false to release only unmanaged.
Remarks
Disposes the ONNX inference session if one was created. This is important for releasing native ONNX runtime handles and memory when using pretrained models.
GetModelMetadata()
Gets metadata about this model for serialization.
public override ModelMetadata<T> GetModelMetadata()
Returns
Remarks
Serializes model architecture configuration, layer weights, and training component types (optimizer, loss function, probability activation). After deserialization, training components are recreated from their type names using reflection. Custom layer definitions are NOT preserved - default LayerHelper layers are used unless custom layers are re-provided after deserialization.
GetTopKPredictions(Tensor<T>, int)
Gets top-K predictions with probabilities.
public List<(int ClassIndex, double Probability)> GetTopKPredictions(Tensor<T> videoFrames, int topK = 5)
Parameters
videoFramesTensor<T>Input video frames tensor.
topKintNumber of top predictions to return (default: 5).
Returns
- List<(int ClassIndex, double Probability)>
List of (ClassIndex, Probability) tuples sorted by probability descending.
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.
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).
SerializeNetworkSpecificData(BinaryWriter)
Serializes SlowFast-specific configuration data including training component types.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriter
Remarks
Serializes configuration parameters and type names for training components (optimizer, loss function, probability activation). Custom layer definitions are NOT serialized - after deserialization, default LayerHelper layers are used unless custom layers are re-provided.
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.