用C ++实现的感知器未按预期训练。 (AND逻辑门示例)

问题描述 投票:0回答:1

下面提供了我的Perceptron实现。

FOR循环的最后一次迭代给出结果:

输入:0输入:0

输出:0.761594

错误:-0.761594

经过如此多的训练样本后,显然是错误的。

最后几行代码给出结果:

输入:1输入:1

输出:0.379652

错误:0.620348

哪一次又错了并且要走...

(全部关于构造函数中的随机权重值。)

但是,如果我仅迭代示例值(1,1,1),则每次迭代的结果将接近于1,这就是它应该如何工作的。

所以我想知道这可能是什么原因,因为感知器应该能够学习AND门,因为输出是线性可分离的。

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#include <math.h>


#define println(x) std::cout<<x<<std::endl;
#define print(x) std::cout<<x;
#define END system("PAUSE"); return 0
#define delay(x) Sleep(x*1000);

typedef unsigned int uint;



class perceptron
{
public:
    perceptron() :learningRate(0.15),biasValue(1),outputVal(0)
    {
        srand((uint)time(0));
        weights = new double[2];
        weights[0] = rand() / double(RAND_MAX);
        weights[1] = rand() / double(RAND_MAX); 
    }
    ~perceptron()
    {
        delete[] weights;
    }
    void train(double x0, double x1, double target)
    {
        backProp(x0, x1, target);
    }
private:
    double biasValue;
    double  outputVal;
    double* weights;
    double learningRate;
private:
    double activationFunction(double sum)
    {
        return tanh(sum);
    }
    void backProp(double x0, double x1, double target)
    {
        println("");

        guess(x0, x1); //Setting outputVal to activationFunction value

        //Calculating Error;

        auto error = target - outputVal;

        //Recalculating weights;

        weights[0] = weights[0] + error * x0 * learningRate;   
        weights[1] = weights[1] + error * x1 * learningRate;

        //Printing values;

        std::cout << "Input:  " << x0 << "   Input:   " << x1 << std::endl;
        std::cout << " Output:   " << outputVal << std::endl;
        std::cout << "Error:   " << error << std::endl;
    }
    double guess(double x0, double x1)
    {
        //Calculating outputValue

        outputVal = activationFunction(x0 * weights[0] + x1 * weights[1]+biasValue);

        return outputVal;
    }
};

int main()
{
    perceptron* p = new perceptron();
    for (auto i = 0; i < 1800; i++)
    {
        p->train(1, 1, 1);
        p->train(0, 1, 0);
        p->train(1, 0, 0);
        p->train(0, 0, 0);
    }
    println("-------------------------------------------------------");
    delay(2);
    p->train(1, 1, 1);
    END;
}
c++ perceptron
1个回答
0
投票

我看到一些问题:

  1. 感知激活不应为tanh()。如果使用它,则必须确保适当地计算梯度。但是您可以通过
  2. 替换激活
double activationFunction(double sum)
{
    return sum > 0;
}

如果sum> 1,则返回1,否则返回零。

  1. 更新权重时,还应更新biasValue。您可以使用
  2. 更新它
biasValue += error * learningRate;

这些更改将使感知器学习“与”门。

© www.soinside.com 2019 - 2024. All rights reserved.