人工智能——神经网络算法初体验

来源:互联网 发布:计字器软件 编辑:程序博客网 时间:2024/06/16 19:46

转自http://blog.csdn.net/cnyali/article/details/50864942

这个程序其实就是让人工智能学习并认识怎么判断一个0~9的数是奇数还是偶数,最简单的人工智能程序

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 感知器判断数字奇偶性   
  2. #include<stdlib.h>  
  3. #include<stdio.h>  
  4. #include<time.h>  
  5.   
  6. int M[10];//权值   
  7. int X[10]={1,2,3,4,5,6,7,8,9,10};//输入向量   
  8. int Y[10]={1,0,1,0,1,0,1,0,1,0};//理想输出向量,0,奇数,1,偶数   
  9. int O[10];//保存输出向量   
  10. int ST=52;//阈值   
  11.   
  12. void initM(){//初始化权值      
  13.     srand((unsigned int)time(0));  
  14.     for(int x=0;x<10;++x)  
  15.         M[x]=rand()%100;  
  16. }   
  17.   
  18. int active(int m,int x){// 跃迁型激活函数    
  19.     int o=m*x;  
  20.     if(o>ST)return 1;  
  21.     else return 0;  
  22. }  
  23.   
  24. void calcY(){//计算输出向量   
  25.     for(int x=0;x<10;++x)  
  26.         O[x]=active(M[x],X[x]);  
  27. }  
  28.   
  29. //根据实际输出向量和理想输出向量调整权向量,  
  30. //返回实际输出和理想输出不匹配的数目  
  31. int adjustM(){  
  32.     int err=0;  
  33.     for(int x=0;x<10;++x)  
  34.         if(O[x]!=Y[x]){  
  35.             err++;  
  36.             if(0==O[x])  
  37.                 M[x]+=X[x];  
  38.             else  
  39.                 M[x]-=X[x];  
  40.         }   
  41.     return err;  
  42. }  
  43.   
  44. void printM(){//打印权向量   
  45.     for(int x=0;x<10;++x)  
  46.         printf("M[%i]=%i\n",x,M[x]);  
  47. }  
  48.   
  49. void test(int input){  
  50.     printf("[%i][%i]",M[input],X[input]);  
  51.     if(active(M[input],X[input]))  
  52.         printf("%d 是偶数\n",input);  
  53.     else  
  54.         printf("%d 是奇数\n",input);  
  55. }  
  56.   
  57. int main(){  
  58.     int n=0;  
  59.     initM();  
  60.     while(1){// 一直训练直到能够100%正确为止    
  61.         n++;  
  62.         calcY();  
  63.         int err=adjustM();  
  64.         if(0>=err)break;//能够 100 %正确地回答问题了,结束训练  
  65.         printf("错误数%d\n",err);  
  66.     }  
  67.     printM();  
  68.     printf("阈值%d 训练次数%d\n",ST,n);  
  69.       
  70.     while(1){  
  71.         int a=0;  
  72.         scanf("%i",&a);  
  73.         if(0>a || 9<a)break;  
  74.         test(a);  
  75.     }  
  76.     return 0;  
  77. }  

0 0
原创粉丝点击