Skip to content

Module_DeepLearning_zh

cyclone_dll edited this page Oct 1, 2026 · 8 revisions

当前位置 : 首页/深度学习模块

深度学习模块 - Deep Learning Module

0.9 起,本模块提供完整的可微分训练栈:张量与层定义、自动求值(前向/反向)、损失函数、优化器、训练循环与 v3 模型序列化。除早期遗留的静态 Layers 工具类外,推荐使用 Core / Modules / Training / Serialization 命名空间下的 API。

子系统 命名空间 说明
核心 Vorcyc.Mathematics.DeepLearning BatchTensor、Sequential、BatchSequential、CnnMlpModel、BatchParallelConcatModel、Parameter
层 Vorcyc.Mathematics.DeepLearning.Modules 单样本 ILayer 与批处理 IBatchLayer 实现
训练 Vorcyc.Mathematics.DeepLearning.Training Trainer、BatchLabelSample、BatchClassLabelSample
损失 Vorcyc.Mathematics.DeepLearning.Losses ILoss、IBatchLoss、BatchMeanSquaredErrorLoss、ISparseBatchLoss
优化器 Vorcyc.Mathematics.DeepLearning.Optimizers SgdOptimizer、AdamOptimizer
序列化 Vorcyc.Mathematics.DeepLearning.Serialization ModelSerializer(format v3)、ModelArchitectureCatalog
集成 Vorcyc.Mathematics.DeepLearning.Integration Signal ↔ BatchTensor 桥接、FeatureBatchBuilder、AudioTrainingSamples
DSP 前端 Vorcyc.Mathematics.DeepLearning.Integration.Frontends BatchPreEmphasisLayer、BatchStftMagnitudeLayer、BatchMelFilterbankLayer
遗留 Vorcyc.Mathematics.DeepLearning.Layers 无梯度的静态 Layers 前向算子(并行 CPU)

数据布局

  • 单样本张量 Tensor<T>(LinearAlgebra):宽 × 高 × 通道(W×H×C),用于 Sequential<T> / MLP 头。
  • 批张量 BatchTensor<T>:N×H×W×C(NHWC) 连续内存,用于 CNN 批训练。
  • 桥接:CnnMlpModel<T> 将 backbone 输出 N×1×1×F 转为 head 输入 1×N×F。

📒目录


模块架构与训练流程

典型 CNN 分类流程:

  1. 用 BatchConvolution2DLayer、BatchBatchNormLayer、池化/激活等组装 BatchSequential<float>。
  2. (可选)BatchFlattenLayer + BatchFullyConnectedLayer + BatchSoftmaxLayer。
  3. 构造 BatchLabelSample<float>(input, target) 批次列表。
  4. new Trainer<float>().FitBatchSequential(model, loss, optimizer, batches, epochs)。
  5. ModelSerializer.SaveToFile(model, path) 持久化权重与 架构元数据(v3)。

混合模型:CnnMlpModel<T> = BatchSequential backbone + Sequential head,使用 Trainer.FitCnnMlp。

双分支:BatchParallelConcatModel<T> 对同一输入并行运行左右两支并在通道维拼接,使用 Trainer.FitBatchParallelConcat。


Core:BatchTensor 与模型容器

BatchTensor<T>

NHWC 四维批张量,Values 为 Span<T>。主要成员:

  • 构造:BatchTensor(batch, height, width, channels)
  • 索引:this[n, h, w, c]
  • Shape → BatchShape;GetSample(int) 导出单样本 Tensor<T>

IBatchLayer<T> / BatchSequential<T>

可微分层接口:Forward(BatchTensor, training)、Backward(grad)、Parameters、GetOutputShape。

BatchSequential<T> 顺序堆叠多个 IBatchLayer<T>,提供 ZeroGradients()。

Sequential<T> / ILayer<T>

单样本层栈,输入/输出为 Tensor<T>(1×N×F 特征向量或 W×H×C 图像张量)。

CnnMlpModel<T>

  • Backbone:BatchSequential<T>(NHWC)
  • Head:Sequential<T>(MLP)
  • Forward / Backward / ZeroGradients 端到端

BatchParallelConcatModel<T>

  • Left / Right:两支 BatchSequential<T>
  • Forward:同输入、通道维 Concat

Parameter<T>

可训练权重/偏置包装,含 Value、Gradient、ZeroGradient()。


Modules:批处理层一览

以下类型均实现 IBatchLayer<T>(T 为 float / double 等 IBinaryFloatingPointIeee754):

类型 说明
BatchConvolution2DLayer 2D 卷积(im2col + GEMM)
BatchDepthwiseConvolution2DLayer 深度可分离卷积
BatchTransposedConvolution2DLayer 转置卷积 / 上采样
BatchBatchNormLayer 批归一化(NHWC)
BatchLayerNormLayer 层归一化
BatchFullyConnectedLayer 全连接(需配合 Flatten)
BatchFlattenLayer N×H×W×C → N×1×1×(HWC)
BatchMaxPool2DLayer / BatchAvgPool2DLayer 池化
BatchGlobalAveragePool2DLayer 全局平均池化
BatchUpsample2DLayer 最近邻 2× 上采样
BatchDropoutLayer Dropout(training 标志控制)
BatchReLUActivation / BatchLeakyReLUActivation / BatchSigmoidActivation / BatchTanhActivation 激活
BatchSoftmaxLayer Softmax
BatchConcatenateLayer 通道维拼接(层内双输入需外部布线时使用 BatchParallelConcatModel)
BatchResidualBlockLayer 残差块
BatchSqueezeExciteLayer SE 注意力

单样本层(ILayer<T>):FullyConnectedLayer、Convolution2DLayer、BatchNormLayer、ReLUActivation、SigmoidActivation、SoftmaxLayer、FlattenLayer、MaxPool2DLayer 等,用于 Sequential<T> 与 MLP 头。


Training:Trainer

Trainer<T> 提供高层训练循环:

方法 模型 数据
Fit Sequential<T> TrainingSample<T> 列表
FitBatched Sequential<T> 打包为 1×N×F 的批次
FitCnnMlp CnnMlpModel<T> NHWC 批 + 标签
FitBatchSequential BatchSequential<T> BatchLabelSample<T> 或 BatchClassLabelSample<T>(稀疏标签)
FitBatchParallelConcat BatchParallelConcatModel<T> BatchLabelSample<T>

单步 API:TrainBatchSequentialStep、TrainBatchParallelConcatStep 等,便于自定义循环。

学习率调度:ILearningRateScheduler<T> — 可在每个 epoch 开始时回调(亦用于 MlpTrainingOptions<T>)。

调度器 行为
ConstantLearningRateScheduler<T> 固定学习率
StepDecayScheduler<T> 每 StepEpochs 乘以 DecayFactor
ExponentialDecayScheduler<T> initial * exp(-decayRate * (epoch-1))
CosineAnnealingScheduler<T> 从初始 LR 余弦衰减至最小值

BatchTrainingSample<T> — FitCnnMlp 用的 record struct:NHWC Input + 旧式 1×N×F Target。

MlpTrainingOptions<T> — 曲线拟合 MLP 训练:OptimizerKind(Sgd/Adam)、学习率、momentum、Adam 超参、可选 LearningRateScheduler、RandomSeed、ComputingContext;CreateOptimizer() 构造 IOptimizer<T>。

MlpRegressor — 为神经回归构建/训练小型 MLP(DeepLearning.Training);见 Examples/DeepLearning_example/CurveFitDemo.cs。

Fit、FitBatched、FitBatchSequential、FitBatchParallelConcat、FitCnnMlp 均支持可选参数 computingContext(或使用外层 ComputingScope)。批层前向会读取执行策略;详见计算上下文手册。


Losses 与 Optimizers

损失

类型 接口 用途
MeanSquaredErrorLoss<T> ILoss<T> 回归(单样本)
CategoricalCrossEntropyLoss<T> ILoss<T> 分类(one-hot 目标)
BatchCategoricalCrossEntropyLoss<T> ISparseBatchLoss<T> NHWC 批分类(整数类标或 one-hot)

IBatchLoss<T>:Compute(prediction, target) + Backward(...),梯度形状与 BatchTensor 一致。

优化器

  • SgdOptimizer<T>:随机梯度下降(可选 momentum)
  • AdamOptimizer<T>:Adam

均实现 IOptimizer<T>:ZeroGrad、Step(parameters)。


Serialization:ModelSerializer v3

文件魔数 VMDL,FormatVersion = 3。除张量权重外,写入 层类型 ID 与超参(LayerDescriptor),加载时可 ModelArchitectureCatalog.VerifyMatches 校验结构。

支持的模型种类(ModelKind):

Kind 类型
Sequential Sequential<T>
CnnMlp CnnMlpModel<T>
BatchSequential BatchSequential<T>
BatchParallelConcat BatchParallelConcatModel<T>

API 示例:

ModelSerializer.SaveToFile(model, "model.vmdl");
ModelSerializer.LoadFromFile(model, "model.vmdl"); // 模型结构须先按相同架构构造

ModelArchitectureCatalog.Describe(model) 可导出层描述列表供调试或单元测试。

复合层的嵌套权重序列化(0.9.2 修复)

BatchResidualBlockLayer、BatchSqueezeExciteLayer 等复合层内部封装了子层(如 BatchBatchNormLayer)。在 0.9.2 之前,序列化只遍历顶层 Parameters,会漏掉子层 BatchNorm 的 running mean/variance(推理统计量不是可训练 Parameter,但必须持久化,否则重载后推理结果漂移)。

修复引入接口 IBatchCompositeLayer<T>:

public interface IBatchCompositeLayer<T>
    where T : unmanaged, IBinaryFloatingPointIeee754<T>
{
    // 该复合层内部按顺序排列的子层,供序列化器递归读写其非参数状态(如 BN running stats)
    IReadOnlyList<IBatchLayer<T>> Children { get; }
}

ModelSerializer 在 v3 写入/读取时,遇到实现该接口的层会递归展开 Children,把每个子层的张量状态(含 BN running stats)一并存取。自定义复合层(内部持有带状态的子层)应实现此接口,否则其子层状态不会被持久化。

ModelArchitectureBuilder — 由 LayerDescriptor 列表重建可训练模型:

方法 输出
BuildBatchSequential<T>(layers) BatchSequential<T>
BuildCnnMlp<T>(layers) CnnMlpModel<T>(识别 backbone.* / head.* 前缀)
BuildBatchLayer<T>(descriptor) 单个 IBatchLayer<T>

LayerBase<T> / BatchLayerBase<T> — 自定义层的可选基类。

BatchTensorUtilities / TensorUtilities — 形状检查、转换与调试辅助。


批训练代码示例

using Vorcyc.Mathematics.DeepLearning;
using Vorcyc.Mathematics.DeepLearning.Losses;
using Vorcyc.Mathematics.DeepLearning.Modules;
using Vorcyc.Mathematics.DeepLearning.Optimizers;
using Vorcyc.Mathematics.DeepLearning.Training;
using Vorcyc.Mathematics.DeepLearning.Serialization;

// 简单 CNN:Conv → BN → ReLU → GAP → FC → Softmax
var model = new BatchSequential<float>(
    new BatchConvolution2DLayer<float>(3, 16, kernelSize: 3, stride: 1, name: "conv1"),
    new BatchBatchNormLayer<float>(16, name: "bn1"),
    new BatchReLUActivation<float>("relu1"),
    new BatchGlobalAveragePool2DLayer<float>("gap"),
    new BatchFullyConnectedLayer<float>(16, 10, name: "fc"),
    new BatchSoftmaxLayer<float>("softmax"));

var batches = new List<BatchLabelSample<float>>(); // 填充 NHWC input / target
var trainer = new Trainer<float>();
var loss = new BatchCategoricalCrossEntropyLoss<float>();
var optimizer = new AdamOptimizer<float>(learningRate: 1e-3f);

trainer.FitBatchSequential(model, loss, optimizer, batches, epochs: 10,
    onEpochEnd: (epoch, avgLoss) => Console.WriteLine($"epoch {epoch}: {avgLoss}"));

ModelSerializer.SaveToFile(model, "cnn.vmdl");

与信号处理集成

DeepLearning.Integration 将 DSP 的 Signal 转为 BatchTensor<float>,便于直接接入 Trainer.FitBatchSequential。依赖方向为 DeepLearning → SignalProcessing(信号模块不引用深度学习)。

类型 布局 用途
波形向量批 N×1×1×L 原始采样序列,长度 L 在通道维
分帧批 1×F×L×1 滑动窗分帧,F 为帧数
谱图批 N×T×F×1 STFT 幅度谱,T 为时间帧、F 为频 bin
using Vorcyc.Mathematics.DeepLearning.Integration;
using Vorcyc.Mathematics.DeepLearning.Training;
using Vorcyc.Mathematics.SignalProcessing.Signals;
using Vorcyc.Mathematics.SignalProcessing.Fourier;

var low = new Signal(256, 8000f);
low.GenerateWave(WaveShape.Sine, 200f);
var highTone = new Signal(256, 8000f);
highTone.GenerateWave(WaveShape.Sine, 600f);

var stft = new Stft(windowSize: 64, hopSize: 32);
var spec = SpectrogramBatchBuilder.FromSignal(low, stft);            // 1×T×F×1
var vectorBatch = BatchTensorSignalExtensions.FromSignal(low);       // 1×1×1×L
var restored = vectorBatch.ToSignal(0, 8000f);                     // 波形往返

var sample = AudioTrainingSamples.SpectrogramClassification(
    signals: [low, highTone],
    classIndices: [0, 1],
    numClasses: 2,
    stft);

trainer.FitBatchSequential(model, loss, optimizer, [sample], epochs: 100);

特征打包(阶段 B)

FeatureBatchBuilder 将 DSP 特征提取结果标准化为 DL 张量:

DSP 来源 布局 API
Stft.AveragePeriodogram N×1×1×F FromPeriodogram / FromPeriodograms
FeatureExtractor 帧序列 N×T×F×1 FromExtractor / FromExtractors
帧特征时间均值 N×1×1×F FromExtractorMean / FromExtractorMeans
任意等长向量 N×1×1×F FromVectors

AudioTrainingSamples 提供 PeriodogramClassification、FeatureMeanClassification、MfccSequenceClassification 等训练样本工厂。

var mfcc = AudioTrainingSamples.CreateDefaultMfccExtractor(8000);
var sample = AudioTrainingSamples.FeatureMeanClassification(
    signals, labels, numClasses: 2, extractor: mfcc);

DSP 前端层(阶段 C)

Integration.Frontends 将固定 DSP 运算封装为 IBatchLayer<float>,可编入 BatchSequential:

层 输入 → 输出 反向传播
BatchPreEmphasisLayer N×1×1×L → N×1×1×L 可微(线性)
BatchStftMagnitudeLayer N×1×1×L → N×T×F×1 stop-gradient
BatchMelFilterbankLayer N×T×F×1 → N×T×M×1 可微(固定矩阵)
using Vorcyc.Mathematics.DeepLearning.Integration.Frontends;

var frontend = AudioFrontendLayers.CreateMelSpectrogramStack(
    samplingRate: 8000, windowSize: 64, hopSize: 32, melBands: 24);

var model = new BatchSequential<float>(
    frontend[0], frontend[1], frontend[2],
    new BatchConvolution2DLayer<float>(1, 16, kernelSize: 3),
    new BatchReLUActivation<float>(),
    new BatchGlobalAveragePool2DLayer<float>(),
    new BatchFullyConnectedLayer<float>(16, numClasses));

var waves = BatchTensorSignalExtensions.FromSignalVectors(signals);
trainer.FitBatchSequential(model, loss, optimizer,
    [new BatchLabelSample<float>(waves, targets)], epochs: 100);

闭环应用(阶段 D)

  • 神经回归:神经网络曲线拟合请使用 MlpRegressor(DeepLearning.Training)——见 Examples/DeepLearning_example/CurveFitDemo.cs。(CurveFitter<T> 本身位于 MachineLearning.CurveFitting,覆盖经典曲线拟合,非神经网络。)
  • 批回归损失:BatchMeanSquaredErrorLoss<T>,配合 AudioTrainingSamples.WaveformRegression。
  • 文档与示例:详见 Module_DeepLearning_Audio_zh.md。

遗留:Layers 静态类

以下为 早期无自动微分 的并行前向算子,新工程请优先使用 Modules + Trainer。保留用于兼容与对照。

Vorcyc.Mathematics.DeepLearning.Layers.Layers 类

Vorcyc.Mathematics.DeepLearning.Layers.Layers 是一个实现神经网络层的静态类。

方法

1. BatchNorm 方法

  • public static Tensor<T> BatchNorm<T>(Tensor<T> input, Tensor<T> mean, Tensor<T> variance, Tensor<T> shift, Tensor<T> scale) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量进行批量归一化。
    • 参数:
      • input: 输入的张量。
      • mean: 均值张量。
      • variance: 方差张量。
      • shift: 偏移量张量。
      • scale: 缩放因子张量。
    • 返回值: 归一化后的张量。
  • public static TensorFp32 BatchNorm(TensorFp32 input, TensorFp32 mean, TensorFp32 variance, TensorFp32 shift, TensorFp32 scale)

    • 对输入张量进行批量归一化。
    • 参数:
      • input: 输入的张量。
      • mean: 均值张量。
      • variance: 方差张量。
      • shift: 偏移量张量。
      • scale: 缩放因子张量。
    • 返回值: 归一化后的张量。

2. Conv2D 方法

  • public static Tensor<T> Conv2D<T>(Tensor<T> input, Tensor<T>[] filters, Tensor<T> biases, int stride = 1, int dilation = 1) where T : IBinaryFloatingPointIeee754<T>

    • 对 2D 张量执行卷积操作。
    • 参数:
      • input: 输入的 2D 张量。
      • filters: 卷积核的数组。
      • biases: 偏置张量。
      • stride: 卷积步长,默认为 1。
      • dilation: 卷积扩张率,默认为 1。
    • 返回值: 卷积结果的张量。
  • public static TensorFp32 Conv2D(TensorFp32 input, TensorFp32[] filters, TensorFp32 biases, int stride = 1, int dilation = 1)

    • 对 2D 张量执行卷积操作。
    • 参数:
      • input: 输入的 2D 张量。
      • filters: 卷积核的数组。
      • biases: 偏置张量。
      • stride: 卷积步长,默认为 1。
      • dilation: 卷积扩张率,默认为 1。
    • 返回值: 卷积结果的张量。

3. Dense 方法

  • public static Tensor<T> Dense<T>(Tensor<T> input, Tensor<T>[] weights, Tensor<T> biases) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量执行密集(全连接)层操作。
    • 参数:
      • input: 输入的张量。
      • weights: 权重张量的数组。
      • biases: 偏置张量。
    • 返回值: 执行密集操作后的张量。
  • public static TensorFp32 Dense(TensorFp32 input, TensorFp32[] weights, TensorFp32 biases)

    • 对输入张量执行密集(全连接)层操作。
    • 参数:
      • input: 输入的张量。
      • weights: 权重张量的数组。
      • biases: 偏置张量。
    • 返回值: 执行密集操作后的张量。

4. Fusion 方法

  • public static Tensor<T> Fusion<T>(Tensor<T> input, Tensor<T> joint) where T : IBinaryFloatingPointIeee754<T>

    • 合并两个张量。
    • 参数:
      • input: 输入的张量。
      • joint: 要合并的张量。
    • 返回值: 合并后的张量。
  • public static TensorFp32 Fusion(TensorFp32 input, TensorFp32 joint)

    • 合并两个张量。
    • 参数:
      • input: 输入的张量。
      • joint: 要合并的张量。
    • 返回值: 合并后的张量。

5. JoinLayer 方法

  • public static Tensor<T> JoinLayer<T>(Tensor<T> input, Tensor<T> joint) where T : IBinaryFloatingPointIeee754<T>

    • 合并两个张量层。
    • 参数:
      • input: 输入的张量。
      • joint: 要合并的张量。
    • 返回值: 合并后的张量。
  • public static TensorFp32 JoinLayer(TensorFp32 input, TensorFp32 joint)

    • 合并两个张量层。
    • 参数:
      • input: 输入的张量。
      • joint: 要合并的张量。
    • 返回值: 合并后的张量。

6. LinearLayer 方法

  • public static Tensor<T> LinearLayer<T>(Tensor<T> input, Tensor<T>[] weights, Tensor<T> biases) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量执行线性(全连接)层操作。
    • 参数:
      • input: 输入的张量。
      • weights: 权重张量的数组。
      • biases: 偏置张量。
    • 返回值: 执行线性操作后的张量。
  • public static TensorFp32 LinearLayer(TensorFp32 input, TensorFp32[] weights, TensorFp32 biases)

    • 对输入张量执行线性(全连接)层操作。
    • 参数:
      • input: 输入的张量。
      • weights: 权重张量的数组。
      • biases: 偏置张量。
    • 返回值: 执行线性操作后的张量。

7. MaxPool2D 方法

  • public static Tensor<T> MaxPool2D<T>(Tensor<T> input) where T : IBinaryFloatingPointIeee754<T>, IMinMaxValue<T>

    • 对输入张量执行二维最大池化操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行最大池化操作后的张量。
  • public static TensorFp32 MaxPool2D(TensorFp32 input)

    • 对输入张量执行二维最大池化操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行最大池化操作后的张量。

8. ReLU 方法

  • public static Tensor<T> ReLU<T>(Tensor<T> input) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量执行 ReLU 激活函数操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行 ReLU 操作后的张量。
  • public static TensorFp32 ReLU(TensorFp32 input)

    • 对输入张量执行 ReLU 激活函数操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行 ReLU 操作后的张量。

9. Sigmoid 方法

  • public static Tensor<T> Sigmoid<T>(Tensor<T> input) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量执行 Sigmoid 激活函数操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行 Sigmoid 操作后的张量。
  • public static TensorFp32 Sigmoid(TensorFp32 input)

    • 对输入张量执行 Sigmoid 激活函数操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 执行 Sigmoid 操作后的张量。

10. Upsample2D 方法

  • public static Tensor<T> Upsample2D<T>(Tensor<T> input) where T : IBinaryFloatingPointIeee754<T>

    • 对输入张量执行二维上采样操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 上采样后的张量。
  • public static TensorFp32 Upsample2D(TensorFp32 input)

    • 对输入张量执行二维上采样操作。
    • 参数:
      • input: 输入的张量。
    • 返回值: 上采样后的张量。

代码示例

以下是一个使用 Layers 类中多个方法的示例,并在示例中加入了注释:

using System;
using Vorcyc.Mathematics.DeepLearning.Layers;
using Vorcyc.Mathematics.LinearAlgebra;

public class LayersExample
{
    public static void Main()
    {
        // 定义输入张量
        var input = new Tensor<float>(new float[,,] 
        { 
            { 
                { 1.0f, 2.0f }, 
                { 3.0f, 4.0f } 
            }, 
            {
                { 5.0f, 6.0f }, 
                { 7.0f, 8.0f }
            } 
        });
        // 定义均值、方差、偏移量和缩放因子张量
        var mean = new Tensor<float>(new float[] { 1.0f, 2.0f });
        var variance = new Tensor<float>(new float[] { 1.0f, 1.0f });
        var shift = new Tensor<float>(new float[] { 0.0f, 0.0f });
        var scale = new Tensor<float>(new float[] { 1.0f, 1.0f });

        // 执行批量归一化
        var normalized = Layers.BatchNorm(input, mean, variance, shift, scale);
        Console.WriteLine("BatchNorm Result:");
        PrintTensor(normalized);

        // 定义卷积核和偏置张量
        var filters = new Tensor<float>[]
        {
        new Tensor<float>(new float[,,] { { { 1.0f, 0.0f }, { 0.0f, 1.0f } } }),
        new Tensor<float>(new float[,,] { { { 0.0f, 1.0f }, { 1.0f, 0.0f } } })
        };
        var biases = new Tensor<float>(new float[] { 0.0f, 0.0f });

        // 执行卷积操作
        var convResult = Layers.Conv2D(input, filters, biases);
        Console.WriteLine("Conv2D Result:");
        PrintTensor(convResult);

        // 定义权重和偏置张量
        var weights = new Tensor<float>[]
        {
        new Tensor<float>(new float[,,] { { { 1.0f, 0.0f }, { 0.0f, 1.0f } } }),
        new Tensor<float>(new float[,,] { { { 0.0f, 1.0f }, { 1.0f, 0.0f } } })
        };
        var denseBiases = new Tensor<float>(new float[] { 0.0f, 0.0f });

        // 执行密集层操作
        var denseResult = Layers.Dense(input, weights, denseBiases);
        Console.WriteLine("Dense Result:");
        PrintTensor(denseResult);

        // 执行 ReLU 激活函数操作
        var reluResult = Layers.ReLU(input);
        Console.WriteLine("ReLU Result:");
        PrintTensor(reluResult);

        // 执行 Sigmoid 激活函数操作
        var sigmoidResult = Layers.Sigmoid(input);
        Console.WriteLine("Sigmoid Result:");
        PrintTensor(sigmoidResult);
    }

    private static void PrintTensor(Tensor<float> tensor)
    {
        for (int d = 0; d < tensor.Depth; d++)
        {
            for (int y = 0; y < tensor.Height; y++)
            {
                for (int x = 0; x < tensor.Width; x++)
                {
                    Console.Write($"{tensor[x, y, d]} ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}

Language / 语言: English · 简体中文


Home


首页

Clone this wiki locally