Professional Documents
Culture Documents
Perceptron 3inputrand
Perceptron 3inputrand
#include <iostream>
2: #include <math.h>
3: #include <cstdlib>
4:
5: using namespace std;
6:
7: int step(float x) {
8: if(x>=0)
9: return 1;
10: else //for negative value
11: return 0;
12: }
13:
14: float r_weight(){
15: float r;
16: r = ((float)rand() / RAND_MAX)*0.5;
17: if((rand() % 3+1)==1){
18: r=r*‐1;
19: }
20: return r;
21: }
22:
23: main(){
24: //cout<<step(0); //for checking
25:
26: // yd=output desire | ys=actual output |
27: float x1[8], x2[8], x3[8], yd[8], ya[8], e[8], dw1, dw2, dw3;
28: float w1 = r_weight(), w2 = r_weight(), w3 = r_weight(), t=0.2, a=0.1, sumOferr=1;
29:
30: //assign input AND operation
31: x1[0]=0;x2[0]=0;x3[0]=0;yd[0]=0;
32: x1[1]=0;x2[1]=1;x3[1]=0;yd[1]=0;
33: x1[2]=1;x2[2]=0;x3[2]=0;yd[2]=0;
34: x1[3]=1;x2[3]=1;x3[3]=0;yd[3]=0;
35: x1[4]=0;x2[4]=0;x3[4]=1;yd[4]=0;
36: x1[5]=0;x2[5]=1;x3[5]=1;yd[5]=1;
37: x1[6]=1;x2[6]=0;x3[6]=1;yd[6]=1;
38: x1[7]=1;x2[7]=1;x3[7]=1;yd[7]=1;
39:
40:
41: //create loop
42: int epoch=1;
43:
44: while(sumOferr!=0){
45:
46: sumOferr=0;
47: cout<<"epoch "<<epoch<<"‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐"<<endl;
48:
49: for(int c=0; c<8; c++){
50: //equation actual output
51: ya[c]=step((x1[c]*w1)+(x2[c]*w2)+(x3[c]*w3)‐t);
52: //calculate error
53: e[c]=yd[c] ‐ ya[c];
54:
55: //calculate weight change
56: dw1=a*x1[c]*e[c];
57: dw2=a*x2[c]*e[c];
58: dw3=a*x3[c]*e[c];
59: //update wieght
60: w1=w1+dw1;
61: w2=w2+dw2;
62: w3=w3+dw3;
63:
64: sumOferr+=e[c]*e[c];
65: //print output
66: cout<<"x1: "<<x1[c]<<" x2: "<<x2[c]<<" yd: "<<yd
[1]=0;
67:
68: } //end FOR
69:
70: //sumOferr=0;
71: epoch++;
72: }//end while
73: } //end main