#include<iostream> #include<stdlib.h> #include<math.h> using namespace std; #define innode 2 #define outnode 1 #define sample 4 class perceptron { public: perceptron(); ~perceptron(); double w[outnode][innode]; double b[outnode]; void init(); void train(double p[sample][innode], double t[sample][outnode]); void pattern(double *p); double randval(double low, double high); void initval(double w[], int n); int hardlim(double val); double lr; double error; }; int perceptron::hardlim(double val) { if (val >= 0.0) { return 1; } else { return 0; } } double perceptron::randval(double low, double high) { double val; val = ((double)rand() / (double)RAND_MAX) + (high - low) + low; return val; } void perceptron::initval(double w[], int n) { for (int i = 0; i < n; i++) { w[i] = randval(-0.01, 0.01); } } void perceptron::init() { initval((double*)w, innode*outnode); initval(b, outnode); } void perceptron::train(double p[sample][innode], double t[sample][outnode]) { double err[outnode]; double nodesum[outnode]; double nodeout[outnode]; double x[innode]; double d[outnode]; for (int i = 0; i < sample; i++) { for (int j = 0; j < innode; j++) { x[j] = p[i][j]; } for (int k = 0; k < outnode; k++) { d[k] = t[i][k]; } for (int k = 0; k < outnode; k++) { nodesum[k] = 0.0; for (int j = 0; j < innode; j++) { nodesum[k] += w[k][j] * x[j]; } nodeout[k] = hardlim(nodesum[k] + b[k]); } for (int k = 0; k < outnode; k++) { err[k] = (d[k] - nodeout[k]); for (int j = 0; j < innode; j++) { w[k][j] += lr*err[k] * x[j]; } } for (int k = 0; k < outnode; k++) { b[k] += lr*err[k]; } for (int k = 0; k < outnode; k++) { error += err[k]; } } } void perceptron::pattern(double* p) { double nodesum[outnode]; double nodeout[outnode]; double x[innode]; for (int i = 0; i < innode; i++) { x[i] = p[i]; } for (int k = 0; k < outnode; k++) { nodesum[k] = 0.0; for (int j = 0; j < innode; j++) { nodesum[k] += w[k][j] * x[j]; } nodeout[k] = hardlim(nodesum[k] + b[k]); } for (int i = 0; i < outnode; i++) { cout << nodeout[i] << endl; } } perceptron::perceptron() { lr = 0.001; error = 0.8; } perceptron::~perceptron() { } double X[sample][innode] = { { 0,0 }, { 0,1 }, { 1,0 }, { 1,1 } }; double Y[sample][outnode] = { { 0 }, { 0 }, { 0 }, { 1 } }; int main() { perceptron Perceptron; Perceptron.init(); int times = 0; while (abs(Perceptron.error)> 0.001&× < 10000) { times++; Perceptron.train(X, Y); } double m[innode] = { 1,1 }; Perceptron.pattern(m); return 0; }