一个简单的ANN算法

#include <stdio.h>  
#include <stdlib.h>
#include <time.h>  
  
int M[10] = {0};                                //权值  
int X[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    //输入向量  
int Y[10] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0};     //理想输出向量 注:1 表示奇数; 0 表示偶数  
int O[10] = {0};                                //保存输出向量  
int ST = 52;                                    //阈值,默认值:52  
  
//初始化权值  
void initM()  
{  
    srand((unsigned int)time(0));  
      
    for (int x=0; x<10; ++x)  
    {  
        //初始化权值所使用的随机数在 0 - 99 之间  
        M[x] = rand()%100;  
    }  
}  
  
//激活函数  
int active(int m, int x)  
{  
    int o = m * x;  
      
    if (o > ST)  
    {  
        return 0;  
    }  
    else  
    {  
        return 1;  
    }  
}  
  
//计算输出向量  
void calcY()  
{  
    for (int x=0; x<10; ++x)  
    {  
        O[x] = active(M[x], X[x]);  
    }  
}  
  
//根据实际输出向量和理想输出向量调整权向量,返回实际输出和理想输出不匹配的数目  
int adjustM()  
{  
    int err = 0;  
    for (int x=0; x<10; ++x)  
    {  
        if (O[x] != Y[x])  
        {  
            err++;  
              
            if (1 == O[x])  
            {  
                M[x] += X[x];  
            }  
            else  
            {  
                M[x] -= X[x];  
            }  
        }  
    }  
      
    return err;  
}  
  
//打印权向量  
void printM()  
{  
    printf("\n最终训练结果:\n");  
    for (int x=0; x<10; ++x)  
    {  
        printf("M[%i] = %i\n", x, M[x]);  
    }  
}  
  
//测试已经训练好的ANN  
void test(int input)  
{  
    if ( 0==active(M[input], X[input]) )  
    {  
        printf("%d 是 偶数 ", input+1);  
    }  
    else  
    {  
        printf("%d 是 奇数 ", input+1);  
    }  
      
    printf("\n\n");  
}  
  
//主函数入口  
int main()  
{  
    printf("请输入阈值:");  
    scanf("%d", &ST);  
    printf("\n");  
      
    initM();  
      
    int n = 0;  
    //一直训练直到能够100%正确为止  
    while (1)  
    {  
        n++;  
        calcY();  
        int err = adjustM();  
        if (0 >=err)  
        {  
            //能够100%正确地回答问题了,结束训练  
            break;  
        }  
        printf("第%0.2d次训练后的结果中存在的错误数 %d\n", n,err);  
    }  
      
    printM();  
    printf("\n阈值=%d 训练次数=%d\n\n", ST, n);  
      
    while (true)  
    {  
        int a = 0;  
        printf("请输入范围为1~10的数字:");  
        scanf("%d", &a);  
        if (1 > a || 10 < a)  
        {  
            break;  
        }  
          
        test(a-1);  
    }  
      
    return 0;  
} 

  

猜你喜欢

转载自www.cnblogs.com/secondwatch/p/8974571.html