感知机的java实现

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 + "]";
}


}

输出的结果


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值