Example usage for weka.classifiers Evaluation errorRate

List of usage examples for weka.classifiers Evaluation errorRate

Introduction

In this page you can find the example usage for weka.classifiers Evaluation errorRate.

Prototype

public final double errorRate() 

Source Link

Document

Returns the estimated error rate or the root mean squared error (if the class is numeric).

Usage

From source file:classif.ExperimentsLauncher.java

License:Open Source License

public void launchStaticEnsemble() {
    try {/*from   ww  w  . jav  a2s  .  com*/
        String algo = "StaticEnsemble";
        System.out.println(algo);

        double testError = 0.0;
        double testError_DT = 0.0;
        double testError_FKM_4 = 0.0;
        double testError_FKM_10 = 0.0;
        //         double testError_KMeans = 0.0;
        startTime = System.currentTimeMillis();
        StaticEnsembleClassify staticensembleClassify = new StaticEnsembleClassify();
        staticensembleClassify.buildClassifier(train);
        endTime = System.currentTimeMillis();
        duration = endTime - startTime;
        //         Duration traintime = Duration.ofMillis(duration);
        //         System.out.println(traintime);

        Evaluation eval_FKM_4 = new Evaluation(train);
        eval_FKM_4.evaluateModel(staticensembleClassify.getFkm_4(), test);
        testError_FKM_4 = eval_FKM_4.errorRate();
        staticensembleClassify.setWeight_fkm_4(testError_FKM_4);
        System.out.println("TestError of FKM_4:" + testError_FKM_4 + "\n");

        //         Evaluation eval_KMeans = new Evaluation(train);
        //         eval_KMeans.evaluateModel(ensembleClassify.getKMeans(), test);
        //         testError_KMeans = eval_KMeans.errorRate();
        //         ensembleClassify.setWeight_kmeans(testError_KMeans);
        //         System.out.println("TestError of KMeans:" + testError_KMeans + "\n");

        Evaluation eval_FKM_10 = new Evaluation(train);
        eval_FKM_10.evaluateModel(staticensembleClassify.getFkm_10(), test);
        testError_FKM_10 = eval_FKM_10.errorRate();
        staticensembleClassify.setWeight_fkm_10(testError_FKM_10);
        System.out.println("TestError of FKM_10:" + testError_FKM_10 + "\n");

        Evaluation eval_DT = new Evaluation(train);
        eval_DT.evaluateModel(staticensembleClassify.getDt(), test);
        testError_DT = eval_DT.errorRate();
        staticensembleClassify.setWeight_dt(testError_DT);
        System.out.println("TestError of DT:" + testError_DT + "\n");

        Evaluation eval = new Evaluation(train);
        eval.evaluateModel(staticensembleClassify, test);
        testError = eval.errorRate();
        System.out.println("TestError of Ensemble:" + testError + "\n");
        System.out.println(eval.toSummaryString());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:classif.ExperimentsLauncher.java

License:Open Source License

public void launchDynamicEnsemble() {
    int method = 0;
    switch (method) {
    case 0:// w  w  w  . j  a  v  a2 s  .  c  o  m
        try {
            String algo = "BigDTDynamicEnsemble";
            System.out.println(algo);

            double testError = 0.0;
            BDTEClassifier dynamicEnsembleClassify = new BDTEClassifier();
            dynamicEnsembleClassify.buildClassifier(train);
            Evaluation eval = new Evaluation(train);
            eval.evaluateModel(dynamicEnsembleClassify, test);
            testError = eval.errorRate();
            System.out.println("TestError:" + testError + "\n");
            System.out.println(eval.toSummaryString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;

    case 1:
        try {
            String algo = "FKMDynamicEnsemble";
            System.out.println(algo);

            double testError = 0.0;
            FKMDEClassifier dynamicEnsembleClassify = new FKMDEClassifier();
            dynamicEnsembleClassify.buildClassifier(train);
            Evaluation eval = new Evaluation(train);
            eval.evaluateModel(dynamicEnsembleClassify, test);
            testError = eval.errorRate();
            System.out.println("TestError:" + testError + "\n");
            System.out.println(eval.toSummaryString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    }
}

From source file:classif.ExperimentsLauncher.java

License:Open Source License

public void launchPU(double ratio) {
    try {//from  w  ww  . j  a va 2  s .co  m
        //         out = new PrintStream(new FileOutputStream(rep + "/DT_" + dataName + "_results.csv", true));
        String algo = "PU";
        System.out.println(algo);
        double testError = 0.0;
        startTime = System.currentTimeMillis();
        //         POSC45 pu = new POSC45();
        DTWD pu = new DTWD();
        pu.setRatio(ratio);
        pu.buildClassifier(train);
        endTime = System.currentTimeMillis();
        duration = endTime - startTime;
        //         Duration traintime = Duration.ofMillis(duration);
        //         System.out.println(traintime);
        startTime = System.currentTimeMillis();
        Evaluation eval = new Evaluation(train);
        eval.evaluateModel(pu, test);
        //         StringBuffer forPredictionsPrinting = new StringBuffer();
        //         eval.evaluateModel(pu, train, forPredictionsPrinting, null, false);
        //         System.out.println(eval.toClassDetailsString());
        //         System.out.println(eval.toSummaryString("\nResults\n======\n", false));
        //         System.out.println(eval.toMatrixString());
        //         System.out.println(forPredictionsPrinting);
        System.out.println(eval.fMeasure(0));
        testError = eval.errorRate();
        endTime = System.currentTimeMillis();
        duration = endTime - startTime;
        //         Duration testtime = Duration.ofMillis(duration);
        //         System.out.println(testtime);
        System.out.println("TestError:" + testError + "\n");
        //         System.out.println(eval.toSummaryString());
        //         out.format("%s,%.4f\n", dataName,  testError);
        //         out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:classif.ExperimentsLauncher.java

License:Open Source License

public void launchPUKMeans() {
    try {/*  w w  w .j a v  a 2 s .  c  om*/
        //         File f = new File(rep + "/" + dataName + "_results.csv");
        //         // if somebody is processing it
        //         if (f.exists()) {
        //            return;
        //         }
        //
        //         out = new PrintStream(new FileOutputStream(rep + "/KMeansDTW_" + "all" + "_results.csv", true));
        //         out.println("dataset,algorithm,nbPrototypes,testErrorRate,trainErrorRate");
        String algo = "PUKMEANS";
        System.out.println(algo);
        //         PrintStream outProto = new PrintStream(new FileOutputStream(rep + "/" + dataName + "_KMEANS.proto", append));

        nbPrototypesMax = this.train.numInstances() / this.train.numClasses();
        if (nbPrototypesMax > 100)
            nbPrototypesMax = 50;
        int tmp;
        tmp = nbExp;
        double[] avgerror = new double[5];
        double[] avgf1 = new double[5];

        for (int j = 1; j <= nbPrototypesMax; j += 1) {
            if (j == 1)
                nbExp = 1;
            else
                nbExp = tmp;
            System.out.println("nbPrototypes=" + j);
            for (int n = 0; n < nbExp; n++) {
                //               System.out.println("This is the "+n+" time.");
                DTWPUKMeans classifierKMeans = new DTWPUKMeans();
                classifierKMeans.setNbClustersinUNL(j);
                startTime = System.currentTimeMillis();
                classifierKMeans.buildClassifier(train);
                endTime = System.currentTimeMillis();
                duration = endTime - startTime;
                //               Duration traintime = Duration.ofMillis(duration);
                //               System.out.println(traintime);
                Evaluation eval = new Evaluation(train);
                eval.evaluateModel(classifierKMeans, test);
                avgerror[n] = eval.errorRate();
                avgf1[n] = eval.fMeasure(0);

                //               PrototyperUtil.savePrototypes(classifierKMeans.prototypes, rep + "/" + dataName + "_KMEANS[" + j + "]_XP" + n + ".proto");

                //               out.format("%s,%s,%d,%.4f\n", dataName, algo, (j * train.numClasses()), testError);
                //               out.flush();
            }
            System.out
                    .println("TestError:" + Utils.mean(avgerror) + "\tF-Measures:" + Utils.mean(avgf1) + "\n");
        }
        //         outProto.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:classif.Prototyper.java

License:Open Source License

/**
 * Predict the accuracy of the prototypes based on the learning set. It uses
 * cross validation to draw the prediction.
 * /*from   w ww . jav a 2s .co m*/
 * @param nbFolds
 *            the number of folds for the x-validation
 * @return the predicted accuracy
 */
public double predictAccuracyXVal(int nbFolds) throws Exception {
    Evaluation eval = new Evaluation(trainingData);
    eval.crossValidateModel(this, trainingData, nbFolds, new Random(), new Object[] {});
    return eval.errorRate();
}

From source file:com.edwardraff.WekaMNIST.java

License:Open Source License

private static void evalModel(Classifier wekaModel, Instances train, Instances test) throws Exception {
    long start;/*from   w  w  w  .  ja v a2s  .  c  o m*/
    long end;
    System.gc();
    start = System.currentTimeMillis();
    wekaModel.buildClassifier(train);
    end = System.currentTimeMillis();
    System.out.println("\tTraining took: " + (end - start) / 1000.0);

    System.gc();
    Evaluation eval = new Evaluation(train);
    start = System.currentTimeMillis();
    eval.evaluateModel(wekaModel, test);
    end = System.currentTimeMillis();
    System.out.println(
            "\tEvaluation took " + (end - start) / 1000.0 + " seconds with an error rate " + eval.errorRate());

    System.gc();
}

From source file:com.reactivetechnologies.analytics.core.eval.AdaBoostM1WithBuiltClassifiers.java

License:Open Source License

@Override
protected void buildClassifierWithWeights(Instances data) throws Exception {

    Instances training;/*from ww w.j a va2 s  .c o m*/
    double epsilon, reweight;
    Evaluation evaluation;
    int numInstances = data.numInstances();

    // Initialize data
    m_Betas = new double[m_Classifiers.length];
    m_NumIterationsPerformed = 0;

    // Create a copy of the data so that when the weights are diddled
    // with it doesn't mess up the weights for anyone else
    training = new Instances(data, 0, numInstances);

    // Do boostrap iterations
    for (m_NumIterationsPerformed = 0; m_NumIterationsPerformed < m_Classifiers.length; m_NumIterationsPerformed++) {
        if (m_Debug) {
            System.err.println("Training classifier " + (m_NumIterationsPerformed + 1));
        }
        // Select instances to train the classifier on
        if (m_WeightThreshold < 100) {
            selectWeightQuantile(training, (double) m_WeightThreshold / 100);
        } else {
            new Instances(training, 0, numInstances);
        }

        /** Changed here: DO NOT Build the classifier! */
        /*if (m_Classifiers[m_NumIterationsPerformed] instanceof Randomizable)
          ((Randomizable) m_Classifiers[m_NumIterationsPerformed]).setSeed(randomInstance.nextInt());
                
        m_Classifiers[m_NumIterationsPerformed].buildClassifier(trainData);*/
        /** End change */

        // Evaluate the classifier
        evaluation = new Evaluation(data);
        evaluation.evaluateModel(m_Classifiers[m_NumIterationsPerformed], training);
        epsilon = evaluation.errorRate();

        // Stop if error too small or error too big and ignore this model
        if (Utils.grOrEq(epsilon, 0.5) || Utils.eq(epsilon, 0)) {
            if (m_NumIterationsPerformed == 0) {
                m_NumIterationsPerformed = 1; // If we're the first we have to to use it
            }
            break;
        }
        // Determine the weight to assign to this model
        m_Betas[m_NumIterationsPerformed] = Math.log((1 - epsilon) / epsilon);
        reweight = (1 - epsilon) / epsilon;
        if (m_Debug) {
            System.err.println("\terror rate = " + epsilon + "  beta = " + m_Betas[m_NumIterationsPerformed]);
        }

        // Update instance weights
        setWeights(training, reweight);
    }
}

From source file:com.reactivetechnologies.analytics.core.eval.AdaBoostM1WithBuiltClassifiers.java

License:Open Source License

@Override
protected void buildClassifierUsingResampling(Instances data) throws Exception {

    Instances trainData, training;/* w  w w .j  a  v a2  s .  c o  m*/
    double epsilon, reweight, sumProbs;
    Evaluation evaluation;
    int numInstances = data.numInstances();
    int resamplingIterations = 0;

    // Initialize data
    m_Betas = new double[m_Classifiers.length];
    m_NumIterationsPerformed = 0;
    // Create a copy of the data so that when the weights are diddled
    // with it doesn't mess up the weights for anyone else
    training = new Instances(data, 0, numInstances);
    sumProbs = training.sumOfWeights();
    for (int i = 0; i < training.numInstances(); i++) {
        training.instance(i).setWeight(training.instance(i).weight() / sumProbs);
    }

    // Do boostrap iterations
    for (m_NumIterationsPerformed = 0; m_NumIterationsPerformed < m_Classifiers.length; m_NumIterationsPerformed++) {
        if (m_Debug) {
            System.err.println("Training classifier " + (m_NumIterationsPerformed + 1));
        }

        // Select instances to train the classifier on
        if (m_WeightThreshold < 100) {
            trainData = selectWeightQuantile(training, (double) m_WeightThreshold / 100);
        } else {
            trainData = new Instances(training);
        }

        // Resample
        resamplingIterations = 0;
        double[] weights = new double[trainData.numInstances()];
        for (int i = 0; i < weights.length; i++) {
            weights[i] = trainData.instance(i).weight();
        }
        do {

            /** Changed here: DO NOT build classifier*/
            // Build and evaluate classifier
            //m_Classifiers[m_NumIterationsPerformed].buildClassifier(sample);
            /** End change */

            evaluation = new Evaluation(data);
            evaluation.evaluateModel(m_Classifiers[m_NumIterationsPerformed], training);
            epsilon = evaluation.errorRate();
            resamplingIterations++;
        } while (Utils.eq(epsilon, 0) && (resamplingIterations < 10));

        // Stop if error too big or 0
        if (Utils.grOrEq(epsilon, 0.5) || Utils.eq(epsilon, 0)) {
            if (m_NumIterationsPerformed == 0) {
                m_NumIterationsPerformed = 1; // If we're the first we have to to use it
            }
            break;
        }

        // Determine the weight to assign to this model
        m_Betas[m_NumIterationsPerformed] = Math.log((1 - epsilon) / epsilon);
        reweight = (1 - epsilon) / epsilon;
        if (m_Debug) {
            System.err.println("\terror rate = " + epsilon + "  beta = " + m_Betas[m_NumIterationsPerformed]);
        }

        // Update instance weights
        setWeights(training, reweight);
    }
}

From source file:Control.Classificador.java

public ArrayList<Resultado> classificar(Plano plano, Arquivo arq) {
    try {/*w ww .  ja v  a2 s  . c  o m*/
        FileReader leitor = new FileReader(arq.arquivo);
        Instances conjunto = new Instances(leitor);
        conjunto.setClassIndex(conjunto.numAttributes() - 1);
        Evaluation avaliacao = new Evaluation(conjunto);
        conjunto = conjunto.resample(new Random());

        Instances baseTreino = null, baseTeste = null;
        Random rand = new Random(1);

        if (plano.eHoldOut) {
            baseTeste = conjunto.testCV(3, 0);
            baseTreino = conjunto.trainCV(3, 0);
        } else {
            baseTeste = baseTreino = conjunto;
        }

        if (plano.IBK) {
            try {
                IB1 vizinho = new IB1();
                vizinho.buildClassifier(baseTeste);
                avaliacao.crossValidateModel(vizinho, baseTeste,
                        (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand);
                Resultado resultado = new Resultado("NN",
                        avaliacao.toMatrixString("Algortmo Vizinho Mais Prximo - Matriz de Confuso"),
                        avaliacao.toClassDetailsString("kNN"));
                resultado.setTaxaErro(avaliacao.errorRate());
                resultado.setTaxaAcerto(1 - avaliacao.errorRate());
                resultado.setRevocacao(recallToDouble(avaliacao, baseTeste));
                resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste));
                this.resultados.add(resultado);
            } catch (UnsupportedAttributeTypeException ex) {
                Mensagem.erro("Algortmo IB1 no suporta atributos numricos!", "MTCS - ERRO");
            }
        }
        if (plano.J48) {
            try {
                J48 j48 = new J48();
                j48.buildClassifier(baseTeste);
                avaliacao.crossValidateModel(j48, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(),
                        rand);
                Resultado resultado = new Resultado("J48",
                        avaliacao.toMatrixString("Algortmo J48 - Matriz de Confuso"),
                        avaliacao.toClassDetailsString("J48"));
                resultado.setTaxaErro(avaliacao.errorRate());
                resultado.setTaxaAcerto(1 - avaliacao.errorRate());
                resultado.setRevocacao(recallToDouble(avaliacao, baseTeste));
                resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste));
                this.resultados.add(resultado);
            } catch (UnsupportedAttributeTypeException ex) {
                Mensagem.erro("Algortmo J48 no suporta atributos nominais!", "MTCS - ERRO");
            }
        }
        if (plano.KNN) {
            try {
                IBk knn = new IBk(3);
                knn.buildClassifier(baseTeste);
                avaliacao.crossValidateModel(knn, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(),
                        rand);
                Resultado resultado = new Resultado("KNN",
                        avaliacao.toMatrixString("Algortmo KNN - Matriz de Confuso"),
                        avaliacao.toClassDetailsString("kNN"));
                resultado.setTaxaErro(avaliacao.errorRate());
                resultado.setTaxaAcerto(1 - avaliacao.errorRate());
                resultado.setRevocacao(recallToDouble(avaliacao, baseTeste));
                resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste));
                this.resultados.add(resultado);
            } catch (UnsupportedAttributeTypeException ex) {
                Mensagem.erro("Algortmo KNN no suporta atributos numricos!", "MTCS - ERRO");
            }

        }
        if (plano.Naive) {
            NaiveBayes naive = new NaiveBayes();
            naive.buildClassifier(baseTeste);
            avaliacao.crossValidateModel(naive, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(),
                    rand);
            Resultado resultado = new Resultado("Naive",
                    avaliacao.toMatrixString("Algortmo NaiveBayes - Matriz de Confuso"),
                    avaliacao.toClassDetailsString("kNN"));
            resultado.setTaxaErro(avaliacao.errorRate());
            resultado.setTaxaAcerto(1 - avaliacao.errorRate());
            resultado.setRevocacao(recallToDouble(avaliacao, baseTeste));
            resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste));
            this.resultados.add(resultado);
        }
        if (plano.Tree) {
            try {
                Id3 id3 = new Id3();
                id3.buildClassifier(baseTeste);
                avaliacao.crossValidateModel(id3, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(),
                        rand);
                Resultado resultado = new Resultado("ID3",
                        avaliacao.toMatrixString("Algortmo ID3 - Matriz de Confuso"),
                        avaliacao.toClassDetailsString("kNN"));
                resultado.setTaxaErro(avaliacao.errorRate());
                resultado.setTaxaAcerto(1 - avaliacao.errorRate());
                resultado.setRevocacao(recallToDouble(avaliacao, baseTeste));
                resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste));
                this.resultados.add(resultado);
            } catch (UnsupportedAttributeTypeException ex) {
                Mensagem.erro("Algortmo Arvore de Deciso no suporta atributos numricos!",
                        "MTCS - ERRO");

            }
        }

    } catch (FileNotFoundException ex) {

        Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
        Mensagem.erro("Selecione um arquivo para comear!", "MTCS - ERRO");
        Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex);
    }

    return this.resultados;
}

From source file:ffnn.FFNNTubesAI.java

@Override
public void buildClassifier(Instances i) throws Exception {
    Instance temp_instance = null;/*from w  w w  . ja v  a2  s.c  o  m*/
    RealMatrix error_output;
    RealMatrix error_hidden;
    RealMatrix input_matrix;
    RealMatrix hidden_matrix;
    RealMatrix output_matrix;
    Instances temp_instances;
    int r = 0;
    Scanner scan = new Scanner(System.in);

    output_layer = i.numDistinctValues(i.classIndex()); //3
    temp_instances = filterNominalNumeric(i);

    if (output_layer == 2) {
        Add filter = new Add();
        filter.setAttributeIndex("last");
        filter.setAttributeName("dummy");
        filter.setInputFormat(temp_instances);
        temp_instances = Filter.useFilter(temp_instances, filter);
        //            System.out.println(temp_instances);
        for (int j = 0; j < temp_instances.numInstances(); j++) {
            if (temp_instances.instance(j).value(temp_instances.numAttributes() - 2) == 0) {
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 2, 1);
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 1, 0);
            } else {
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 2, 0);
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 1, 1);
            }
        }
    }

    //temp_instances.randomize(temp_instances.getRandomNumberGenerator(1));
    //System.out.println(temp_instances);
    input_layer = temp_instances.numAttributes() - output_layer; //4
    hidden_layer = 0;
    while (hidden_layer < 1) {
        System.out.print("Hidden layer : ");
        hidden_layer = scan.nextInt();
    }
    int init_hidden = hidden_layer;
    error_hidden = new BlockRealMatrix(1, hidden_layer);
    error_output = new BlockRealMatrix(1, output_layer);
    input_matrix = new BlockRealMatrix(1, input_layer + 1); //Menambahkan bias

    buildWeight(input_layer, hidden_layer, output_layer);

    long last_time = System.nanoTime();
    double last_error_rate = 1;
    double best_error_rate = 1;

    double last_update = System.nanoTime();

    // brp iterasi
    //        for( long itr = 0; last_error_rate > 0.001; ++ itr ){
    for (long itr = 0; itr < 50000; ++itr) {
        if (r == 10) {
            break;
        }
        long time = System.nanoTime();
        if (time - last_time > 2000000000) {
            Evaluation eval = new Evaluation(i);
            eval.evaluateModel(this, i);

            double accry = eval.correct() / eval.numInstances();
            if (eval.errorRate() < last_error_rate) {
                last_update = System.nanoTime();
                if (eval.errorRate() < best_error_rate)
                    SerializationHelper.write(accry + "-" + time + ".model", this);
            }

            if (accry > 0)
                last_error_rate = eval.errorRate();

            // 2 minute without improvement restart
            if (time - last_update > 30000000000L) {
                last_update = System.nanoTime();
                learning_rate = random() * 0.05;
                hidden_layer = (int) (10 + floor(random() * 15));
                hidden_layer = (int) floor((hidden_layer / 25) * init_hidden);
                if (hidden_layer == 0) {
                    hidden_layer = 1;
                }
                itr = 0;
                System.out.println("RESTART " + learning_rate + " " + hidden_layer);
                buildWeight(input_layer, hidden_layer, output_layer);
                r++;
            }

            System.out.println(accry + " " + itr);
            last_time = time;
        }

        for (int j = 0; j < temp_instances.numInstances(); j++) {
            // foward !!
            temp_instance = temp_instances.instance(j);

            for (int k = 0; k < input_layer; k++) {
                input_matrix.setEntry(0, k, temp_instance.value(k));
            }
            input_matrix.setEntry(0, input_layer, 1.0); // bias

            hidden_matrix = input_matrix.multiply(weight1);
            for (int y = 0; y < hidden_layer; ++y) {
                hidden_matrix.setEntry(0, y, sig(hidden_matrix.getEntry(0, y)));
            }

            output_matrix = hidden_matrix.multiply(weight2).add(bias2);
            for (int y = 0; y < output_layer; ++y) {
                output_matrix.setEntry(0, y, sig(output_matrix.getEntry(0, y)));
            }

            // backward <<

            // error layer 2
            double total_err = 0;
            for (int k = 0; k < output_layer; k++) {
                double o = output_matrix.getEntry(0, k);
                double t = temp_instance.value(input_layer + k);
                double err = o * (1 - o) * (t - o);
                total_err += err * err;
                error_output.setEntry(0, k, err);
            }

            // back propagation layer 2
            for (int y = 0; y < hidden_layer; y++) {
                for (int x = 0; x < output_layer; ++x) {
                    double wold = weight2.getEntry(y, x);
                    double correction = learning_rate * error_output.getEntry(0, x)
                            * hidden_matrix.getEntry(0, y);
                    weight2.setEntry(y, x, wold + correction);
                }
            }

            for (int x = 0; x < output_layer; ++x) {
                double correction = learning_rate * error_output.getEntry(0, x); // anggap 1 inputnya
                bias2.setEntry(0, x, bias2.getEntry(0, x) + correction);
            }

            // error layer 1
            for (int k = 0; k < hidden_layer; ++k) {
                double o = hidden_matrix.getEntry(0, k);
                double t = 0;
                for (int x = 0; x < output_layer; ++x) {
                    t += error_output.getEntry(0, x) * weight2.getEntry(k, x);
                }
                double err = o * (1 - o) * t;
                error_hidden.setEntry(0, k, err);
            }

            // back propagation layer 1
            for (int y = 0; y < input_layer + 1; ++y) {
                for (int x = 0; x < hidden_layer; ++x) {
                    double wold = weight1.getEntry(y, x);
                    double correction = learning_rate * error_hidden.getEntry(0, x)
                            * input_matrix.getEntry(0, y);
                    weight1.setEntry(y, x, wold + correction);
                }
            }
        }
    }
}