Last active
August 29, 2015 14:22
-
-
Save linmx0130/3447a30eb92d8fe391c1 to your computer and use it in GitHub Desktop.
Simple Perceptron Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstring> | |
#include <cstdlib> | |
#include <cmath> | |
#include <ctime> | |
#define MAXN 20 | |
#define ETA 0.1 | |
struct Graph{ | |
int tot,Head[MAXN],Pre[MAXN*MAXN],U[MAXN*MAXN],V[MAXN*MAXN]; | |
double W[MAXN*MAXN]; | |
void AddEdge(int u,int v,double w){ | |
++tot; | |
U[tot]=u; | |
V[tot]=v; | |
W[tot]=w; | |
Pre[tot]=Head[u]; | |
Head[u]=tot; | |
} | |
}g; | |
int Input[MAXN],TOutput[MAXN],Output[MAXN]; | |
void getOutput(){ | |
double h[MAXN]; | |
memset(h,0,sizeof(h)); | |
for (int u=0;u<=2;++u){ | |
for (int p=g.Head[u];p;p=g.Pre[p]){ | |
h[g.V[p]]+=g.W[p]*Input[u]; | |
} | |
} | |
for (int i=3;i<=6;++i){ | |
if (h[i]>0){ | |
Output[i]=1; | |
}else{ | |
Output[i]=0; | |
} | |
} | |
} | |
void modifyWeight(){ | |
for (int u=0;u<=2;++u){ | |
for (int p=g.Head[u];p;p=g.Pre[p]){ | |
g.W[p]=g.W[p]-ETA*(Output[g.V[p]]-TOutput[g.V[p]])*Input[u]; | |
} | |
} | |
} | |
void outputWeight(){ | |
double o[MAXN][MAXN]; | |
for (int i=0;i<=2;++i){ | |
for (int p=g.Head[i];p;p=g.Pre[p]){ | |
o[i][g.V[p]]=g.W[p]; | |
} | |
} | |
printf("{ \n"); | |
for (int i=0;i<=2;++i){ | |
for (int j=3;j<=6;++j){ | |
printf("%lf, ",o[i][j]); | |
} | |
printf("\n"); | |
} | |
printf("}\n"); | |
} | |
double getDoubleRand(){ | |
return ((double)rand())/32768; | |
} | |
int main(){ | |
//Init | |
srand(time(0)); | |
for (int i=1;i<=2;++i){ | |
for (int j=3;j<=6;++j){ | |
g.AddEdge(i,j,getDoubleRand()/100); | |
} | |
} | |
// 0 point: bias | |
for (int i=3;i<=6;++i){ | |
g.AddEdge(0,i,getDoubleRand()/100); | |
} | |
Input[0]=1; | |
outputWeight(); | |
//Train | |
for (int i=0;i<50001;++i){ | |
int a=Input[1]=(getDoubleRand()>0.5)?1:0; | |
int b=Input[2]=(getDoubleRand()>0.5)?1:0; | |
TOutput[3]=a|b; | |
TOutput[4]=a&b; | |
TOutput[5]=a?0:1; | |
TOutput[6]=a^b; | |
getOutput(); | |
modifyWeight(); | |
if (i%1000==0){ | |
printf("I={%d,%d}\n",Input[1],Input[2]); | |
printf("TO={%d,%d,%d,%d}\n",TOutput[3],TOutput[4],TOutput[5],TOutput[6]); | |
printf("O={%d,%d,%d,%d}\n",Output[3],Output[4],Output[5],Output[6]); | |
outputWeight(); | |
} | |
} | |
//Test | |
while (1){ | |
printf("input a,b:"); | |
if (scanf("%d%d",&Input[1],&Input[2])!=2) break; | |
getOutput(); | |
printf("a OR b = %d\n",Output[3]); | |
printf("a AND b = %d\n",Output[4]); | |
printf("NOT a = %d\n",Output[5]); | |
printf("a XOT b = %d\n",Output[6]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment