class GaussianNB {
private double[] priors;
private double[][] sigmas;
private double[][] thetas;
public GaussianNB(double[] priors, double[][] sigmas, double[][] thetas) {
this.priors = priors;
this.sigmas = sigmas;
this.thetas = thetas;
}
public int predict(double[] features) {
double[] likelihoods = new double[this.sigmas.length];
for (int i = 0, il = this.sigmas.length; i < il; i++) {
double sum = 0.;
for (int j = 0, jl = this.sigmas[0].length; j < jl; j++) {
sum += Math.log(2. * Math.PI * this.sigmas[i][j]);
}
double nij = -0.5 * sum;
sum = 0.;
for (int j = 0, jl = this.sigmas[0].length; j < jl; j++) {
sum += Math.pow(features[j] - this.thetas[i][j], 2.) / this.sigmas[i][j];
}
nij -= 0.5 * sum;
likelihoods[i] = Math.log(this.priors[i]) + nij;
}
int classIdx = 0;
for (int i = 0, l = likelihoods.length; i < l; i++) {
classIdx = likelihoods[i] > likelihoods[classIdx] ? i : classIdx;
}
return classIdx;
}
public static void main(String[] args) {
if (args.length == 4) {
// Features:
double[] features = new double[args.length];
for (int i = 0, l = args.length; i < l; i++) {
features[i] = Double.parseDouble(args[i]);
}
// Parameters:
double[] priors = {0.3333333333333333, 0.3333333333333333, 0.3333333333333333};
double[][] sigmas = {{0.12176400309550259, 0.14081600309550263, 0.029556003095502676, 0.010884003095502673}, {0.2611040030955028, 0.09650000309550268, 0.21640000309550278, 0.03832400309550265}, {0.39625600309550263, 0.10192400309550273, 0.2984960030955029, 0.07392400309550265}};
double[][] thetas = {{5.005999999999999, 3.428000000000001, 1.4620000000000002, 0.2459999999999999}, {5.936, 2.7700000000000005, 4.26, 1.3259999999999998}, {6.587999999999998, 2.9739999999999998, 5.552, 2.026}};
// Prediction:
GaussianNB clf = new GaussianNB(priors, sigmas, thetas);
int estimation = clf.predict(features);
System.out.println(estimation);
}
}
}