最简单的神经网络算法

参考:http://blog.csdn.net/helloaya/article/details/4224425

人工神经网络算法是模拟人的神经网络的一种算法.

该算法像人一样,具有一定的学习能力。人工神经网络可以学会它所能表达的任何东西.

该算法在模拟人类抽象思维方面较传统的算法具有优势,如图像识别 (人脸识别,车牌识别), 声音识别方面已经有成熟的运用。

举个简单的例子可以说明人工神经网络和传统算法的差别所在 (等会也要实现):

假设要解决这个问题: 写一个程序, 判断 0, 1, 2, 3 ... 9 这10个数的奇偶性

1. 如果是传统算法, 则是模拟人的逻辑思维,对这个问题进行形式化和逻辑化 :

if (input 模  2  == 零) {

    input 是 偶数

} else {

    input 是 奇数

}

2. 如果是ANN算法,则要提供一组正确的数据对处理这个问题的神经网络ANN进行训练 :

未进行训练的神经网络,就像刚出生的婴儿一样,什么都不懂。这个时候, 你要教他 0 是偶数,  1是奇数....,

教完之后问ANN懂了没有,懂了则停止训练 (网络已经形成),不懂则继续训练.

while (1) {

    训练;

    if (测试通过)  {

         跳出循环;

    } 

}

训练完之后,这个ANN以后便能够正确处理 奇偶性判断的问题了.

处理上面这个问题,只需要模拟一个神经元即可,再复杂的问题,可能需要多个神经元,再再复杂,需要多层多神经元的配合来实现 (以后再研究)

//感知器判断数字奇偶性
//关键点,阈值应该怎么定
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>

using namespace std;

int M[10];//权值
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};//理想输出向量,0表示奇数,1表示偶数
int O[10];//保存输出向量
int ST=52;//阈值

void initM()
{
	int x =0;
	srand((unsigned int)time(0));
	for(x=0;x<10;++x)
	{
		M[x]=rand()%100;
	}
}
/**?跃迁型激活函数?**/
int active(int m, int x)
{
	int o=m*x;
	if(o>ST)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
//计算输出向量
void calcY()
{
	int x=0;
	for(x=0;x<10;++x)
	{
		O[x]=active(M[x],X[x]);
	}
}
//根据实际输出向量和理想输出向量调整权向量,返回实际输出和理想输出不匹配的数目
int adjustM()
{
	int err=0;int x=0;
	for(x=0;x<10;++x)
	{
		if(O[x]!=Y[x])
		{
			err++;
			if(0==O[x])
			{
				M[x]+=X[x];
			}
			else
			{
				M[x]-=X[x];
			}
		}
	}
	return err;
}
/**?打印权向量?**/
void printM()
{
	int x=0;
	for(x=0;x<10;++x)
	{
		printf("M[%d]=%d
",x,M[x]);
	}
}

void test(int input)
{
	printf("[%d][%d]",M[input],X[input]);
	if(active(M[input],X[input]))
	{
		printf("%d是偶数
",input);
	}
	else
	{
		printf("%d是奇数
",input);
	}
}

int main()
{
	int n=0;
	initM();
	/**?一直训练直到能够100%正确为止?**/
	while(1)
	{
		n++;
		calcY();
		int err=adjustM();
		if(0>=err)
		{
			//能够?100?%正确地回答问题了,结束训练
			break;
		}
		cout<<"错误数"<<err<<endl;
	}
	printM();
	printf("阈值%d训练次数%d
",ST,n);
	while(1)
	{
		int a=0;
		scanf("%d",&a);
		if(0>a||9<a)
		{
			break;
		}
		test(a);
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/striver-zhu/p/4688133.html