Skip to content

Instantly share code, notes, and snippets.

@Alrecenk
Last active December 22, 2015 13:59
Show Gist options
  • Save Alrecenk/6482644 to your computer and use it in GitHub Desktop.
Save Alrecenk/6482644 to your computer and use it in GitHub Desktop.
Naive Bayes Classifier Construction
//constructs a naive Bayes binary classifier
public NaiveBayes(double in[][], boolean out[]){
int inputs = in[0].length ;
//initialize sums and sums of squares for each class
double[] poss = new double[inputs], poss2 = new double[inputs];
double[] negs = new double[inputs], negs2 = new double[inputs];
//calculate amount of each class, sums, and sums of squares
for(int k=0;k<in.length;k++){//for each data point
if(out[k]){
positives++;//keep track of total positives
for(int j=0;j<inputs;j++){//for each input
poss[j] += in[k][j] ;
poss2[j] += in[k][j]*in[k][j] ;
}
}else{
negatives++;//keep track of total negatives
for(int j=0;j<inputs;j++){//for each input
negs[j] += in[k][j] ;
negs2[j] += in[k][j]*in[k][j] ;
}
}
}
//initialize means and variances
posmean = new double[inputs] ;
posvariance = new double[inputs] ;
negmean = new double[inputs] ;
negvariance = new double[inputs] ;
//calculate means and variances
for(int j=0;j<inputs;j++){//for each input
posmean[j] = poss[j]/positives;
negmean[j] = negs[j]/negatives;
posvariance[j] = (poss2[j] - ((poss[j]*poss[j])/positives))/(positives - 1) ;
negvariance[j] = (negs2[j] - ((negs[j]*negs[j])/negatives))/(negatives - 1) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment