我试图翻译神经网络的这个python代码 https://gist.github.com/miloharper/c5db6590f26d99ab2670#file-main-py 在C#中。我正在使用Math.Net Numerics作为矩阵,这是我到目前为止在C#中编写的代码
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra.Double;
namespace NeuralNetwork
{
class Program
{
static void Main(string[] args)
{
NeuralNetwork NN = new NeuralNetwork();
Console.WriteLine("Random starting synaptic weights: ");
Console.WriteLine(NN.SynapticWeights);
Matrix<double> TrainingSetInput = DenseMatrix.OfArray(new double[,] { { 0, 0, 1 }, { 1, 1, 1 }, { 1, 0, 1 }, { 0, 1, 1 } });
Matrix<double> TrainingSetOutput = DenseMatrix.OfArray(new double[,] { { 0, 1, 1, 0 } }).Transpose();
NN.Train(TrainingSetInput, TrainingSetOutput, 10000);
Console.WriteLine("New synaptic weights after training: ");
Console.WriteLine(NN.SynapticWeights);
Console.WriteLine("Considering new situation {1, 0, 0} -> ?: ");
Console.WriteLine(NN.Think(DenseMatrix.OfArray(new double[,] { { 1, 0, 0 } })));
Console.ReadLine();
}
}
class NeuralNetwork
{
private Matrix<double> _SynapticWeights;
public NeuralNetwork()
{
_SynapticWeights = 2 * Matrix<double>.Build.Random(3, 1) - 1;
}
private Matrix<double> Sigmoid(Matrix<double> Input)
{
return 1 / (1 + Matrix<double>.Exp(-Input));
}
private Matrix<double> SigmoidDerivative(Matrix<double> Input)
{
return Input * (1 - Input); //NEW Exception here
}
public Matrix<double> Think(Matrix<double> Input)
{
return Sigmoid((Input * _SynapticWeights)); //Exception here (Solved)
}
public void Train(Matrix<double> TrainingInput, Matrix<double> TrainingOutput, int TrainingIterations)
{
for (int Index = 0; Index < TrainingIterations; Index++)
{
Matrix<double> Output = Think(TrainingInput);
Matrix<double> Error = TrainingOutput - Output;
Matrix<double> Adjustment = Matrix<double>.op_DotMultiply(TrainingInput.Transpose(), Error * SigmoidDerivative(Output));
_SynapticWeights += Adjustment;
}
}
public Matrix<double> SynapticWeights { get { return _SynapticWeights; } set { _SynapticWeights = value; } }
}
}
当我执行它时,它在第53行显示异常(代码中该行有注释)。它说:
矩阵尺寸必须一致:op1为4x3,op2为3x1
我是否将其复制错误或者是否存在MAth.Net库的问题?
提前致谢:D