我有一个使用相同数据的项目,在我的c ++代码中,它需要17秒才能训练100个数据,同时在此项目的javascript代码中
https://github.com/CodingTrain/Toy-Neural-Network-JS 它仅运行约10秒即可训练2400data 请有人帮我做错什么,我需要完成我的本科论文项目。
我已经建立了2个项目,其中一个(该项目)与那个javascript代码(kinda)中的c ++中的神经网络相同,但仍然给出相同的结果
NeuralNetwork::NeuralNetwork(int a,int b,int c)
{
this->numInput = a;
this->numHidden = b;
this->numOutput = c;
std::vector<double> vec(a, 0.1);
for (int i = 0; i < b; ++i) {
this->weightIH.push_back(vec);
}
std::vector<double> vec2(b, 0.1);
for (int i = 0; i < c; ++i) {
this->weightHO.push_back(vec2);
}
}
NeuralNetwork::~NeuralNetwork()
{
}
std::vector<double> NeuralNetwork::tambahbias(std::vector<double> a) {
int size = a.size();
for (int i = 0; i < size; ++i) {
a[i] = a[i] + 1;
}
return a;
}
std::vector<double> NeuralNetwork::activate(std::vector<double> a) {
int size = a.size();
for (int i = 0; i < size; ++i) {
a[i] = a[i] / (1 + abs(a[i]));
}
return a;
}
std::vector<double> NeuralNetwork::derivation(std::vector<double> a) {
int size = a.size();
for (int i = 0; i < size; ++i) {
a[i] = a[i] * (1 - a[i]);
}
return a;
}
std::vector<double> NeuralNetwork::hitungError(std::vector<double> a, std::vector<double> b) {
int size = a.size();
for (int i = 0; i < size; ++i) {
a[i] = b[i] - a[i];
}
return a;
}
void NeuralNetwork::train(std::vector<double> a, std::vector<double> target) {
std::vector<double> hidden(numHidden);
for (int i = 0; i < numHidden; ++i) {
for (int j = 0; j < numInput; ++j) {
hidden[i] += a[j] * weightIH[i][j];
}
}
hidden = tambahbias(hidden);
hidden = activate(hidden);
std::vector<double> output(numOutput);
for (int i = 0; i < numOutput; ++i) {
for (int j = 0; j < numHidden; ++j) {
output[i] += hidden[j] * weightHO[i][j];
}
}
output = tambahbias(output);
output = activate(output);
std::vector<double> errorO(numOutput);
errorO = hitungError(output, target);
std::vector<double> gradO(numOutput);
gradO = derivation(output);
for (int i = 0; i < numOutput; ++i) {
gradO[i] = gradO[i] * errorO[i] * 0.1;
}
for (int i = 0; i < numOutput; ++i) {
for (int j = 0; j < numHidden; ++j) {
weightHO[i][j] += (gradO[i] * hidden[j]);
}
}
std::vector<double> gradH(numHidden);
std::vector<double> derH(numHidden);
derH = derivation(hidden);
for (int i = 0; i < numHidden; ++i) {
for (int j = 0; j < numOutput; ++j) {
gradH[i] = gradO[j] * weightHO[j][i];
}
gradH[i] = gradH[i] * derH[i] * 0.1;
}
for (int i = 0; i < numHidden; ++i) {
for (int j = 0; j < numInput; ++j) {
weightIH[i][j] += (gradH[i] * a[j]);
}
}
}
答案 0 :(得分:0)
您要将所有std::vector
复制到函数中
void NeuralNetwork::train(std::vector<double> a, std::vector<double> target)
改用引用:
void NeuralNetwork::train(const std::vector<double>& a, const std::vector<double>& target)
复制向量是在空间和时间上的O(n)
操作,而使用引用在两者中都是O(1)
。
const std::vector
参考不能被修改,在修改后将向量复制进出的时候:
std::vector<double> NeuralNetwork::derivation(std::vector<double> a)
改用非常量引用:
void NeuralNetwork::derivation(std::vector<double>& a)
答案 1 :(得分:0)
原来我只是个白痴,不了解调试/发布,使这个程序发布只是解决问题,谢谢大家的帮助