因為類神經網路課程順便寫的,盡量簡潔和只使用單一 class,開箱即用,希望可以幫助到大家。
氣死網路上完全查不到這類型的相關程式碼乾脆自己發。
底下就是單層感知機的實作
import java.util.ArrayList; import java.util.Random;
public class Perceptron { private double eta = 0.01; private int nIter = 50; private ArrayList<Integer> errors;
private double[] w;
public Perceptron() { }
public Perceptron(double eta, int nIter) { this.eta = eta; this.nIter = nIter; }
public void fit(double[][] x, double[] y) { Random random = new Random(); w = new double[x[0].length + 1]; errors = new ArrayList<>();
for (int i = 0; i < w.length; i++) { w[i] = random.nextGaussian(); }
for (int i = 0; i < nIter; i++) { int error = 0; for (int j = 0; j < y.length; j++) { double update = eta * (y[j] - predict(x[j])); w[w.length - 1] += update; for (int k = 0; k < x[j].length; k++) { w[k] += update * x[j][k]; } error += update != 0 ? 1 : 0; } errors.add(error); } }
public int epochError = 0;
public double[] epoch(double[][] x, double[] y, double[] w) { this.w = w; epochError = 0;
for (int j = 0; j < y.length; j++) { double update = eta * (y[j] - predict(x[j])); w[w.length - 1] += update; for (int k = 0; k < x[j].length; k++) { w[k] += update * x[j][k]; } epochError += update != 0 ? 1 : 0; } return w; }
private double dot(double[] x) { double pred = w[x.length]; for (int i = 0; i < x.length; i++) { pred += x[i] * w[i]; } return pred; }
private double dot(double[] x, double[] weight) { double pred = weight[x.length]; for (int i = 0; i < x.length; i++) { pred += x[i] * weight[i]; } return pred; }
public double predict(double[] x) { return dot(x) >= 0 ? 1 : -1; }
public double predict(double[] x, double[] w) { return dot(x, w) >= 0 ? 1 : -1; }
public ArrayList<Integer> getErrors() { return errors; }
public double[] getW() { return w; }
public void setW(double[] w) { this.w = w; } }
|
大概就這樣,不要拿走說是自己寫的就好。