
實現時遇到一個問題,就是fi的值的設定問題,因為我們采用隨機梯度下降法,一方面這節省了時間,但是如果fi值亙古不變的話可能會面臨跳來跳去一直找不到答案的問題,所以我這里設定他得知在每一輪之后都會按比例減小(fi *= 0.5;),大家可以按自己的喜好自由設定。
import java.util.Scanner;
public class Perceptron {
private static int N = 3;
private static int n = 2;
private static double[][] X = null;
private static double[] Y = null;
private static double[] W = null;
private static double B = 0;
private static double fi = 0.5;
private static boolean check(int id) {
double ans = B;
for(int i=0;i<n;i++)
ans += X[id][i] * W[i];
if(ans * Y[id] > 0) return true;
return false;
}
private static void debug() {
System.out.print("debug: W");
for(int i=0;i<n;i++) System.out.print(W[i] + " ");
System.out.println("/ B : " + B);
}
public static void solve() {
Scanner in = new Scanner(System.in);
System.out.print("input N:"); N = in.nextInt();
System.out.print("input n:"); n = in.nextInt();
X = new double[N][n];
Y = new double[N];
W = new double[n];
System.out.println("input N * n datas X[i][j]:");
for(int i=0;i<N;i++)
for(int j=0;j<n;j++)
X[i][j] = in.nextDouble();
System.out.println("input N datas Y[i]");
for(int i=0;i<N;i++)
Y[i] = in.nextDouble();
for(int i=0;i<n;i++) W[i] = 0;
B = 0;
boolean ok = true;
while(ok == true) {
ok = false;
//這里在原來算法的基礎上不斷地將fi縮小,以避免跳來跳去一直達不到要求的點的效果。
for(int i=0;i<N;i++) {
//System.out.println("here " + i);
while(check(i) == false) {
ok = true;
for(int j=0;j<n;j++)
W[j] += fi * Y[i] * X[i][j];
B += fi * Y[i];
//debug();
}
}
fi *= 0.5;
}
}
public static void main(String[] args) {
solve();
System.out.print("W = [");
for(int i=0;i<n-1;i++) System.out.print(W[i] + ", ");
System.out.println(W[n-1] + "]");
System.out.println("B = " + B);
}
}
posted on 2015-03-20 11:08
marchalex 閱讀(634)
評論(0) 編輯 收藏 所屬分類:
java小程序