import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class neuralnetwork
{
public static void main(String[] args)
{
int[] input = new int [32];
double[][] hiddenWeight = new double[14][32];
double[] outweight = new double[14];
double[] hiddenout = new double[14];
double rate = 0.1;
double output;
double error;
double outT;
double[] hiddenoutT = new double[14];
int right =0;
for(int i = 0; i < 14; i++) //初始化权值
{
for(int j = 0; j < 32 ; j++)
{
hiddenWeight[i][j] = Math.random();
}
outweight[i] = Math.random();
}
ArrayList<Integer> input1 = new ArrayList<Integer>();
for(int i = 0; i<100; i++) //训练
{
for(int j =0; j < 1000; j++)
{
if(i==0)
{
input1.add((int)(Math.random()*100));
}
input = toBinaryNum(input1.get(j));
for(int k = 0; k < 14; k++)
{
double sum = 0;
for(int l = 0; l < 32; l++)
{
sum += input[l] * hiddenWeight[k][l];
}
hiddenout[k] = 1 / (1 + Math.exp(-sum));
}
double sum = 0;
for(int k = 0; k < 14; k++)
{
sum += hiddenout[k] * outweight[k];
}
output = 1/(1+Math.exp(-sum));
error = input[31] - output; //开始回溯
outT =error*output*(1-output);
for(int k = 0; k < 14; k++)
{
outweight[k] += rate * outT * hiddenout[k];
}
for(int k = 0; k < 14; k++)
{
hiddenoutT[k] = hiddenout[k]*(1-hiddenout[k])*(outweight[k])*outT;
for(int l = 0; l < 32; l++)
{
hiddenWeight[k][l] += rate * hiddenoutT[k] * input[l];
}
}
}
Collections.shuffle(input1);
}
for(int i =0; i < 10000; i++) //验证结果
{
input = toBinaryNum((int)(Math.random()*100));
for(int k = 0; k < 14; k++)
{
double sum = 0;
for(int l = 0; l < 32; l++)
{
sum += input[l] * hiddenWeight[k][l];
}
hiddenout[k] = 1 / (1 + Math.exp(-sum));
}
double sum = 0;
for(int k = 0; k < 14; k++)
{
sum += hiddenout[k] * outweight[k];
}
output = 1/(1+Math.exp(-sum));
output = Math.round(output);
if(output == input[31])
{
right++;
}
System.out.println(right*100.0/10000);
}
}
public static int[] toBinaryNum(int num) //将十进制转为二进制
{
int[] BinaryNum =new int[32];
for(int i = 31; i >= 0; i--)
{
BinaryNum[i] = num % 2;
num /= 2;
}
return BinaryNum;
}
}
以后会更新其他写法,和关于BP的更多应用。