感知机算法的C语言实现(共4页).doc
精选优质文档-倾情为你奉上感知机算法的C语言实现维数n=3时,分别取M=10,M=20,M=30(1) 当M=10时,收敛时,迭代次数K=1,权矩阵矢量为W=-0.,0.,-0.,阈值,正确分类个数为26个。正确分类率。(2) 当M=20 时,收敛时,迭代次数K=20,权矩阵矢量为W=-0.,0.,0.,阈值,正确分类个数为28个。正确分类率为。(3) 当M=30时,收敛时,迭代次数K=2,权矩阵矢量为W=-0.,-0.,0.,阈值,正确分类个数为30个。正确分类率为。维数n=5时,分别取M=10,M=20,M=30(1) 当M=10时,收敛时,迭代次数K=2,权矢量矩阵为W=-0.,0.,0.,-0.,0.,阈值,正确分类个数为26个。正确分类率为。(2) 当M=20时,收敛时,迭代次数K=2,权矩阵矢量为W=-0.,-0.,-0.,-0.,0.,阈值,正确分类个数为27个。正确分类率为。(3) 当M=30时,收敛时,迭代次数K=2,权矢量矩阵为W=-0.,-0.,0.,0.,0.,阈值。正确分类个数为30个。正确分类率为。程序如下所示:#include<stdio.h>#include<stdlib.h>#include<time.h>#include<math.h>#define PI 3.#define COUNT 30 /样本训练次数#define DIMEN 5 / 输入样本维度/*函数名:ran_f函数功能:产生0到1之间均匀分布的随机数接口参数: *p double型指针变量函数返回值 a double型*/double ran_f(double*p) double a;srand(unsigned) time(NULL);*p = rand();a = *p / 32767.0;return(a);void main()double xCOUNTDIMEN; / 输入样本训练数据 int yCOUNT; / 训练输出int dCOUNT; / 理想输出double WCOUNT; / 权值矩阵double thres; / 阈值double eps = 0.00001; / 进行收敛判断的条件double deta = 0.2; / 学习因子double r1 = 3.0; / 随机数种子double xt305; /测试数据int dt30; /理想数据输出double m1, m2, s, dp, ep; / dp为理想输出与实际输出的差,ep为均方误差int yt30; /测试输出 int count = 0; /测试正确的数目 double Rate; /正确分类率int i, j, k; for(i = 0; i < COUNT; i+)for(j = 0; j < DIMEN; j+)m1 = ran_f(r); /产生均匀分布的随机数m2 = ran_f(r);xij = sqrt(-2 * log(m1) * sin(2 * PI * m2); /产生正态分布随机数if(xi1 >= 0)di = 1;elsedi = 0;srand(unsigned)time(NULL); for(j = 0; j < DIMEN; j+) /对权值、阈值进行初始化,随机产生-1,1间的数Wj = (2.0 * rand() / RAND_MAX - 1) ; thres = (2.0 * rand() / RAND_MAX - 1) ; k = 0; /迭代次数while(1)ep = 0;for(i = 0; i < COUNT; i+)s = 0;for(j = 0; j < DIMEN; j+)s += Wj * xij; s = s - thres;if(s >= 0)yi = 1;elseyi = 0;dp = (double)(di - yi);for(j = 0; j < DIMEN; j+)/更新权值、阈值Wj = Wj + deta * dp * xij;thres = thres - deta * dp;dp = (dp * dp) / 2.0;ep += dp;k+;if(ep <= eps) / 如果均方误差ep小于等于设定的收敛条件值,则认定均方差最小,达到系统收敛,则跳出循环。break;printf("迭代次数=%dn",k);printf("权值:n");for(j = 0; j < DIMEN; j+)printf("%fn",Wj);printf("阈值:n");printf("%fn",thres); /* 用30个新矢量验证系统*/for(i = 0; i < 30; i+)for(j = 0; j < DIMEN; j+)m1 = ran_f(r); /产生均匀分布随机数m2 = ran_f(r);xtij = sqrt(-2 * log(m1) * sin(2 * PI * m2);/产生正态分布随机数if(xti1 >= 0)dti = 1;elsedti = 0;s = 0;for(j = 0; j < DIMEN; j+) /计算测试输出s += Wj * xij;s = s - thres;if(s >= 0)yi = 1;elseyi = 0;if(dti = yi)count+; printf("正确分类个数=%dn",count);Rate = (double)(count / 30.0);printf("分类正确率:n");printf("%f",Rate);专心-专注-专业