VS2017 控制台应用(.NET Framework)代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace neuralNetworks
{
class singlePerceptron
{
int R, S;//r是输入向量的维数,s是输出向量的维数,这里取s=1;
public double[,] W;//权重矩阵w=int[s,r]
public double[,] B;//偏置向量b=[s,1]
public singlePerceptron(int inputDimension, int outputDimension)
{
R = inputDimension;
S = outputDimension;
init();
}
private void init() //初始化感知器
{
W = new double[S, R];
B = new double[S, 1];
}
public void train(double[,] inputs, int[] outputs) //训练感知器
{
int sampleCount = inputs.GetLength(0);//训练集样本个数
bool error = true;//出现计算结果和目标不一致
double sum;
int e;
while (error)
{ //用训练集迭代更新W,B
error = false;
for (int j = 0; j < sampleCount; j++)
{
for (int i = 0; i < S; i++)
{
//W[i]*inputs[j]+B[i],W[i]是R维的,B[i]是1维的
sum = 0;
for (int h = 0; h < R; h++)
{
sum = sum + W[i, h] * inputs[j, h];
}
sum = sum + B[i, 0];//传输函数
e = outputs[j] - transmissionFun.hardlim(sum, 0);//计算e值(误差)
if (e != 0)//修正权重值
{
error = true;
for (int h = 0; h < R; h++)
{
W[i, h] = W[i, h] + e * inputs[j, h];
}
B[i, 0] = B[i, 0] + e;
}
}
}
}
int sim(double[] input)
{
sum = 0;
for (int i = 0; i < S; i++)
{
for (int h = 0; h < R; h++)
{
sum = sum + W[i, h] * input[h];
}
sum = sum + B[i, 0];
}
return transmissionFun.hardlim(sum, 0);
}
void ToString()
{
}
}
static class transmissionFun
{
static public int hardlim(double v, double thresh)
{
if (v >= thresh)
return 1;
return 0;
}
}
}
} |
|