代码说明:w和b为感知机模型参数,w就是weight叫做权值,或者叫weight ector, 叫做偏置,(bias)
f(x) = w.x+b
package org.ansj.ml;
import java.util.Arrays;
public class Perceptron {
public static void main(String[] args) {
//三个点
int[][] T = { { 3, 3 }, { 4, 3 }, { 1, 1 } };
//定义应三个点类别
int[] Y = { 1, 1, -1 };
//利用T度下降法,初始值w,b为0,minL(w,b),线性公式:wx+b
double[] w = new double[] { 0, 0 };
double b = 0;
boolean flag = true;
do {
flag = false;
for (int i = 0; i < Y.length; i++) {
int[] x = T[i];
int y = Y[i];
//如果没有正确的分类,更新w,b , 这里,w是一个向量,与x求内积,当小于等于0时说明被错误的分类
if (y * ((w[0] * x[0] + w[1] * x[1])+b) <= 0) {
w[0] = w[0] + x[0] * y;
w[1] = w[1] + x[1] * y;
b = b + y;
flag = true;
System.out.println(Arrays.toString(w)+"\t"+b);
}
}
} while (flag);
}
}