一款 C# 编写的神经网络计算图框架-部分代码示例

时间:2024-11-11 13:40:57
//声明两个ConvLayer 和一个激活函数SigmodLayer 
ConvLayer cl1 = new ConvLayer(13, 5, true);
          
SigmodLayer sl = new SigmodLayer();
float lr = 0.5f;
ConvLayer cl2 = new ConvLayer(5, 1, true);

int i = 0,a=0;
while (a < 5000)
{
     
        dynamic ff = cl1.Forward(x);
        ff = sl.Forward(ff);
        ff = cl2.Forward(ff);
       
        //计算误差
        MSELoss mloss = new MSELoss();
       
        var loss = mloss.Forward(ff, y);

        Console.WriteLine("误差:" + loss);

        dynamic grid = mloss.Backward();

        //反传播w2
       
        dynamic w22 = cl2.backweight(grid);

        //反传播W1
        dynamic grid1 = cl2.backward(grid);
        grid1 = sl.Backward(grid1);
        dynamic w11 = cl1.backweight(grid1);
           
       //更新参数
        cl2.weights = Matrix.MatrixSub(cl2.weights, Matrix.multiply(w22.grid, lr));
        cl2.basicData = Matrix.MatrixSub(cl2.basicData, Matrix.multiply(w22.basic, lr));

        cl1.weights = Matrix.MatrixSub(cl1.weights, Matrix.multiply(w11.grid, lr));
        cl1.basicData = Matrix.MatrixSub(cl1.basicData, Matrix.multiply(w11.basic, lr));
        i++;
  
    a++;
}