以前写的算法。(数据集见图)
package BP;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;
public class BackPropagation {
public class Sample//样本
{
private double[] attributes=new double[4];//样本属性值
private int label;//样本标签
Sample(double[] attributes,int label)//构造函数
{
for(int i=0;i<this.attributes.length;i++)
{
this.attributes[i]=attributes[i];
}
this.label= label;
}
public int getLabel()//获取样本标签
{
return this.label;
}
public double[] getAttributes()//返回样本的属性组
{
return this.attributes;
}
public double compute(double[] weights)//计算该样本属性与对应的权值的乘积和
{
int i;
double num=0;
for (i = 0; i < weights.length - 1; i++)
{
num += weights[i] * this.attributes[i];
}
num -= weights[weights.length - 1] * 1;// 偏置
return num;
}
public void show()//输出样本的属性和标签
{
int i;
for(i=0;i<this.attributes.length;i++)
{
System.out.printf(this.attributes[i]+" ");
}
System.out.println(this.label);
}
}
public double compute(double[] d,double[] weights)//计算两个数组的乘积和
{
int i;
double num=0;
for (i = 0; i < weights.length - 1; i++)
{
num += d[i]*weights[i];
}
num -= weights[weights.length - 1] * 1;// 偏置
return num;
}
//计算sigmoid函数的输出值
public double sigmoid(double x)
{
return 1.0/(1.0+Math.exp((-1.0)*x));
}
//初始化权值,随机产生0~1之间的数
public void init_weight(double[][] ih_weights,double[] ho_weights)
{
int i,j;
Random r = new Random();
for(i=0;i<ih_weights.length;i++)//初始化输入层到隐藏层的权值
{
for(j=0;j<ih_weights[0].length;j++)
{
ih_weights[i][j]= r.nextInt(10)/10.0;
}
}
for (i = 0; i < ho_weights.length; i++)//初始化隐藏层到输出层的权值
{
ho_weights[i]= r.nextInt(10)/10.0;
}
}
//加载数据集
public void load_datas(String filename,ArrayList<Samp