import java.util.ArrayList;
import java.util.List;/**
* 数据是二维的感知机
* 参考《统计学习方法》 李航 2012年3月 第一版2.3节
* ThreadSafe
** @author Administrator
*
*/
public class Perceptron2 {
public static final double yita = 1;
/**
* 调整参数
*
* @param p
* @param d
* @param yita
*/
public void adjust(Param p, Dot d, double yita) {
p.w1 = p.w1 + yita * d.y * d.x1;
p.w2 = p.w2 + yita * d.y * d.x2;
p.b += yita * d.y;
}
/**
* 判断是否有误差
*
* @param p
* @param d
* @return
*/
public boolean hasError(Param p, Dot d) {
// 损失
double temp = d.y * ((p.w1 * d.x1 + p.w2 * d.x2) + p.b);
if (temp <= 0) {
return true;
}
return false;
}
public void train(Param p, List<Dot> list) {
boolean end = false;
while (!end) {
end = true;
for (int i = 0; i < list.size(); i++) {
// 有误差
if (hasError(p, list.get(i))) {
end = false;
// 调整参数
adjust(p, list.get(i), yita);
break;
}
}
}
}
public static void main(String[] args) {
//参数
Param param = new Param(0, 0, 0);
//添加点
List<Dot> list = new ArrayList<Dot>();
Dot d1 = new Dot(3, 3, 1);
list.add(d1);
Dot d2 = new Dot(4, 3, 1);
list.add(d2);
Dot d3 = new Dot(1, 1, -1);
list.add(d3);
Perceptron2 p = new Perceptron2();
//训练
p.train(param, list);
System.out.println("训练出的参数: "+param.toString());
}
}
/**
* 参数
*
* @author Administrator
*
*/
class Param {
double w1;
double w2;
double b;
public Param(double w1, double w2, double b) {
super();
this.w1 = w1;
this.w2 = w2;
this.b = b;
}
public double getW1() {
return w1;
}
public void setW1(double w1) {
this.w1 = w1;
}
public double getW2() {
return w2;
}
public void setW2(double w2) {
this.w2 = w2;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
@Override
public String toString() {
return "Param [w1=" + w1 + ", w2=" + w2 + ", b=" + b + "]";
}
}
/**
* 实例点
*
* @author Administrator
*
*/
class Dot {
double x1;
double x2;
double y;
public Dot(double x1, double x2, double y) {
super();
this.x1 = x1;
this.x2 = x2;
this.y = y;
}
public double getX1() {
return x1;
}
public void setX1(double x1) {
this.x1 = x1;
}
public double getX2() {
return x2;
}
public void setX2(double x2) {
this.x2 = x2;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
@Override
public String toString() {
return "Dot [x1=" + x1 + ", x2=" + x2 + ", y=" + y + "]";
}
}
输出的结果