id stringlengths 36 36 | text stringlengths 1 1.25M |
|---|---|
4e6c9c98-a71e-463c-900f-0c9a3f84975a | public void printStatus() {
System.out.println(new Date() + " my status (" + this.getMe().getFullAddress() +") {");
System.out.println(new Date() + " \t first: " + this.getFirst().getFullAddress());
System.out.println(new Date() + " \t second: " + this.getSecond().getFullAddress());
System.out.println(new Date() + " \t third: " + this.getThird().getFullAddress());
System.out.println(new Date() + " \t pulse: " + this.getPulse().getFullAddress());
System.out.println(new Date() + " }");
} |
c1d29fde-2cf0-495f-a656-c93c97982d77 | private Normal() {} |
4a8890a3-6af3-48e9-8d65-dbc31a2796eb | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
17cae252-e9e7-4021-8b02-3995ad208c11 | private RenameMeThenEdit() {} |
f6865828-0499-456a-b255-ac0a7a4efbbd | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
6bbd8cef-d7dc-4ed8-9f27-63fdfef18b24 | private MoveMeThenEditMe() {} |
49ccc46a-e3e3-44cf-9225-60d6bf8d1aea | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
f4961cda-2b95-4d75-ae32-5738edac8f93 | private RenameTheDirThenEditMe() {} |
de70232e-18e3-49d7-859c-263e3ce0b83c | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
b95b1d9a-412e-4925-a3ad-2b72f93a9f71 | private SomeClass() {} |
b414a750-bf65-4a0c-9ca1-568b3b0f3fa3 | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
334a7f10-53cc-4630-ba5a-30e881a6a120 | private MoveDirThenEditMe() {} |
9c28e432-d273-4923-982c-735132ad29f2 | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
717f72c0-723e-406d-94bd-4732912eeef2 | private DeleteThisDirThenEditMe() {} |
39f7dca0-c45b-4941-b079-becd446999f0 | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
f06825ea-d3ad-4ef3-a693-751a98cd4938 | private DeleteMeThenEdit() {} |
d44294cc-c8df-4d4d-97c7-6545476fb9ba | public static void main(String[] args)
{
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
// some stuff happens here
} |
bcf4c37c-91c9-4b63-9d51-b1a07449aa9f | public abstract void train(Matrix features, Matrix labels) throws Exception; |
60561ed4-b920-47da-bb1c-925fcb8b03ac | public abstract void predict(double[] features, double[] labels) throws Exception; |
4e33cbc9-12c6-4f03-b87c-ba52c2af2d7d | public double measureAccuracy(Matrix features, Matrix labels, Matrix confusion) throws Exception
{
if(features.rows() != labels.rows())
throw(new Exception("Expected the features and labels to have the same number of rows"));
if(labels.cols() != 1)
throw(new Exception("Sorry, this method currently only supports one-dimensional labels"));
if(features.rows() == 0)
throw(new Exception("Expected at least one row"));
int labelValues = labels.valueCount(0);
if(labelValues == 0) // If the label is continuous...
{
// The label is continuous, so measure root mean squared error
double[] pred = new double[1];
double sse = 0.0;
for(int i = 0; i < features.rows(); i++)
{
double[] feat = features.row(i);
double[] targ = labels.row(i);
pred[0] = 0.0; // make sure the prediction is not biassed by a previous prediction
predict(feat, pred);
double delta = targ[0] - pred[0];
sse += (delta * delta);
}
return Math.sqrt(sse / features.rows());
}
else
{
// The label is nominal, so measure predictive accuracy
if(confusion != null)
{
confusion.setSize(labelValues, labelValues);
for(int i = 0; i < labelValues; i++)
confusion.setAttrName(i, labels.attrValue(0, i));
}
int correctCount = 0;
double[] prediction = new double[1];
for(int i = 0; i < features.rows(); i++)
{
double[] feat = features.row(i);
int targ = (int)labels.get(i, 0);
if(targ >= labelValues)
throw new Exception("The label is out of range");
predict(feat, prediction);
int pred = (int)prediction[0];
if(confusion != null)
confusion.set(targ, pred, confusion.get(targ, pred) + 1);
if(pred == targ)
correctCount++;
}
return (double)correctCount / features.rows();
}
} |
33af2802-8de4-483c-bbf8-9ac852510ce7 | public PerceptronException(){
return;
} |
af71be22-3544-4712-beaf-136ef577f242 | public PerceptronException(String message){
super(message);
} |
b42f9460-c726-467a-8171-0e64c13cfa6c | public PerceptronException(Throwable throwable){
super(throwable);
} |
7e0b682e-bf92-4f5d-ae1e-0897d4bcee40 | public PerceptronException(String message, Throwable throwable){
super(message, throwable);
} |
cfcb4a12-5045-4f32-b0c0-17fba261f3fc | public PerceptronNode(){
weights = new double[4];
initializeWeights();
} |
a57766c1-44f8-47ce-bf03-d97ecd1a42de | public PerceptronNode(int numInputs){
weights = new double[numInputs+1];
initializeWeights();
} |
c17df11a-fe5c-4df5-8544-f6be04175a10 | public double getOutput(double[] inputs) throws PerceptronException{
if(inputs.length != (weights.length-1))
throw new PerceptronException("The weights of the inputs were the wrong size!");
double combinedTotal = 0;
//add all of the inputs to the combined total
for(int i = 0; i < inputs.length; i++){
combinedTotal += weights[i] * inputs[i];
}
//add the bias to the combined total
combinedTotal += weights[weights.length - 1] * bias;
double afterSigmoid = 1.0 / (1.0 + Math.exp(combinedTotal));
return afterSigmoid;
} |
202fd095-35f0-455c-84a0-9b3ed044bd1e | public double[] getWeights(){
return weights;
} |
227d6885-0288-40fb-a331-ab07bf3dc711 | public double getWeight(int idx){
return weights[idx];
} |
0357a413-e54a-4627-a851-695b570649a4 | public double getBias(){
return bias;
} |
4e16feb4-49ad-4e6e-ab9b-d9fbe1ee298f | public void setWeights(double[] weights) throws PerceptronException{
this.weights = weights;
} |
90be4807-93cc-475d-9a29-2eacbbb62270 | public void setWeight(int idx, double weight) throws PerceptronException{
if(idx > weights.length-2){
throw new PerceptronException("The index specified is not a settable weight in this neuron.");
}
} |
d5d957e2-da3a-4f71-9559-8c2f88ffa8f8 | public void setNumInputs(int numInputs){
weights = new double[numInputs+1];
initializeWeights();
} |
c45c2510-78f6-4969-9638-2254342b45bf | public double getHNError(double activation, Double[] nextLayerErrors, Double[] nextLayerWeights){
double accSum = 0;
//SUM
for(int i = 0; i < nextLayerWeights.length; i++){
accSum += nextLayerWeights[i] * nextLayerErrors[i]; //Wkh * Deltak
}
//Deltah <= Oh(1-Oh) * sum above
double ret = activation * (1 - activation) * accSum;
return ret;
} |
a49938d3-5f90-406d-99ce-fd7180ddf8dc | private void initializeWeights(){
int wLen = weights.length;
for(int i = 0; i < wLen; i++){
double initTemp = (Math.random() - .5) * 2.0;
weights[i] = initTemp;
}
} |
39093696-cc71-4e3e-9dbe-08c5b0711797 | public MLPerceptronLearner(){
numHiddenLayers = -1;
numHiddenNodes = -1;
online = true;
inclMomentum = true;
} |
69159aca-2e39-454f-9a4e-a79bfcdd92e8 | public MLPerceptronLearner(int numHiddenLayers, boolean online){
this.numHiddenLayers = numHiddenLayers;
this.online = online;
} |
9ae27b83-bae7-4d47-81e8-63d73be507df | public void setOnline(boolean online){
this.online = online;
} |
2c667d86-3824-4f6b-8229-2f68cc4ecb58 | public void setInclMomentum(boolean inclMomentum){
this.inclMomentum = inclMomentum;
} |
1c2ebf2b-e550-4b10-8d11-10b60eb16099 | public void setNumHiddenLayers(int numHiddenLayers){
this.numHiddenLayers = numHiddenLayers;
} |
93441154-3815-4eff-91e6-ebc95b5f2350 | public void setNumHiddenNodes(int numHiddenNodes){
this.numHiddenNodes = numHiddenNodes;
} |
c6e43a73-44e2-4a9f-b1e6-2c7ee801f484 | private void initializeNodes(int numInputs, int numOutputClasses){
//check to see if the hiddenlayers and hiddennodes have been initialized, and if not,
//initialize them to default values
nodesList = new ArrayList<List<PerceptronNode>>();
if(numHiddenLayers == -1){
numHiddenLayers = 2;
}
if(numHiddenNodes == -1){
numHiddenNodes = numOutputClasses;
}
//add numHiddenLayers + 1 layers, including one for the output nodes
for(int i = 0; i < numHiddenLayers + 1; i++){
nodesList.add(new ArrayList<PerceptronNode>());
if(i == 0){
for(int j = 0; j < numHiddenNodes + 1; j++){
nodesList.get(i).add(new PerceptronNode(numInputs));
}
}
else if(i < numHiddenLayers){
for(int j = 0; j < numHiddenNodes + 1; j++){
nodesList.get(i).add(new PerceptronNode(numHiddenNodes));
}
}
else{
for(int j = 0; j < numOutputClasses; j++){
nodesList.get(i).add(new PerceptronNode(numHiddenNodes));
}
}
}
} |
b6f3b783-6123-418c-b15a-fd8860a5b7b5 | @Override
public void train(Matrix features, Matrix labels) throws Exception {
int featuresNumCols = features.cols();
int numPossibleOutputs = labels.valueCount(0);
//initialize the nodes!
initializeNodes(featuresNumCols, numPossibleOutputs);
} |
a00929fe-9bb3-4f2f-bf3e-d7d3dc6077ed | @Override
public void predict(double[] features, double[] labels) throws Exception {
} |
39294b8e-2990-4bb6-b208-ef73f6cbd27d | private void performWeightUpdate(List<List<Double>> errors){
} |
06fab976-fa60-466a-a8d2-3de99256e028 | private void performStochasticTraining(Matrix features, Matrix labels)
throws PerceptronException{
int numRows = labels.rows();
int featuresNumCols = features.cols();
int numPossibleOutputs = labels.valueCount(0);
//make an arraylist to accumulate errors in
List<List<Double>> errors = new ArrayList<List<Double>>();
for(int i = 0; i < numHiddenLayers + 1; i++){
List<Double> temp = new ArrayList<Double>();
errors.add(temp);
if(i < numHiddenLayers){
//initialize all of the errors to "0.0"
for(int j = 0; j < numHiddenNodes; j++){
temp.add(0.0);
}
}
else{
for(int j = 0; j < numPossibleOutputs; j++){
temp.add(0.0);
}
}
}
//iterate through all of the rows
for(int i = 0; i < numRows; i++){
//get the row that we're on now
double[] featureRow = features.row(i);
double[] labelRow = labels.row(i);
//get the predicted outcome for each node
List<List<Double>> activationsRes = getPredOutcome(featureRow);
for(int j = numHiddenLayers; j >= 0; j--){
if(j == numHiddenLayers){
for(int k = 0; k < numPossibleOutputs; k++){
//calculate the correct outcome
double correctOutcome = 0.0;
if(j == (int)labelRow[0]){
correctOutcome = 1.0;
}
double activation = activationsRes.get(i).get(j);
//DELTAk <= Ok(1-Ok)(Tk - Ok)
double tempErr = activation * (1 - activation) * (correctOutcome - activation);
errors.get(j).set(k, tempErr + errors.get(j).get(k));
}
}
else{
for(int k = 0; k < numHiddenNodes; k++){
PerceptronNode workNode = nodesList.get(j).get(k);
Double[] nextLayerErr = (Double[]) errors.get(j+1).toArray();
double thisNodesActivation = activationsRes.get(j).get(k);
//compile the errors from the next layer into an array
Double[] nextLayerWeights = new Double[nodesList.get(j+1).size()];
for(int l = 0; l < nodesList.get(j+1).size(); l++){
nextLayerWeights[l] = nodesList.get(j+1).get(l).getWeight(k);
}
//set the errors based on the
errors.get(j).set(k, errors.get(j).get(k) +
workNode.getHNError(thisNodesActivation, nextLayerErr, nextLayerWeights));
}
}
}
}
//perform the weight only AFTER all of the errors have been adjusted for each entry in the
//dataset
this.performWeightUpdate(errors);
} |
571694e7-ae87-4bf5-bdd8-839869ce9aa2 | private void performOnlineTraining(Matrix features, Matrix labels) throws PerceptronException{
int numRows = labels.rows();
int featuresNumCols = features.cols();
int numPossibleOutputs = labels.valueCount(0);
//iterate through all of the rows
for(int i = 0; i < numRows; i++){
//get the row that we're on now
double[] featureRow = features.row(i);
double[] labelRow = labels.row(i);
//make an arraylist to accumulate errors in
List<List<Double>> errors = new ArrayList<List<Double>>();
for(int tct = 0; tct < numHiddenLayers + 1; tct++){
List<Double> temp = new ArrayList<Double>();
errors.add(temp);
if(tct < numHiddenLayers){
//initialize all of the errors to "0.0"
for(int j = 0; j < numHiddenNodes; j++){
temp.add(0.0);
}
}
else{
for(int j = 0; j < numPossibleOutputs; j++){
temp.add(0.0);
}
}
}
//get the predicted outcome for each node
List<List<Double>> activationsRes = getPredOutcome(featureRow);
for(int j = numHiddenLayers; j >= 0; j--){
if(j == numHiddenLayers){
for(int k = 0; k < numPossibleOutputs; k++){
//calculate the correct outcome
double correctOutcome = 0.0;
if(j == (int)labelRow[0]){
correctOutcome = 1.0;
}
double activation = activationsRes.get(i).get(j);
//DELTAk <= Ok(1-Ok)(Tk - Ok)
double tempErr = activation * (1 - activation) * (correctOutcome - activation);
errors.get(j).set(k, tempErr + errors.get(j).get(k));
}
}
else{
for(int k = 0; k < numHiddenNodes; k++){
PerceptronNode workNode = nodesList.get(j).get(k);
Double[] nextLayerErr = (Double[]) errors.get(j+1).toArray();
double thisNodesActivation = activationsRes.get(j).get(k);
//compile the errors from the next layer into an array
Double[] nextLayerWeights = new Double[nodesList.get(j+1).size()];
for(int l = 0; l < nodesList.get(j+1).size(); l++){
nextLayerWeights[l] = nodesList.get(j+1).get(l).getWeight(k);
}
//set the errors based on the last iteration's errors
errors.get(j).set(k, errors.get(j).get(k) +
workNode.getHNError(thisNodesActivation, nextLayerErr, nextLayerWeights));
}
}
}
//perform the weight update after each error has been calculated, after each iteration
this.performWeightUpdate(errors);
}
} |
18c53d0c-e9f9-40d0-8566-9e643b9498fe | private List<List<Double>> getPredOutcome(double[] features) throws PerceptronException{
int numPossibleOutputs = nodesList.get((nodesList.size()-1)).size();
List<List<Double>> activations = new ArrayList<List<Double>>();
//initialize the arraylist of the lists of activations
for(int i = 0; i < numHiddenLayers + 1; i++){
activations.add(new ArrayList<Double>());
}
for(int i = 0; i < nodesList.size(); i++){
if(i == 0){
for(int j = 0; j < numHiddenNodes; j++){
PerceptronNode workingNode = nodesList.get(i).get(j);
activations.get(i).add(workingNode.getOutput(features));
}
}
else if(i < numHiddenLayers){
for(int j = 0; j < numHiddenNodes; j++){
PerceptronNode workingNode = nodesList.get(i).get(j);
List<Double> tempActList = activations.get(i-1);
double[] tempActArray = new double[tempActList.size()];
for(int k = 0; k < tempActList.size(); k++){
tempActArray[k] = tempActList.get(i);
}
activations.get(i).add(workingNode.getOutput(tempActArray));
}
}
else{
for(int j = 0; j < numPossibleOutputs; j++){
PerceptronNode workingNode = nodesList.get(i).get(j);
List<Double> tempActList = activations.get(i-1);
double[] tempActArray = new double[tempActList.size()];
for(int k = 0; k < tempActList.size(); k++){
tempActArray[k] = tempActList.get(i);
}
activations.get(i).add(workingNode.getOutput(tempActArray));
}
}
}
return activations;
} |
71a8742a-1f01-4ec5-9809-329a889150a5 | public void train(Matrix features, Matrix labels) throws Exception {
m_labels = new double[labels.cols()];
for(int i = 0; i < labels.cols(); i++) {
if(labels.valueCount(i) == 0)
m_labels[i] = labels.columnMean(i); // continuous
else
m_labels[i] = labels.mostCommonValue(i); // nominal
}
} |
2af2b06d-0c3a-47fe-b6b4-ab9eff8b27ab | public void predict(double[] features, double[] labels) throws Exception {
for(int i = 0; i < m_labels.length; i++)
labels[i] = m_labels[i];
} |
064a737c-eac4-410f-b40a-2dfb14c0f19c | public SupervisedLearner getLearner(String model, Random rand) throws Exception
{
if (model.equals("baseline")) return new BaselineLearner();
// else if (model.equals("perceptron")) return new Perceptron(rand);
// else if (model.equals("neuralnet")) return new NeuralNet(rand);
// else if (model.equals("decisiontree")) return new DecisionTree();
// else if (model.equals("knn")) return new InstanceBasedLearner();
else throw new Exception("Unrecognized model: " + model);
} |
6d71b576-fe3f-47fe-b5ff-f20be8ff3d16 | public void run(String[] args) throws Exception {
//args = new String[]{"-L", "baseline", "-A", "data/iris.arff", "-E", "cross", "10", "-N"};
//Random rand = new Random(1234); // Use a seed for deterministic results (makes debugging easier)
Random rand = new Random(); // No seed for non-deterministic results
//Parse the command line arguments
ArgParser parser = new ArgParser(args);
String fileName = parser.getARFF(); //File specified by the user
String learnerName = parser.getLearner(); //Learning algorithm specified by the user
String evalMethod = parser.getEvaluation(); //Evaluation method specified by the user
String evalParameter = parser.getEvalParameter(); //Evaluation parameters specified by the user
boolean printConfusionMatrix = parser.getVerbose();
boolean normalize = parser.getNormalize();
// Load the model
SupervisedLearner learner = getLearner(learnerName, rand);
// Load the ARFF file
Matrix data = new Matrix();
data.loadArff(fileName);
if (normalize)
{
System.out.println("Using normalized data\n");
data.normalize();
}
// Print some stats
System.out.println();
System.out.println("Dataset name: " + fileName);
System.out.println("Number of instances: " + data.rows());
System.out.println("Number of attributes: " + data.cols());
System.out.println("Learning algorithm: " + learnerName);
System.out.println("Evaluation method: " + evalMethod);
System.out.println();
if (evalMethod.equals("training"))
{
System.out.println("Calculating accuracy on training set...");
Matrix features = new Matrix(data, 0, 0, data.rows(), data.cols() - 1);
Matrix labels = new Matrix(data, 0, data.cols() - 1, data.rows(), 1);
Matrix confusion = new Matrix();
double startTime = System.currentTimeMillis();
learner.train(features, labels);
double elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0);
double accuracy = learner.measureAccuracy(features, labels, confusion);
System.out.println("Training set accuracy: " + accuracy);
if(printConfusionMatrix) {
System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)");
confusion.print();
System.out.println("\n");
}
}
else if (evalMethod.equals("static"))
{
Matrix testData = new Matrix();
testData.loadArff(evalParameter);
if (normalize)
testData.normalize(); // BUG! This may normalize differently from the training data. It should use the same ranges for normalization!
System.out.println("Calculating accuracy on separate test set...");
System.out.println("Test set name: " + evalParameter);
System.out.println("Number of test instances: " + testData.rows());
Matrix features = new Matrix(data, 0, 0, data.rows(), data.cols() - 1);
Matrix labels = new Matrix(data, 0, data.cols() - 1, data.rows(), 1);
double startTime = System.currentTimeMillis();
learner.train(features, labels);
double elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0);
double trainAccuracy = learner.measureAccuracy(features, labels, null);
System.out.println("Training set accuracy: " + trainAccuracy);
Matrix testFeatures = new Matrix(testData, 0, 0, testData.rows(), testData.cols() - 1);
Matrix testLabels = new Matrix(testData, 0, testData.cols() - 1, testData.rows(), 1);
Matrix confusion = new Matrix();
double testAccuracy = learner.measureAccuracy(testFeatures, testLabels, confusion);
System.out.println("Test set accuracy: " + testAccuracy);
if(printConfusionMatrix) {
System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)");
confusion.print();
System.out.println("\n");
}
}
else if (evalMethod.equals("random"))
{
System.out.println("Calculating accuracy on a random hold-out set...");
double trainPercent = Double.parseDouble(evalParameter);
if (trainPercent < 0 || trainPercent > 1)
throw new Exception("Percentage for random evaluation must be between 0 and 1");
System.out.println("Percentage used for training: " + trainPercent);
System.out.println("Percentage used for testing: " + (1 - trainPercent));
data.shuffle(rand);
int trainSize = (int)(trainPercent * data.rows());
Matrix trainFeatures = new Matrix(data, 0, 0, trainSize, data.cols() - 1);
Matrix trainLabels = new Matrix(data, 0, data.cols() - 1, trainSize, 1);
Matrix testFeatures = new Matrix(data, trainSize, 0, data.rows() - trainSize, data.cols() - 1);
Matrix testLabels = new Matrix(data, trainSize, data.cols() - 1, data.rows() - trainSize, 1);
double startTime = System.currentTimeMillis();
learner.train(trainFeatures, trainLabels);
double elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0);
double trainAccuracy = learner.measureAccuracy(trainFeatures, trainLabels, null);
System.out.println("Training set accuracy: " + trainAccuracy);
Matrix confusion = new Matrix();
double testAccuracy = learner.measureAccuracy(testFeatures, testLabels, confusion);
System.out.println("Test set accuracy: " + testAccuracy);
if(printConfusionMatrix) {
System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)");
confusion.print();
System.out.println("\n");
}
}
else if (evalMethod.equals("cross"))
{
System.out.println("Calculating accuracy using cross-validation...");
int folds = Integer.parseInt(evalParameter);
if (folds <= 0)
throw new Exception("Number of folds must be greater than 0");
System.out.println("Number of folds: " + folds);
int reps = 1;
double sumAccuracy = 0.0;
double elapsedTime = 0.0;
for(int j = 0; j < reps; j++) {
data.shuffle(rand);
for (int i = 0; i < folds; i++) {
int begin = i * data.rows() / folds;
int end = (i + 1) * data.rows() / folds;
Matrix trainFeatures = new Matrix(data, 0, 0, begin, data.cols() - 1);
Matrix trainLabels = new Matrix(data, 0, data.cols() - 1, begin, 1);
Matrix testFeatures = new Matrix(data, begin, 0, end - begin, data.cols() - 1);
Matrix testLabels = new Matrix(data, begin, data.cols() - 1, end - begin, 1);
trainFeatures.add(data, end, 0, data.rows() - end);
trainLabels.add(data, end, data.cols() - 1, data.rows() - end);
double startTime = System.currentTimeMillis();
learner.train(trainFeatures, trainLabels);
elapsedTime += System.currentTimeMillis() - startTime;
double accuracy = learner.measureAccuracy(testFeatures, testLabels, null);
sumAccuracy += accuracy;
System.out.println("Rep=" + j + ", Fold=" + i + ", Accuracy=" + accuracy);
}
}
elapsedTime /= (reps * folds);
System.out.println("Average time to train (in seconds): " + elapsedTime / 1000.0);
System.out.println("Mean accuracy=" + (sumAccuracy / (reps * folds)));
}
} |
527f39ff-6498-4ac6-833f-1d2e253884c6 | public ArgParser(String[] argv) {
try{
for (int i = 0; i < argv.length; i++) {
if (argv[i].equals("-V"))
{
verbose = true;
}
else if (argv[i].equals("-N"))
{
normalize = true;
}
else if (argv[i].equals("-A"))
{
arff = argv[++i];
}
else if (argv[i].equals("-L"))
{
learner = argv[++i];
}
else if (argv[i].equals("-E"))
{
evaluation = argv[++i];
if (argv[i].equals("static"))
{
//expecting a test set name
evalExtra = argv[++i];
}
else if (argv[i].equals("random"))
{
//expecting a double representing the percentage for testing
//Note stratification is NOT done
evalExtra = argv[++i];
}
else if (argv[i].equals("cross"))
{
//expecting the number of folds
evalExtra = argv[++i];
}
else if (!argv[i].equals("training"))
{
System.out.println("Invalid Evaluation Method: " + argv[i]);
System.exit(0);
}
}
else
{
System.out.println("Invalid parameter: " + argv[i]);
System.exit(0);
}
}
}
catch (Exception e) {
System.out.println("Usage:");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E [evaluationMethod] {[extraParamters]} [OPTIONS]\n");
System.out.println("OPTIONS:");
System.out.println("-V Print the confusion matrix and learner accuracy on individual class values\n");
System.out.println("Possible evaluation methods are:");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E training");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E static [testARFF_File]");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E random [%_ForTraining]");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E cross [numOfFolds]\n");
System.exit(0);
}
if (arff == null || learner == null || evaluation == null)
{
System.out.println("Usage:");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E [evaluationMethod] {[extraParamters]} [OPTIONS]\n");
System.out.println("OPTIONS:");
System.out.println("-V Print the confusion matrix and learner accuracy on individual class values");
System.out.println("-N Use normalized data");
System.out.println();
System.out.println("Possible evaluation methods are:");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E training");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E static [testARFF_File]");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E random [%_ForTraining]");
System.out.println("MLSystemManager -L [learningAlgorithm] -A [ARFF_File] -E cross [numOfFolds]\n");
System.exit(0);
}
} |
5faaf890-48ae-4ace-a842-ee760239b5cb | public String getARFF(){ return arff; } |
021dbde8-100b-459f-b1e7-4983b87c880d | public String getLearner(){ return learner; } |
77b11c86-1dba-44fb-b663-95b5b9abbd42 | public String getEvaluation(){ return evaluation; } |
c347ae51-9c44-4bbe-9b2c-56ded98bcf03 | public String getEvalParameter() { return evalExtra; } |
18728cf0-437a-4b53-bc92-28a0f4df8912 | public boolean getVerbose() { return verbose; } |
9c1d1207-6562-4d4f-913c-bf24ddfb4c90 | public boolean getNormalize() { return normalize; } |
0adf027a-4c50-4448-83b1-411161a3f079 | public static void main(String[] args) throws Exception
{
MLSystemManager ml = new MLSystemManager();
ml.run(args);
} |
072e15da-f8c5-4cf4-8304-e83fd87996f8 | public Matrix() {} |
2b3404a3-e4b4-44c5-bb59-c05b4685a097 | public Matrix(Matrix that, int rowStart, int colStart, int rowCount, int colCount) {
m_data = new ArrayList< double[] >();
for(int j = 0; j < rowCount; j++) {
double[] rowSrc = that.row(rowStart + j);
double[] rowDest = new double[colCount];
for(int i = 0; i < colCount; i++)
rowDest[i] = rowSrc[colStart + i];
m_data.add(rowDest);
}
m_attr_name = new ArrayList<String>();
m_str_to_enum = new ArrayList< TreeMap<String, Integer> >();
m_enum_to_str = new ArrayList< TreeMap<Integer, String> >();
for(int i = 0; i < colCount; i++) {
m_attr_name.add(that.attrName(colStart + i));
m_str_to_enum.add(that.m_str_to_enum.get(colStart + i));
m_enum_to_str.add(that.m_enum_to_str.get(colStart + i));
}
} |
e8cc3c15-74ac-475e-8828-9ed63029c95a | public void add(Matrix that, int rowStart, int colStart, int rowCount) throws Exception {
if(colStart + cols() > that.cols())
throw new Exception("out of range");
for(int i = 0; i < cols(); i++) {
if(that.valueCount(colStart + i) != valueCount(i))
throw new Exception("incompatible relations");
}
for(int j = 0; j < rowCount; j++) {
double[] rowSrc = that.row(rowStart + j);
double[] rowDest = new double[cols()];
for(int i = 0; i < cols(); i++)
rowDest[i] = rowSrc[colStart + i];
m_data.add(rowDest);
}
} |
a5e3a419-ece3-4caa-91c3-65a101eb55c5 | public void setSize(int rows, int cols) {
m_data = new ArrayList< double[] >();
for(int j = 0; j < rows; j++) {
double[] row = new double[cols];
m_data.add(row);
}
m_attr_name = new ArrayList<String>();
m_str_to_enum = new ArrayList< TreeMap<String, Integer> >();
m_enum_to_str = new ArrayList< TreeMap<Integer, String> >();
for(int i = 0; i < cols; i++) {
m_attr_name.add("");
m_str_to_enum.add(new TreeMap<String, Integer>());
m_enum_to_str.add(new TreeMap<Integer, String>());
}
} |
20ce9389-a21d-4119-aac0-e6ec6aa5eaa9 | public void loadArff(String filename) throws Exception, FileNotFoundException {
m_data = new ArrayList<double[]>();
m_attr_name = new ArrayList<String>();
m_str_to_enum = new ArrayList< TreeMap<String, Integer> >();
m_enum_to_str = new ArrayList< TreeMap<Integer, String> >();
boolean READDATA = false;
Scanner s = new Scanner(new File(filename));
while (s.hasNext()) {
String line = s.nextLine().trim();
if (line.length() > 0 && line.charAt(0) != '%') {
if (!READDATA) {
Scanner t = new Scanner(line);
String firstToken = t.next().toUpperCase();
if (firstToken.equals("@RELATION")) {
String datasetName = t.nextLine();
}
if (firstToken.equals("@ATTRIBUTE")) {
TreeMap<String, Integer> ste = new TreeMap<String, Integer>();
m_str_to_enum.add(ste);
TreeMap<Integer, String> ets = new TreeMap<Integer, String>();
m_enum_to_str.add(ets);
Scanner u = new Scanner(line);
if (line.indexOf("'") != -1) u.useDelimiter("'");
u.next();
String attributeName = u.next();
if (line.indexOf("'") != -1) attributeName = "'" + attributeName + "'";
m_attr_name.add(attributeName);
int vals = 0;
String type = u.next().trim().toUpperCase();
if (type.equals("REAL") || type.equals("CONTINUOUS") || type.equals("INTEGER")) {
}
else {
try {
String values = line.substring(line.indexOf("{")+1,line.indexOf("}"));
Scanner v = new Scanner(values);
v.useDelimiter(",");
while (v.hasNext()) {
String value = v.next().trim();
if(value.length() > 0)
{
ste.put(value, new Integer(vals));
ets.put(new Integer(vals), value);
vals++;
}
}
}
catch (Exception e) {
throw new Exception("Error parsing line: " + line + "\n" + e.toString());
}
}
}
if (firstToken.equals("@DATA")) {
READDATA = true;
}
}
else {
double[] newrow = new double[cols()];
int curPos = 0;
try {
Scanner t = new Scanner(line);
t.useDelimiter(",");
while (t.hasNext()) {
String textValue = t.next().trim();
//System.out.println(textValue);
if (textValue.length() > 0) {
double doubleValue;
int vals = m_enum_to_str.get(curPos).size();
//Missing instances appear in the dataset as a double defined as MISSING
if (textValue.equals("?")) {
doubleValue = MISSING;
}
// Continuous values appear in the instance vector as they are
else if (vals == 0) {
doubleValue = Double.parseDouble(textValue);
}
// Discrete values appear as an index to the "name"
// of that value in the "attributeValue" structure
else {
doubleValue = m_str_to_enum.get(curPos).get(textValue);
if (doubleValue == -1) {
throw new Exception("Error parsing the value '" + textValue + "' on line: " + line);
}
}
newrow[curPos] = doubleValue;
curPos++;
}
}
}
catch(Exception e) {
throw new Exception("Error parsing line: " + line + "\n" + e.toString());
}
m_data.add(newrow);
}
}
}
} |
132a0f1b-b0f0-4869-b038-2ea46c945320 | int rows() { return m_data.size(); } |
e222a696-000f-45a3-b931-02d38cbcd452 | int cols() { return m_attr_name.size(); } |
26a9b3dd-f62b-47f9-9406-ffc2e29979ac | double[] row(int r) { return m_data.get(r); } |
66e81f32-41c5-44dd-844b-d19cbde6ef63 | double get(int r, int c) { return m_data.get(r)[c]; } |
0d574df6-4210-4577-b2ac-ce63ff7e63f8 | void set(int r, int c, double v) { row(r)[c] = v; } |
d44d7fc7-dc85-4c2b-a435-1c16231f40f3 | String attrName(int col) { return m_attr_name.get(col); } |
154d70f3-d370-4218-913c-cfcfb8075946 | void setAttrName(int col, String name) { m_attr_name.set(col, name); } |
072dac54-ecc9-4960-a740-e77b935bdc1d | String attrValue(int attr, int val) { return m_enum_to_str.get(attr).get(val); } |
3c840dd5-ee63-4247-ae03-06cbf098ce8e | int valueCount(int col) { return m_enum_to_str.get(col).size(); } |
ff08b53f-4472-415e-b233-927683818fd5 | void shuffle(Random rand) {
for(int n = rows(); n > 0; n--) {
int i = rand.nextInt(n);
double[] tmp = row(n - 1);
m_data.set(n - 1, row(i));
m_data.set(i, tmp);
}
} |
b4c34233-bf09-4cd6-bf63-663210ec9982 | void shuffle(Random rand, Matrix buddy) {
for (int n = rows(); n > 0; n--) {
int i = rand.nextInt(n);
double[] tmp = row(n - 1);
m_data.set(n - 1, row(i));
m_data.set(i, tmp);
double[] tmp1 = buddy.row(n - 1);
buddy.m_data.set(n - 1, buddy.row(i));
buddy.m_data.set(i, tmp1);
}
} |
db8f90dd-40a1-4c1d-8293-79b691edda51 | double columnMean(int col) {
double sum = 0;
int count = 0;
for(int i = 0; i < rows(); i++) {
double v = get(i, col);
if(v != MISSING)
{
sum += v;
count++;
}
}
return sum / count;
} |
fe889faa-7a56-447c-a765-d48003d37eaf | double columnMin(int col) {
double m = MISSING;
for(int i = 0; i < rows(); i++) {
double v = get(i, col);
if(v != MISSING)
{
if(m == MISSING || v < m)
m = v;
}
}
return m;
} |
c8ddcb4c-11a9-4316-973a-f5a6b51d6fcd | double columnMax(int col) {
double m = MISSING;
for(int i = 0; i < rows(); i++) {
double v = get(i, col);
if(v != MISSING)
{
if(m == MISSING || v > m)
m = v;
}
}
return m;
} |
b8564576-3405-4d2a-b165-77e1f4000641 | double mostCommonValue(int col) {
TreeMap<Double, Integer> tm = new TreeMap<Double, Integer>();
for(int i = 0; i < rows(); i++) {
double v = get(i, col);
if(v != MISSING)
{
Integer count = tm.get(v);
if(count == null)
tm.put(v, new Integer(1));
else
tm.put(v, new Integer(count.intValue() + 1));
}
}
int maxCount = 0;
double val = MISSING;
Iterator< Entry<Double, Integer> > it = tm.entrySet().iterator();
while(it.hasNext())
{
Entry<Double, Integer> e = it.next();
if(e.getValue() > maxCount)
{
maxCount = e.getValue();
val = e.getKey();
}
}
return val;
} |
50effd75-0e6b-4004-b4b9-78a3a1afd616 | void normalize() {
for(int i = 0; i < cols(); i++) {
if(valueCount(i) == 0) {
double min = columnMin(i);
double max = columnMax(i);
for(int j = 0; j < rows(); j++) {
double v = get(j, i);
if(v != MISSING)
set(j, i, (v - min) / (max - min));
}
}
}
} |
62af5b36-a054-4fc6-9970-e85fda472f9a | void print() {
System.out.println("@RELATION Untitled");
for(int i = 0; i < m_attr_name.size(); i++) {
System.out.print("@ATTRIBUTE " + m_attr_name.get(i));
int vals = valueCount(i);
if(vals == 0)
System.out.println(" CONTINUOUS");
else
{
System.out.print(" {");
for(int j = 0; j < vals; j++) {
if(j > 0)
System.out.print(", ");
System.out.print(m_enum_to_str.get(i).get(j));
}
System.out.println("}");
}
}
System.out.println("@DATA");
for(int i = 0; i < rows(); i++) {
double[] r = row(i);
for(int j = 0; j < r.length; j++) {
if(j > 0)
System.out.print(", ");
if(valueCount(j) == 0)
System.out.print(r[j]);
else
System.out.print(m_enum_to_str.get(j).get((int)r[j]));
}
System.out.println("");
}
} |
c970264d-250b-45c4-8846-36d2b7f016da | @Before
public void setUp() throws Exception {
hm = new EvilHangMan(6, 8);
} |
d24dbd25-c0f7-4ed0-9465-0e9065760d49 | @Test
public void testInitialValues() {
// call the constructor and see that the initial values are correct
assertEquals("", hm.getSecretWord()); // unknown at first
assertEquals(8, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ ", hm.displayGameState());
assertEquals("", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
69c5925f-5da4-4dc8-831b-9d040eb47d57 | @Test
public void testGuess() {
// pretty much every guess is going to be wrong!
boolean correct = hm.makeGuess('S');
assertFalse(correct);
assertEquals(7, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ ", hm.displayGameState());
assertEquals("S", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
5ea59dab-4ec8-4df9-9bf1-f141979f64d3 | @Test
public void testTwoGuesses() {
boolean correct = hm.makeGuess('S');
assertFalse(correct);
correct = hm.makeGuess('P');
assertFalse(correct);
assertEquals(6, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ ", hm.displayGameState());
assertEquals("SP", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
05327ec0-93c3-4de5-9596-d5f577b76c86 | @Test
public void testIllegalCharGuess() {
boolean correct = hm.makeGuess('?');
assertFalse(correct);
assertEquals(8, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ ", hm.displayGameState());
assertEquals("", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
8c4c0939-2cd0-4700-bf4b-261413bbe0d9 | @Test
public void testMultipleCharGuess() {
boolean correct = hm.makeGuess('A');
assertFalse(correct);
correct = hm.makeGuess('A');
assertFalse(correct);
assertEquals(7, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ ", hm.displayGameState());
assertEquals("A", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
5c444629-bdd6-4f8e-8871-545fc19ef80b | @Test
public void testSecretWord() {
// after one guess, the secret word changes
hm.makeGuess('A');
assertEquals("BEBOPS", hm.getSecretWord()); // don't ask how I know that
// after another guess, it changes again!
hm.makeGuess('B');
assertEquals("CEDERS", hm.getSecretWord()); // don't ask how I know that
} |
50020217-442e-4426-b83d-cf0b13182f64 | @Test
public void testWin() {
// correctly guess the word and see if the game ends
hm = new EvilHangMan(4, 16);
hm.makeGuess('A');
hm.makeGuess('E');
hm.makeGuess('I');
hm.makeGuess('O');
hm.makeGuess('U');
hm.makeGuess('R');
hm.makeGuess('S');
hm.makeGuess('T');
hm.makeGuess('L');
hm.makeGuess('N');
// at this point, the correct word is WYCH
boolean correct = hm.makeGuess('W');
assertTrue(correct);
correct = hm.makeGuess('Y');
assertTrue(correct);
correct = hm.makeGuess('C');
assertTrue(correct);
correct = hm.makeGuess('H');
assertTrue(correct);
// the authors of EvilHangMan assume you'll never win!
// that's because the game switches from "evil" to "normal"
// once you guess a letter correctly.
// so, there's no need to test these, I guess
//assertTrue(hm.gameOver());
//assertTrue(hm.isWin());
} |
9c6747f0-2b4f-434d-afd7-da8409a9116a | @Test
public void testLoss() {
// use up all guesses and see if game ends
hm.makeGuess('A');
hm.makeGuess('C');
hm.makeGuess('D');
hm.makeGuess('F');
hm.makeGuess('H');
hm.makeGuess('I');
hm.makeGuess('J');
hm.makeGuess('K');
assertTrue(hm.gameOver());
assertFalse(hm.isWin());
} |
76b85e65-7882-4519-9e7c-2c6b16e1cdcc | @Before
public void setUp() throws Exception {
hm = new NormalHangMan(WORD, 8,"");
} |
5c4b6a1a-dc74-46c8-af96-aa6387c5f8b7 | @Test
public void testInitialValues() {
// call the constructor and see that the initial values are correct
assertEquals(WORD, hm.getSecretWord());
assertEquals(8, hm.numGuessesRemaining());
assertEquals(7, hm.numLettersRemaining()); // because the word has 7 distinct letters
assertEquals("_ _ _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
1923ca65-3f71-40e8-9613-a45321e5f121 | @Test
public void testCorrectGuess1() {
// make a correct guess and see if everything is updated
boolean correct = hm.makeGuess('S');
assertTrue(correct);
assertEquals(8, hm.numGuessesRemaining());
assertEquals(6, hm.numLettersRemaining());
assertEquals("S _ _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("S", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
c875358d-8944-4015-8e15-043a715f7dfe | @Test
public void testCorrectGuess2() {
// make a correct guess and see if everything is updated
boolean correct = hm.makeGuess('O');
assertTrue(correct);
assertEquals(8, hm.numGuessesRemaining());
assertEquals(6, hm.numLettersRemaining());
assertEquals("_ _ O _ _ _ _ O _ ", hm.displayGameState());
assertEquals("O", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
3972c6bb-477c-4c29-80d7-9ea35e263fe4 | @Test
public void testTwoCorrectGuesses() {
// make two correct guesses and see if everything is updated
boolean correct = hm.makeGuess('S');
assertTrue(correct);
correct = hm.makeGuess('P');
assertTrue(correct);
assertEquals(8, hm.numGuessesRemaining());
assertEquals(5, hm.numLettersRemaining());
assertEquals("S P _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("SP", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
b5c2ca33-9b59-4493-9df2-ed3df851b85e | @Test
public void testIncorrectGuess() {
// make an incorrect guess and see if everything is updated
boolean correct = hm.makeGuess('K');
assertFalse(correct);
assertEquals(7, hm.numGuessesRemaining());
assertEquals(7, hm.numLettersRemaining());
assertEquals("_ _ _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("K", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
ca67950b-4b25-4d84-9eb6-ee3b77ef571b | @Test
public void testTwoIncorrectGuesses() {
// make two incorrect guesses and see if everything is updated
boolean correct = hm.makeGuess('K');
assertFalse(correct);
correct = hm.makeGuess('T');
assertFalse(correct);
assertEquals(6, hm.numGuessesRemaining());
assertEquals(7, hm.numLettersRemaining());
assertEquals("_ _ _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("KT", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
2d3a8813-57ea-4c3f-ae88-52c278947f14 | @Test
public void testCorrectAndIncorrectGuesses() {
// make correct and incorrect guesses and see if everything is updated
boolean correct = hm.makeGuess('S');
assertTrue(correct);
correct = hm.makeGuess('T');
assertFalse(correct);
correct = hm.makeGuess('P');
assertTrue(correct);
correct = hm.makeGuess('K');
assertFalse(correct);
assertEquals(6, hm.numGuessesRemaining());
assertEquals(5, hm.numLettersRemaining());
assertEquals("S P _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("STPK", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
22cd7002-9b1b-4215-a995-4ece29fddcfc | @Test
public void testIllegalCharGuess() {
boolean correct = hm.makeGuess('?');
assertFalse(correct);
assertEquals(8, hm.numGuessesRemaining());
assertEquals("_ _ _ _ _ _ _ _ _ ", hm.displayGameState());
assertEquals("", hm.lettersGuessed());
assertFalse(hm.gameOver());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.