【发布时间】:2017-05-07 18:42:19
【问题描述】:
我试图为神经网络翻译这个 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
【问题讨论】:
-
虽然 Python 代码真正写的是“点”,但它显然意味着简单的矩阵*向量乘法,而不是点积。所以试试那个(我发现的 Matrix 类定义了一个
operator *) -
我尝试了 * 运算符但它仍然不起作用
-
另一件事可能是对行和列的不同解释。虽然它会破坏背后的数学,但您可以快速测试交换参数的顺序是否突然“修复”点或 *。如果它有效,那么与原始 Python 代码所期望的相比,一切都被颠倒了。
-
好的,尝试交换行和列,但它没有做任何事情。一个矩阵是 3x1(SynapticWeights),另一个是 4x3(TrainingSetInput)。我不知道如何将它们正确地点乘在一起。
-
好吧,我真的很想知道你昨天尝试了什么,如果你现在就试试
return Sigmoid(Input * _SynapticsWeights);(根据下面的讨论)
标签: c# python artificial-intelligence