原文地址
How to build a simple neural network in 9 lines of Python code
这个项目是我们c艹老师叫我们用c艹重写的,给出了模板程序,要求通过eigen库进行改进使得循环尽可能少
下面给出个人实现
其中值得一提的是,对于求一个行向量的各个数的倒数时,采用的是化为对角阵后求逆再化为行向量的方式
而两个行向量的按位向乘采用了化为对角阵后进行矩阵乘法的方式
#include <iostream>
#include <Dense>
using Eigen::MatrixXd;
using namespace std;
MatrixXd weights(1, 3), input(4, 3), output(1, 4), errors(1, 4), guess(1, 4), problem(3, 1), adjust(1, 3);
double GetRand() //随机生成(-1, 1)的数
{
return 2.0 * rand() / RAND_MAX - 1.0;
}
int main() {
srand((unsigned int)time(0));
/*
input << 0, 0, 1,
1, 1, 1,
1, 0, 1,
0, 1, 1;
*/
input << 1, 1, 1,
0, 0, 1,
1, 1, 1,
0, 0, 1;
// output << 0, 1, 1, 0;
output << 1, 0, 1, 0;
// problem << 0, 0, 0;
problem << 1, 0, 0;
for (int i = 0; i < 3; i++)
weights(0, i) = GetRand();
for (int k = 0; k < 10000; k++) {
MatrixXd x(1, 4), a(1, 4);
a << 1, 1, 1, 1;
x = (input * weights.transpose());
x = -x;
guess = ((x.array().exp().matrix().transpose() + a).asDiagonal()).inverse().diagonal();
errors = output - guess;
adjust << 0, 0, 0;
a << 1, 1, 1, 1;
adjust = (input.transpose() * (((a - guess) * guess.asDiagonal()) * errors.asDiagonal()).transpose()).transpose();
weights += adjust;
}
double y;
MatrixXd x(1, 1);
x = weights * problem;
y = 1 / (1 + exp(-x(0, 0)));
cout << "guess [1,0,0] is " << y << endl;
return 0;
}
Comments NOTHING