两层感知器网络实现异或问题

来源:互联网 发布:淘宝开发团队多少人 编辑:程序博客网 时间:2024/04/20 07:09







#include <stdio.h>#include <stdlib.h>//样例结构体struct sample{int A;int B;int Classs;};//f函数double f(double *weight,int A,int B){return weight[0]+weight[1]*A+weight[2]*B;}//感知器函数int sgn(double y){if (y>0.000000000001)return 1;elsereturn 0;}//步长函数double getStep(double weight,int t,int o,int x){double rate = 0.01;//学习速率return weight+rate*(t-o)*x;}//学习权值void learnWeightOfAandNonB(double *weight,struct sample *sampleColletion){int i,j;int maxTimes=500;int isRight=0;int result=0;for (i=0;i<maxTimes;++i){isRight=0;for (j=0;j<4;++j){result = sgn(f(weight,sampleColletion[j].A,sampleColletion[j].B));if (result == sampleColletion[j].Classs){isRight++;}else{weight[1] = getStep(weight[1],sampleColletion[j].Classs,result,sampleColletion[j].A);weight[2] = getStep(weight[2],sampleColletion[j].Classs,result,sampleColletion[j].B);}}if (isRight == 4){break;}}if (i == maxTimes){printf("超过最大迭代次数,程序结束------weight_AandNonB\n");exit(0);}}//学习权值void learnWeightOfAxorB(double *weight,double *weight_AandNonB,struct sample *sampleColletion){int i,j;int maxTimes=500;int isRight=0;int result=0;int tempA,tempB;for (i=0;i<maxTimes;++i){isRight=0;for (j=0;j<4;++j){tempA = sgn(f(weight_AandNonB,sampleColletion[j].A,sampleColletion[j].B));tempB = sgn(f(weight_AandNonB,sampleColletion[j].B,sampleColletion[j].A));result = sgn(f(weight,tempA,tempB));if (result == sampleColletion[j].Classs){isRight++;}else{weight[1] = getStep(weight[1],sampleColletion[j].Classs,result,tempA);weight[2] = getStep(weight[2],sampleColletion[j].Classs,result,tempB);}}if (isRight == 4){break;}}if (i == maxTimes){printf("超过最大迭代次数,程序结束------weight_AxorB\n");exit(0);}}int main(void){int i=0;double weight_AandNonB[3] ={-0.1,-0.1,-0.1};//初始化权值double weight_AxorB[3] ={-0.1,-0.1,-0.1};struct sample AandNonB[4]={{0,0,0},{0,1,0},{1,0,1},{1,1,0}};//初始化样例struct sample AxorB[4]={{0,0,0},{0,1,1},{1,0,1},{1,1,0}}; //输出原始权值printf("原始权值\nweight_AandNonB\n");for(i=0;i<3;++i){printf("%.2f\t",weight_AandNonB[i]);}printf("\nweight_AxorB\n");for(i=0;i<3;++i){printf("%.2f\t",weight_AxorB[i]);}printf("\n\n\n\n");learnWeightOfAandNonB(weight_AandNonB,AandNonB);learnWeightOfAxorB(weight_AxorB,weight_AandNonB,AxorB);//输出学习后权值printf("学习后权值\nweight_AandNonB\n");for(i=0;i<3;++i){printf("%.2f\t",weight_AandNonB[i]);}printf("\nweight_AxorB\n");for(i=0;i<3;++i){printf("%.2f\t",weight_AxorB[i]);}printf("\n\n\n");return 0;}


结果:



0 0
原创粉丝点击