尝试在C中实现感知器,无法进行训练。 输出总是只有零,我不知道什么是错的。 虽然,我怀疑它可能是delta函数,或者我只是错误地实现了感知器。
提前感谢所有帮助过的人!
#include<stdio.h>
#define arrayLength(x) (sizeof(x) / sizeof((x)[0]))
typedef int bool;
enum { false, true };
int main(){
float trainInputs [2][2] = {{0.0f, 1.0f}, {0.0f, 0.0f}};
float trainOutputs [2][1] = {{1.0f}, {0.0f}};
int amontOfTrainData = 1;
float inputs [] = {0.0f, 1.1f};
float outputs [] = {0.0f};
float wights [(arrayLength(inputs) * arrayLength(outputs))] = {0.5f, 0.5f, 0.5f, 0.5f};
float learningRate = 0.01f;
float delta(float actual, float want, float wight){
float error = want - actual;
float out = error * learningRate * wight;
printf(":%.6f:\n", out);
return out;
}
// Run perceptron
void run(bool train){
int outputInc = 0;
int wightInc = 0;
while(outputInc < arrayLength(outputs)){
int inputInc = 0;
while(inputInc < arrayLength(inputs)){
if(train){
int x = 0;
while(x < amontOfTrainData){
outputs[outputInc] = trainInputs[x][inputInc] * wights[wightInc];
wights[wightInc] = delta(outputs[outputInc], trainOutputs[x][outputInc], wights[wightInc]);
x++;
}
}else{
outputs[outputInc] = inputs[inputInc] * wights[wightInc];
}
inputInc++;
wightInc++;
}
//printf("out[%i]: %.5f\n", outputInc, outputs[outputInc]);
outputInc++;
}
}
int b = 0;
while(b < 100){
run(true);
b++;
}
printf("-----------[ 100 LOOPS DONE ]-----------\n");
run(false);
return 0;
}
答案 0 :(得分:1)
由于error
,learningRate
和wight
小于0,表达式error * learningRate * wight
也会趋于0。
delta
不应该是权重的新值,而是变化的数量,因此不是:
wights[wightInc] = delta(...);
尝试:
wights[wightInc] += delta(...);
(你使用哪种来源为感知器公式?)
答案 1 :(得分:1)
我已经应用了所有更改,这是最终的工作代码。 感谢所有帮助过我的人!
#include<stdio.h>
#include<stdbool.h>
#define arrayLength(x) (sizeof(x) / sizeof((x)[0]))
float trainInputs [2][2] = {{0.0f, 1.0f}, {0.0f, 0.0f}};
float trainOutputs [2][1] = {{1.0f}, {0.0f}};
int amontOfTrainData = 1;
float inputs [] = {1.0f, 1.0f};
float outputs [] = {0.0f};
float wights [(arrayLength(inputs) * arrayLength(outputs))] = {0.001f, 0.001f};
float learningRate = 0.1f;
float delta(float actual, float want, float wight)
{
float error = want - actual;
float out = error * learningRate * wight;
return out;
}
void run(bool train)
{
int outputInc = 0;
int wightInc = 0;
while(outputInc < arrayLength(outputs))
{
int inputInc = 0;
while(inputInc < arrayLength(inputs))
{
if(train)
{
int x = 0;
while(x < amontOfTrainData)
{
outputs[outputInc] = trainInputs[x][inputInc] * wights[wightInc];
wights[wightInc] += delta(outputs[outputInc], trainOutputs[x][outputInc], wights[wightInc]);
x++;
}
}
else
{
outputs[outputInc] = inputs[inputInc] * wights[wightInc];
}
inputInc++;
wightInc++;
}
printf("out[%i]: %.5f\n", outputInc, outputs[outputInc]);
outputInc++;
}
}
int main()
{
// Run neural network
int b = 0;
int loops = 500;
while(b < loops)
{
run(true);
b++;
}
printf("-----------[ %i LOOPS DONE ]-----------\n", loops);
run(false);
return 0;
}