Skip to content

Instantly share code, notes, and snippets.

@maxmaxmir
Created February 19, 2016 20:50
Show Gist options
  • Save maxmaxmir/96d3c3669c29dc23e20f to your computer and use it in GitHub Desktop.
Save maxmaxmir/96d3c3669c29dc23e20f to your computer and use it in GitHub Desktop.
Modified AbaloneTest.java (uses ABAGAIL)
import opt.*;
import opt.example.*;
import opt.ga.*;
import shared.*;
import func.nn.backprop.*;
//Java imports
import java.util.*;
import java.io.*;
import java.text.*;
import java.lang.Runnable;
import java.lang.Thread;
class Analyze implements Runnable {
private Thread t;
private String threadName;
private String data_file;
private Instance[] instances;
private DataSet set;
private String comments;
private int trainingIterations;
//ANN specifications
private int inputLayer;
private int outputLayer;
private int hiddenLayer;
private ErrorMeasure measure = new SumOfSquaresError();
private DecimalFormat df = new DecimalFormat("0.000");
public static double[] convert_to_double_arr(String[] str_array) {
double[] double_arr = new double[str_array.length];
for (int i=0; i < str_array.length; i++) {
double_arr[i] = Double.parseDouble(str_array[i]);
}
return double_arr;
}
private static Instance[] initializeInstances(String data_file) {
Instance[] instances = null;
try {
ArrayList<String []> instance_list = new ArrayList();
String line;
BufferedReader br = new BufferedReader(new FileReader(new File(data_file)));
while ((line = br.readLine()) != null) {
instance_list.add(line.split(","));
}
instances = new Instance[instance_list.size()];
for(int i = 0; i < instances.length; i++) {
double[] attributes = convert_to_double_arr(instance_list.get(i));
instances[i] = new Instance(attributes); // Create an instance with all the attributes
instances[i].setLabel(new Instance(attributes[attributes.length - 1])); // Set the label for each instance
}
}
catch (Exception e) {
e.printStackTrace();
}
return instances;
}
Analyze(String optimization_algorithm, String data_folder_path, String data_file, String comments, int trainingIterations) {
threadName = optimization_algorithm;
this.data_file = data_file;
this.comments = comments;
this.trainingIterations = trainingIterations;
//Prepare instances and dataset
instances = initializeInstances(data_folder_path + data_file);
set = new DataSet(instances);
//ANN specifications
inputLayer = instances[0].size();
outputLayer = 1;
hiddenLayer = (int)(inputLayer + outputLayer)/2;
}
public void run() {
OptimizationAlgorithm oa = null;
BackPropagationNetwork network = new BackPropagationNetworkFactory().createClassificationNetwork(new int[] {inputLayer, hiddenLayer, outputLayer});
NeuralNetworkOptimizationProblem nnop = new NeuralNetworkOptimizationProblem(set, network, measure);
try {
switch (threadName) {
case "RHC":
oa = new RandomizedHillClimbing(nnop);
break;
case "SA":
oa = new SimulatedAnnealing(1E11, .95, nnop);
break;
case "GA":
oa = new StandardGeneticAlgorithm(200, 100, 10, nnop);
break;
}
double start = System.nanoTime(), end, trainingTime, testingTime, correct = 0, incorrect = 0;
for(int k = 0; k < trainingIterations; k++) {
double error = 1/oa.train();
System.out.println(this.threadName + ": " + df.format(error));
}
end = System.nanoTime();
trainingTime = (end - start)/Math.pow(10,9);
BackPropagationNetwork new_network = new BackPropagationNetworkFactory().createClassificationNetwork(new int[] {inputLayer, hiddenLayer, outputLayer});
Instance optimalInstance = oa.getOptimal();
new_network.setWeights(optimalInstance.getData());
double predicted, actual;
start = System.nanoTime();
for(int j = 0; j < instances.length; j++) {
new_network.setInputValues(instances[j].getData());
new_network.run();
predicted = Double.parseDouble(instances[j].getLabel().toString());
actual = Double.parseDouble(new_network.getOutputValues().toString());
double trash = Math.abs(predicted - actual) < 0.5 ? correct++ : incorrect++;
}
end = System.nanoTime();
testingTime = (end - start)/Math.pow(10,9);
String results = "\nResults for " + threadName + "_" + data_file + "_" + comments + ": \nCorrectly classified " + correct + " instances." +
"\nIncorrectly classified " + incorrect + " instances.\nPercent correctly classified: "
+ df.format(correct/(correct+incorrect)*100) + "%\nTraining time: " + df.format(trainingTime)
+ " seconds\nTesting time: " + df.format(testingTime) + " seconds\n";
System.out.println(results);
} catch (Exception e) {
e.printStackTrace();
}
}
public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class NNTrain{
public static void main(String[] args) {
String[] algorithms = {"RHC", "SA", "GA"};
String data_folder_path = "data/";
String data_files[] = {"abalone.txt","abalone_normalized.csv"};
int num_runs = 1;
int training_iterations = 10;
for (int i = 0; i < algorithms.length; i++) {
for (int j = 0; j < data_files.length; j++) {
for (int k = 0; k < num_runs; k++) {
new Analyze(algorithms[i], data_folder_path, data_files[j], "run_" + (k+1), training_iterations).start();
}
}
}
}
}
@marita3
Copy link

marita3 commented Feb 19, 2016

How to get access for submitting updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment