Beispiel #1
0
  /**
   * It the function that writes
   *
   * @param fichero the name of file
   * @param ec_tra The value of training MSE
   * @param ec_tst The value of test MSE
   * @param B An element of the Base class
   * @param P An element of poblacion class
   */
  public void write(String fichero, double ec_tra, double ec_tst, Base B, Poblacion P) {

    int i, j;
    String output = new String("");
    output += "Numero de reglas: ";
    output += B.getN_reglas() + "\n" + "\n";
    for (i = 0; i < B.getN_reglas(); i++) {
      for (j = 0; j < B.getN_variables(); j++)
        output +=
            B.getBDatos_x0(j, B.getBregla(B.getIndex(i), j))
                + " "
                + B.getBDatos_x1(j, B.getBregla(B.getIndex(i), j))
                + " "
                + B.getBDatos_x3(j, B.getBregla(B.getIndex(i), j))
                + "\n";
      output += "\n";
    }
    if (B.getSalidaPDEF() != 87654321)
      output += "\nSalida por defecto: " + B.getSalidaPDEF() + "\n";

    output += "\n";

    output += "\nMSEtra: " + ec_tra + " MSEtst: " + ec_tst + "\n";

    Fichero.escribeFichero(fichero, output);
  }
Beispiel #2
0
  /**
   * Obtains the parameters used in the execution of the algorithm and stores them in the private
   * variables of the class
   *
   * @param ficheroScript Name of the configuration script that indicates the parameters that are
   *     going to be used during the execution of the algorithm
   */
  public void leerConfiguracion(String ficheroScript) {

    String fichero, linea, token;
    StringTokenizer lineasFichero, tokens;
    byte line[];
    int i, j;

    ficheroSalida = new String[2];

    fichero = Fichero.leeFichero(ficheroScript);
    lineasFichero = new StringTokenizer(fichero, "\n\r");

    lineasFichero.nextToken();
    linea = lineasFichero.nextToken();

    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of the training and test files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTraining = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTest = new String(line, i, j - i);

    /*Getting the path and base name of the results files*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of output files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[0] = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[1] = new String(line, i, j - i);

    /*Getting the seed*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    semilla = Long.parseLong(tokens.nextToken().substring(1));

    /*Getting the number of neighbors*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    k = Integer.parseInt(tokens.nextToken().substring(1));
  }
Beispiel #3
0
  /** Calculates the necessary statistical data and creates KEEL out-put files */
  private void generaSalida() {
    Fichero f = new Fichero();
    String cad = "";
    String miSalida = new String("");
    miSalida = train.copiaCabeceraTest();
    // System.out.println("\n Estas son las reglas encontradas:");
    // conjReglasFinal.print();
    conjunto_reglas.adjuntaNombreClases(clases);
    conjunto_reglas.adjuntaNombreClase(nombre_atributos[train.getnentradas()]);
    cad = conjunto_reglas.printString();
    /*cad += "\n\n" + evReg.printString() + "\n\n  Time (seconds); " +
    (tiempo / 1000);*/

    f.escribeFichero(ficheroSalida, cad);

    f.escribeFichero(ficheroSalidaTr, miSalida + evReg.salida(datosTrain));
    f.escribeFichero(ficheroSalidaTst, miSalida + evReg.salida(datosTest));
  }
Beispiel #4
0
  /**
   * It obtains all the necesary information from the configuration file.<br>
   * First of all it reads the name of the input data-sets, training, validation and test.<br>
   * Then it reads the name of the output files, where the training (validation) and test outputs
   * will be stored<br>
   * Finally it read the parameters of the algorithm, such as the random seed.<br>
   *
   * @param fileName Name of the configuration file
   */
  public void parseConfigurationFile(String fileName) {
    StringTokenizer line;
    String file = Fichero.leeFichero(fileName); // file is an string containing the whole file

    line = new StringTokenizer(file, "\n\r");
    readName(line); // We read the algorithm name
    readInputFiles(line); // We read all the input files
    readOutputFiles(line); // We read all the output files
    readAllParameters(line); // We read all the possible parameters
  };
Beispiel #5
0
 /**
  * It generates the output file from a given dataset and stores it in a file
  *
  * @param dataset myDataset input dataset
  * @param filename String the name of the file
  * @param lanzar Chc the algorithm class
  */
 private void doOutput(myDataset dataset, String filename, Chc lanzar) {
   String output = new String("");
   output = dataset.copyHeader(); // we insert the header in the outputa file
   // We write the output for each example
   for (int i = 0; i < dataset.getnData(); i++) {
     // for regression:
     output +=
         dataset.getOutputAsReal(i)
             + " "
             + (double) this.regressionOutput(dataset.getExample(i), lanzar)
             + "\n";
   }
   Fichero.escribeFichero(filename, output);
 }
Beispiel #6
0
 /**
  * 9b) Descargar las sentencias de un almacén en un archivo de texto de nuestro directorio.
  *
  * @param nombreDeArchivo - fichero en el que se van a escribir las sentencias del almacén
  */
 public void descargar(String nombreDeArchivo) {
   try {
     Arista arista;
     Fichero.abrir(nombreDeArchivo, true, false);
     for (int i = 0; i < nodosSalientes.size(); ++i) {
       for (int j = 0; j < nodosSalientes.get(i).size(); ++j) {
         arista = nodosSalientes.get(i).get(j);
         for (int k = 0; k < arista.repeticiones; ++k)
           Fichero.escribirSentencia(
               listaSujetosObjetos.get(i)
                   + " "
                   + listaPropiedades.get(arista.propiedad)
                   + " "
                   + listaSujetosObjetos.get(arista.verticeObjetivo)
                   + " .");
       }
     }
     Fichero.cerrar();
   } catch (IOException e) {
     System.err.println("Error: Imposible acceder al fichero especificado.");
     return;
   }
 }
Beispiel #7
0
 /**
  * It generates the output file from a given dataset and stores it in a file
  *
  * @param dataset myDataset input dataset
  * @param filename String the name of the file
  * @param data containing integer identifiers of nominal values
  * @param classData containing integer identifiers of classes
  * @param infoAttr containing number of values for each attribute
  * @param contenedor containing all the interesting rules
  * @param nClasses indicates number of classes
  */
 private void doOutput(
     myDataset dataset,
     String filename,
     int data[][],
     int classData[],
     int infoAttr[],
     Vector<Rule> contenedor,
     int nClases) {
   String output = new String("");
   output = dataset.copyHeader(); // we insert the header in the output file
   // We write the output for each example
   for (int i = 0; i < dataset.getnData(); i++) {
     // for classification:
     output +=
         dataset.getOutputAsString(i)
             + " "
             + this.classificationOutput(
                 dataset, i, data, classData, infoAttr, contenedor, nClasses)
             + "\n";
   }
   Fichero.escribeFichero(filename, output);
 }
Beispiel #8
0
  public static void main(String[] args) throws IOException {

    Fichero fich1 = new Fichero("D:\\cascas.txt");
    existeArchivo(fich1);

    fich1.crearFichero();
    existeArchivo(fich1);

    fich1.escribirFichero("Paco el botero.");
    fich1.escribirFichero("Vaya porro fuman algunos.");

    System.out.println(fich1.leerFichero());

    fich1.abrirArchivo();

    try {
      Thread.sleep(4000);
      fich1.eliminarFichero();
    } catch (Exception e) {
    }
  }
Beispiel #9
0
  /** Reads the data of the configuration file */
  public void leer_conf() {
    int i, j;
    String cadenaEntrada, valor;
    double cruce, mutacion, a, b, tau;
    int long_poblacion, tipo_fitness;

    // we read the file in a String
    cadenaEntrada = Fichero.leeFichero(fichero_conf);
    StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);

    // we read the algorithm's name
    sT.nextToken();
    sT.nextToken();

    // we read the name of the training and test files
    sT.nextToken();
    valor = sT.nextToken();

    StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
    ficheros.nextToken();
    fich_datos_chequeo = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_datos_tst = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_br = ((ficheros.nextToken()).replace('\"', ' ')).trim();

    // we read the name of the output files
    sT.nextToken();
    valor = sT.nextToken();

    ficheros = new StringTokenizer(valor, "\t ", false);
    fich_tra_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_tst_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_reglas = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1);

    // we read the seed of the random generator
    sT.nextToken();
    valor = sT.nextToken();
    semilla = Double.parseDouble(Quita_blancos(valor));
    Randomize.setSeed((long) semilla);
    ;

    // we read the Number of Iterations
    sT.nextToken();
    valor = sT.nextToken();
    n_generaciones = Long.parseLong(Quita_blancos(valor));

    // we read the Population Size
    sT.nextToken();
    valor = sT.nextToken();
    long_poblacion = Integer.parseInt(Quita_blancos(valor));

    // we read the Tau parameter for the minimun maching degree required to the KB
    sT.nextToken();
    valor = sT.nextToken();
    tau = Double.parseDouble(Quita_blancos(valor));

    // we read the Parameter a
    sT.nextToken();
    valor = sT.nextToken();
    a = Double.parseDouble(Quita_blancos(valor));

    // we read the Parameter b
    sT.nextToken();
    valor = sT.nextToken();
    b = Double.parseDouble(Quita_blancos(valor));

    // we read the Type of Fitness Function
    sT.nextToken();
    valor = sT.nextToken();
    tipo_fitness = Integer.parseInt(Quita_blancos(valor));

    // we read the Cross Probability
    sT.nextToken();
    valor = sT.nextToken();
    cruce = Double.parseDouble(Quita_blancos(valor));

    // we read the Mutation Probability
    sT.nextToken();
    valor = sT.nextToken();
    mutacion = Double.parseDouble(Quita_blancos(valor));

    // we create all the objects
    tipoc = 1;
    tabla = new MiDataset(fich_datos_chequeo, true);
    if (tabla.salir == false) {
      base_reglas = new BaseR(fichero_br, tabla);
      fun_adap = new Adap(tabla, base_reglas, tau, tipo_fitness);
      alg_gen = new AG(long_poblacion, base_reglas.n_reglas, cruce, mutacion, a, b, fun_adap);
    }
  }
Beispiel #10
0
  public void run() {
    int i, j;
    double ec, el, ec_tst, el_tst;

    /* We read the configutate file and we initialize the structures and variables */
    leer_conf();
    if (tabla.salir == false) {
      Gen = 0;

      /* Generation of the initial population */
      alg_gen.Initialize();

      /* Evaluation of the initial population */
      alg_gen.Evaluate();

      Gen++;

      /* Main of the genetic algorithm */
      do {
        /* Interchange of the new and old population */
        alg_gen.Intercambio();

        /* Selection by means of Baker */
        alg_gen.Select();

        /* Crossover */
        if (tipoc > 0) alg_gen.Max_Min_Crossover();
        else alg_gen.Cruce_Multipunto();

        /* Mutation */
        alg_gen.Mutacion();

        /* Elitist selection */
        alg_gen.Elitist();

        /* Evaluation of the current population */
        alg_gen.Evaluate();

        /* we increment the counter */
        Gen++;
      } while (Gen <= n_generaciones);

      /* we calcule the MSEs */
      fun_adap.Decodifica(alg_gen.solucion());
      fun_adap.Error_tra();
      ec = fun_adap.EC;
      el = fun_adap.EL;

      tabla_tst = new MiDataset(fich_datos_tst, false);
      fun_adap.Error_tst(tabla_tst);
      ec_tst = fun_adap.EC;
      el_tst = fun_adap.EL;

      fun_adap.Cubrimientos_Base();

      /* we write the RB */
      cadenaReglas = base_reglas.BRtoString();
      cadenaReglas +=
          "\nMSEtra: "
              + ec
              + "  MSEtst: "
              + ec_tst
              + "\nAverage covering degree: "
              + fun_adap.medcb
              + " Minimum covering degree: "
              + fun_adap.mincb;

      Fichero.escribeFichero(fichero_reglas, cadenaReglas);

      /* we write the obligatory output files*/
      String salida_tra = tabla.getCabecera();
      salida_tra += fun_adap.getSalidaObli(tabla);
      Fichero.escribeFichero(fich_tra_obli, salida_tra);

      String salida_tst = tabla_tst.getCabecera();
      salida_tst += fun_adap.getSalidaObli(tabla_tst);
      Fichero.escribeFichero(fich_tst_obli, salida_tst);

      /* we write the MSEs in specific files */
      Fichero.AnadirtoFichero(ruta_salida + "PcomunR.txt", "" + base_reglas.n_reglas + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "PcomunTRA.txt", "" + ec + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "PcomunTST.txt", "" + ec_tst + "\n");
    }
  }
Beispiel #11
0
  /**
   * Reads configuration script, and extracts its contents.
   *
   * @param ficheroScript Name of the configuration script
   */
  public void leerConfiguracion(String ficheroScript) {

    String fichero, linea, token;
    StringTokenizer lineasFichero, tokens;
    byte line[];
    int i, j;

    ficheroSalida = new String[2];

    fichero = Fichero.leeFichero(ficheroScript);
    lineasFichero = new StringTokenizer(fichero, "\n\r");

    lineasFichero.nextToken();
    linea = lineasFichero.nextToken();

    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of training and test files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTraining = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTest = new String(line, i, j - i);

    /*Getting the path and base name of the results files*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of output files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[0] = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[1] = new String(line, i, j - i);

    /*Getting the seed*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    semilla = Long.parseLong(tokens.nextToken().substring(1));

    /*Getting the mutation and cross probability*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    pMutacion1to0 = Double.parseDouble(tokens.nextToken().substring(1));
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    pMutacion0to1 = Double.parseDouble(tokens.nextToken().substring(1));
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    pCruce = Double.parseDouble(tokens.nextToken().substring(1));

    /*Getting the size of the population and number of evaluations*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    tamPoblacion = Integer.parseInt(tokens.nextToken().substring(1));
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    nEval = Integer.parseInt(tokens.nextToken().substring(1));

    /*Getting the alfa equilibrate factor*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    alfa = Double.parseDouble(tokens.nextToken().substring(1));

    /*Getting the type of selection*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();
    token = token.substring(1);
    if (token.equalsIgnoreCase("binary_tournament")) torneo = true;
    else torneo = false;

    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    kNeigh = Integer.parseInt(tokens.nextToken().substring(1));

    /*Getting the type of distance function*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    distanceEu = tokens.nextToken().substring(1).equalsIgnoreCase("Euclidean") ? true : false;
  } // end-method
Beispiel #12
0
  /**
   * Writes results
   *
   * @param nombreFichero Name of the output file
   * @param salidaKNN Instances to write
   * @param prediccion Instances to mantain
   * @param entradas Input attributes characteristics
   * @param salida Output attribute characteristics
   * @param nEntradas Number of input attributes
   * @param relation Name of the data set
   */
  public static void escribeSalida(
      String nombreFichero,
      int[][] salidaKNN,
      int[][] prediccion,
      Attribute entradas[],
      Attribute salida,
      int nEntradas,
      String relation) {

    int n_ejemplos, n_salidas = 0;
    String cadena = "";
    int i, j;

    /*Printing input attributes*/
    cadena += "@relation " + relation + "\n";
    for (i = 0; i < nEntradas; i++) {
      cadena += "@attribute " + entradas[i].getName() + " ";
      if (entradas[i].getType() == Attribute.NOMINAL) {
        cadena += "{";
        for (j = 0; j < entradas[i].getNominalValuesList().size(); j++) {
          cadena += (String) entradas[i].getNominalValuesList().elementAt(j);
          if (j < entradas[i].getNominalValuesList().size() - 1) {
            cadena += ", ";
          }
        }
        cadena += "}\n";
      } else {
        if (entradas[i].getType() == Attribute.INTEGER) {
          cadena += "integer";
        } else {
          cadena += "real";
        }
        cadena +=
            " ["
                + String.valueOf(entradas[i].getMinAttribute())
                + ", "
                + String.valueOf(entradas[i].getMaxAttribute())
                + "]\n";
      }
    }

    /*Printing output attribute*/
    cadena += "@attribute " + salida.getName() + " ";
    if (salida.getType() == Attribute.NOMINAL) {
      cadena += "{";
      for (j = 0; j < salida.getNominalValuesList().size(); j++) {
        cadena += (String) salida.getNominalValuesList().elementAt(j);
        if (j < salida.getNominalValuesList().size() - 1) {
          cadena += ", ";
        }
      }
      cadena += "}\n";
    } else {
      cadena +=
          "integer ["
              + String.valueOf(salida.getMinAttribute())
              + ", "
              + String.valueOf(salida.getMaxAttribute())
              + "]\n";
    }

    /*Printing the data*/
    cadena += "@data\n";

    Fichero.escribeFichero(nombreFichero, cadena);

    n_ejemplos = salidaKNN.length;

    if (n_ejemplos > 0) n_salidas = salidaKNN[0].length;

    for (i = 0; i < n_ejemplos; i++) {
      cadena = "";
      for (j = 0; j < n_salidas; j++) cadena += "" + salidaKNN[i][j] + " ";
      for (j = 0; j < n_salidas; j++) cadena += "" + prediccion[i][j] + " ";
      cadena += "\n";
      Fichero.AnadirtoFichero(nombreFichero, cadena);
    }
  } // end-method
Beispiel #13
0
  /** Reads the data of the configuration file */
  public void leer_conf() {
    int i, n_etiquetas;
    String cadenaEntrada, valor;

    // we read the file in a String
    cadenaEntrada = Fichero.leeFichero(fichero_conf);
    StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);

    // we read the algorithm's name
    sT.nextToken();
    sT.nextToken();

    // we read the name of the training and test files
    sT.nextToken();
    valor = sT.nextToken();

    StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
    ficheros.nextToken();
    fich_datos_chequeo = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_datos_tst = ((ficheros.nextToken()).replace('\"', ' ')).trim();

    // we read the name of the output files
    sT.nextToken();
    valor = sT.nextToken();

    ficheros = new StringTokenizer(valor, "\t ", false);
    fich_tra_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fich_tst_obli = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_reglas = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    fichero_inf = ((ficheros.nextToken()).replace('\"', ' ')).trim();
    ruta_salida = fichero_reglas.substring(0, fichero_reglas.lastIndexOf('/') + 1);

    // we read the Number of labels
    sT.nextToken();
    valor = sT.nextToken();
    n_etiquetas = Integer.parseInt(valor.trim());

    // we read the KB Output File Format with Weight values to 1 (0/1)
    peso = 0;

    // we create all the objects
    tabla = new MiDataset(fich_datos_chequeo, true);
    tabla_tst = new MiDataset(fich_datos_tst, false);
    base_datos = new BaseD(n_etiquetas, tabla.n_variables);

    for (i = 0; i < tabla.n_variables; i++) {
      base_datos.n_etiquetas[i] = n_etiquetas;
      base_datos.extremos[i].min = tabla.extremos[i].min;
      base_datos.extremos[i].max = tabla.extremos[i].max;
    }

    MaxReglas = tabla.long_tabla; // MaxReglas == #Ejemplos
    base_reglas = new BaseR(MaxReglas, base_datos, tabla);
    fun_adap = new Adap(tabla, tabla_tst, base_reglas);
    Regla_act = new int[tabla.n_variables];
    grado_pertenencia = new double[tabla.n_variables];
    Conjunto_Reglas = new TipoRegla[tabla.long_tabla];

    for (i = 0; i < tabla.long_tabla; i++) {
      Conjunto_Reglas[i] = new TipoRegla(tabla.n_variables);
    }
  }
Beispiel #14
0
 /**
  * It stores the rule base in a given file
  *
  * @param filename Name for the rulebase file
  */
 public void saveFile(String filename) {
   String stringOut = new String("");
   stringOut = printString();
   Fichero.escribeFichero(filename, stringOut);
 }
Beispiel #15
0
  public void leerConfiguracion(String ficheroScript) {

    String fichero, linea, token;
    StringTokenizer lineasFichero, tokens;
    byte line[];
    int i, j;

    ficheroSalida = new String[2];

    fichero = Fichero.leeFichero(ficheroScript);
    lineasFichero = new StringTokenizer(fichero, "\n\r");

    lineasFichero.nextToken();
    linea = lineasFichero.nextToken();

    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of the training and test files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTraining = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroTest = new String(line, i, j - i);

    /*Getting the path and base name of the results files*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    token = tokens.nextToken();

    /*Getting the names of output files*/
    line = token.getBytes();
    for (i = 0; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[0] = new String(line, i, j - i);
    for (i = j + 1; line[i] != '\"'; i++) ;
    i++;
    for (j = i; line[j] != '\"'; j++) ;
    ficheroSalida[1] = new String(line, i, j - i);

    /*Getting the number of neighbours*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    k = Integer.parseInt(tokens.nextToken().substring(1));

    /*Getting the k' */
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    k2 = Integer.parseInt(tokens.nextToken().substring(1));

    /*Getting the type of distance function*/
    linea = lineasFichero.nextToken();
    tokens = new StringTokenizer(linea, "=");
    tokens.nextToken();
    distanceEu = tokens.nextToken().substring(1).equalsIgnoreCase("Euclidean") ? true : false;
  }
Beispiel #16
0
  /**
   * Constructora Carga las sentencias en el almacén desde el fichero especificado.
   *
   * @param nombreDeArchivo de texto desde el que leer las entidades
   */
  private Almacen(String nombreDeArchivo) throws IOException {
    // Inicializa los atributos de la clase
    nodosEntrantes = new ListaArray<ListaArray<Arista>>();
    nodosSalientes = new ListaArray<ListaArray<Arista>>();
    sujetos = objetos = propiedades = sentencias = 0;
    arbolSujetosObjetos = new Trie();
    arbolPropiedades = new Trie();
    listaSujetosObjetos = new ListaArray<String>();
    listaPropiedades = new ListaArray<String>();
    // Variables auxiliares
    int tempArista;
    Arista a;

    // Lee las sentencias desde el fichero y las añade al trie y a la lista de nodos del grafo
    Fichero.abrir(nombreDeArchivo, false, false);
    String sentencia, sujeto, propiedad, objeto;
    int idSujeto, idPropiedad, idObjeto;
    StringTokenizer tokenizador;
    sentencia = Fichero.leerSentencia();
    while (sentencia != null) {
      tokenizador = new StringTokenizer(sentencia);
      sujeto = tokenizador.nextToken();
      propiedad = tokenizador.nextToken();
      objeto = tokenizador.nextToken();
      sentencias++;

      // Insertar sujeto en el trie
      idSujeto = arbolSujetosObjetos.insertar(sujeto, sujetos + objetos);
      if (idSujeto == sujetos + objetos) {
        // Agregar al array de int -> String
        listaSujetosObjetos.insertLast(sujeto);
        // Añadir su hueco en las listas de adyacencia
        nodosEntrantes.insertLast(new ListaArray<Arista>());
        nodosSalientes.insertLast(new ListaArray<Arista>());
        // Incrementar contador
        sujetos++;
      }
      // Insertar propiedad en el trie
      idPropiedad = arbolPropiedades.insertar(propiedad, propiedades);
      if (idPropiedad == propiedades) {
        // Agregar al array de int -> String
        listaPropiedades.insertLast(propiedad);
        // En caso de ser una propiedad especial, guardar su valor entero
        if (propiedad.equals(propiedadEs)) idPropiedadEs = idPropiedad;
        else if (propiedad.equals(propiedadSubClaseDe)) idPropiedadSubClaseDe = idPropiedad;
        else if (propiedad.equals(propiedadCursa)) idPropiedadCursa = idPropiedad;
        else if (propiedad.equals(propiedadEncargadoDe)) idPropiedadEncargadoDe = idPropiedad;
        else if (propiedad.equals(propiedadDepartamentoDe)) idPropiedadDepartamentoDe = idPropiedad;
        else if (propiedad.equals(propiedadTrabajaPara)) idPropiedadTrabajaPara = idPropiedad;
        // Incrementar contador
        propiedades++;
      }
      // Insertar objeto en el trie
      idObjeto = arbolSujetosObjetos.insertar(objeto, sujetos + objetos);
      if (idObjeto == sujetos + objetos) {
        // Agregar al array de int -> String
        listaSujetosObjetos.insertLast(objeto);
        // Añadir su hueco en las listas de adyacencia
        nodosEntrantes.insertLast(new ListaArray<Arista>());
        nodosSalientes.insertLast(new ListaArray<Arista>());
        // Incrementar contador
        objetos++;
      }

      // Inserta la arista en la primera lista de adyacencia, o añade una repetición
      tempArista = nodosSalientes.get(idSujeto).find(new Arista(idObjeto, idPropiedad));
      if (tempArista == -1)
        nodosSalientes.get(idSujeto).insertLast(new Arista(idObjeto, idPropiedad));
      else nodosSalientes.get(idSujeto).get(tempArista).repeticiones++;

      // Lee la siguiente sentencia
      sentencia = Fichero.leerSentencia();
    }

    Fichero.cerrar();

    // Crear la segunda lista de adyacencia a partir de la primera
    for (int i = 0; i < nodosSalientes.size(); i++) {
      for (int j = 0; j < nodosSalientes.get(i).size(); j++) {
        a = nodosSalientes.get(i).get(j);
        nodosEntrantes
            .get(a.verticeObjetivo)
            .insertLast(new Arista(i, a.propiedad, a.repeticiones));
      }
    }

    // Ordenar las aristas salientes de cada nodo
    nodosSalientesOrdenados = new ListaArray<ListaArray<Integer>>(nodosSalientes.size());
    for (int i = 0; i < nodosSalientes.size(); ++i)
      nodosSalientesOrdenados.set(i, nodosSalientes.get(i).sort());
  }
Beispiel #17
0
  public static void main(String[] args) {
    String cadena = "";
    StringTokenizer lineas, tokens, tokensT;
    String linea, dato1, dato2, token, timesplit[];
    boolean algorithms = true;
    Vector<String> algoritmos;
    Vector<String> datasets;

    Vector<Integer> saltos;
    int i, j, k, l, m, n;
    double accuracyAv[][];
    double accuracySD[][];
    double reductionAv[][];
    double reductionSD[][];
    double kappaAv[][];
    double kappaSD[][];
    double accredAv[][];
    double kapredAv[][];
    double time[][];
    int runs[][];
    String alAct, alAnterior;
    int configAct;
    String datAct;
    int salAct;
    double acc, red, kappa;
    int aciertos, total;
    double accV[], redV[], kappaV[];
    Vector<String> valoresClase;
    int confusionMatrix[][];
    int sumKappa, sumi, sumj;
    double accSD, redSD, kapSD;
    String tiempos;
    int postime;

    if (args.length != 1) {
      System.err.println("Error. Hace falta un parámetro: Fichero de algoritmos y datasets.");
      System.exit(1);
    }

    algoritmos = new Vector<String>();
    datasets = new Vector<String>();

    saltos = new Vector<Integer>();

    /*Lectura del fichero de configuración*/
    cadena = Fichero.leeFichero(args[0]);
    lineas = new StringTokenizer(cadena, "\n\r");
    while (lineas.hasMoreTokens()) {
      linea = lineas.nextToken();
      if (linea.equalsIgnoreCase("----")) algorithms = false;
      else {
        if (algorithms) {
          algoritmos.addElement(new String(linea));
        } else {
          tokens = new StringTokenizer(linea, " ");
          token = tokens.nextToken();
          datasets.addElement(new String(token));
          token = tokens.nextToken();
          saltos.addElement(new Integer(token));
        }
      }
    }

    accuracyAv = new double[datasets.size()][algoritmos.size()];
    accuracySD = new double[datasets.size()][algoritmos.size()];
    reductionAv = new double[datasets.size()][algoritmos.size()];
    reductionSD = new double[datasets.size()][algoritmos.size()];
    kappaAv = new double[datasets.size()][algoritmos.size()];
    kappaSD = new double[datasets.size()][algoritmos.size()];
    accredAv = new double[datasets.size()][algoritmos.size()];
    kapredAv = new double[datasets.size()][algoritmos.size()];
    time = new double[datasets.size()][algoritmos.size()];
    runs = new int[datasets.size()][algoritmos.size()];
    accV = new double[10];
    redV = new double[10];
    kappaV = new double[10];

    // tiempos = Fichero.leeFichero("tiempos.txt");

    tiempos = Fichero.leeFichero("tiempos.txt");

    tokensT = new StringTokenizer(tiempos, "=\n\r");

    System.out.println("Numbero de algoritmos " + algoritmos.size());
    System.out.println("Dataset Size = " + datasets.size());
    /*Cálculo del accuracy, kappa y reducción en KNN (TRAIN)*/
    configAct = 0;
    for (j = 0; j < datasets.size(); j++) {
      System.out.println("Processing dataset: " + datasets.elementAt(j));

      for (i = 0; i < algoritmos.size(); i++) {
        alAct = (String) algoritmos.elementAt(i);

        configAct = i;

        datAct = (String) datasets.elementAt(j);
        salAct = ((Integer) saltos.elementAt(j)).intValue();
        acc = red = kappa = 0.0;
        for (k = 0; k < 10; k++) {
          /*Accuracy Computation*/
          int result =
              (j + salAct) * algoritmos.size() * 10
                  + i * 10
                  + k; // Calculo el result correspondiente.

          // System.out.println("results//Clas-KNN//"+alAct+"//result"+Integer.toString((j+salAct)*datasets.size()+i*10+k)+".tra");
          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + ".tra");

          lineas = new StringTokenizer(cadena, "\n\r");
          aciertos = total = 0;
          while (lineas.hasMoreTokens()) {
            linea = lineas.nextToken();
            if (!(linea.startsWith("@"))) {
              tokens = new StringTokenizer(linea, " ");
              dato1 = tokens.nextToken();
              dato2 = tokens.nextToken();
              if (dato1.equalsIgnoreCase(dato2)) {
                aciertos++;
                total++;
              } else {
                total++;
              }
            }
          }
          accV[k] = (double) aciertos / (double) total;
          //	System.out.println(accV[k]);
          /*Reduction Computation*/

          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + "e0.txt");

          tokens = new StringTokenizer(cadena, "=\n\r");
          tokens.nextToken();
          dato1 = tokens.nextToken();
          redV[k] = Double.parseDouble(dato1.substring(1)) / 100.0;

          /*Kappa Computation*/
          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + ".tra");

          System.out.println("Result" + result);
          ;

          lineas = new StringTokenizer(cadena, "\n\r");
          aciertos = total = 0;
          valoresClase = new Vector<String>();
          while (lineas.hasMoreTokens()) {
            linea = lineas.nextToken();
            if (!(linea.startsWith("@"))) {
              tokens = new StringTokenizer(linea, " ");
              dato1 = tokens.nextToken();
              if (!valoresClase.contains(dato1)) {
                valoresClase.addElement(dato1);
              }
            }
          }
          confusionMatrix = new int[valoresClase.size()][valoresClase.size()];

          lineas = new StringTokenizer(cadena, "\n\r");

          total = 0;

          while (lineas.hasMoreTokens()) {

            linea = lineas.nextToken();

            if (!(linea.startsWith("@"))) {

              tokens = new StringTokenizer(linea, " ");

              dato1 = tokens.nextToken();

              dato2 = tokens.nextToken();

              try {

                confusionMatrix[valoresClase.indexOf(dato1)][valoresClase.indexOf(dato2)]++;

              } catch (ArrayIndexOutOfBoundsException e) {

                confusionMatrix[valoresClase.indexOf(dato1)][0]++;
              }

              total++;
            }
          }

          sumKappa = 0;

          for (l = 0; l < valoresClase.size(); l++) {

            sumKappa += confusionMatrix[l][l];
          }

          kappa = total * sumKappa;

          sumKappa = 0;

          for (l = 0; l < valoresClase.size(); l++) {

            sumi = 0;

            for (m = 0; m < valoresClase.size(); m++) {

              sumi += confusionMatrix[l][m];
            }

            sumj = 0;

            for (m = 0; m < valoresClase.size(); m++) {

              sumj += confusionMatrix[m][l];
            }

            sumKappa += sumi * sumj;
          }

          kappaV[k] = (double) (kappa - sumKappa) / (double) (total * total - sumKappa);

          // System.out.println(accV[k]);
        }

        acc = 0;

        for (l = 0; l < accV.length; l++) {

          acc += accV[l];
        }

        acc /= (double) accV.length;

        red = 0;

        for (l = 0; l < redV.length; l++) {

          red += redV[l];
        }

        red /= (double) redV.length;

        kappa = 0;

        for (l = 0; l < kappaV.length; l++) {

          kappa += kappaV[l];
        }

        kappa /= (double) kappaV.length;

        accSD = redSD = kapSD = 0;

        for (l = 0; l < accV.length; l++) {

          accSD += (acc - accV[l]) * (acc - accV[l]);
        }

        accSD = Math.sqrt(accSD / (double) accV.length);

        for (l = 0; l < redV.length; l++) {

          redSD += (red - redV[l]) * (red - redV[l]);
        }

        redSD = Math.sqrt(redSD / (double) redV.length);

        for (l = 0; l < kappaV.length; l++) {

          kapSD += (kappa - kappaV[l]) * (kappa - kappaV[l]);
        }

        kapSD = Math.sqrt(kapSD / (double) kappaV.length);

        /*Store the values in the main matrixes*/

        accuracyAv[j][i] = acc;
        accuracySD[j][i] = accSD;
        reductionAv[j][i] = red;
        reductionSD[j][i] = redSD;
        kappaAv[j][i] = kappa;
        kappaSD[j][i] = kapSD;
        accredAv[j][i] = acc * red;
        kapredAv[j][i] = kappa * red;

        // System.out.println("Acc =" +acc);

        /*Time processing*/

        /*
        for( k=0; k< 10 ;k++){
        	dato1 = tokensT.nextToken();
        	time[j][i] += Double.parseDouble(dato1) ;
        	runs[j][i]++;
        	//System.out.println(dato1);
        }*/
      }
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaAccuracyTRA.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena +=
            String.format("%6.4f", accuracyAv[i][j])
                + "\t"
                + String.format("%6.4f", accuracySD[i][j])
                + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaAccuracyTRA.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaReduction.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena +=
            String.format("%6.4f", reductionAv[i][j])
                + "\t"
                + String.format("%6.4f", reductionSD[i][j])
                + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaReduction.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaTime.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena += String.format("%6.4f", time[i][j] / (double) runs[i][j]) + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaTime.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaKappaTRA.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena +=
            String.format("%6.4f", kappaAv[i][j])
                + "\t"
                + String.format("%6.4f", kappaSD[i][j])
                + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaKappaTRA.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaAccRedTRA.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena += String.format("%6.4f", accredAv[i][j]) + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaAccRedTRA.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaKappaRedTRA.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena += String.format("%6.4f", kapredAv[i][j]) + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaKappaRedTRA.txt", cadena);
    }

    configAct = 0;
    /*Cálculo del accuracy, kappa y reducción en KNN (TST)*/
    for (j = 0; j < datasets.size(); j++) {

      for (i = 0; i < algoritmos.size(); i++) {
        alAct = (String) algoritmos.elementAt(i);
        // System.out.println("Processing algorithm: " + alAct);

        salAct = ((Integer) saltos.elementAt(j)).intValue();
        acc = red = kappa = 0.0;
        for (k = 0; k < 10; k++) {
          /*Accuracy Computation*/
          int result =
              (j + salAct) * algoritmos.size() * 10
                  + i * 10
                  + k; // Calculo el result correspondiente.
          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + ".tst");

          lineas = new StringTokenizer(cadena, "\n\r");
          aciertos = total = 0;
          while (lineas.hasMoreTokens()) {
            linea = lineas.nextToken();
            if (!(linea.startsWith("@"))) {
              tokens = new StringTokenizer(linea, " ");
              dato1 = tokens.nextToken();
              dato2 = tokens.nextToken();
              if (dato1.equalsIgnoreCase(dato2)) {
                aciertos++;
                total++;
              } else {
                total++;
              }
            }
          }
          accV[k] = (double) aciertos / (double) total;

          /*Reduction Computation*/
          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + "e0.txt");

          tokens = new StringTokenizer(cadena, "=\n\r");
          tokens.nextToken();
          dato1 = tokens.nextToken();
          redV[k] = Double.parseDouble(dato1.substring(1)) / 100.0;

          /*Kappa Computation*/
          cadena =
              Fichero.leeFichero(
                  "results//Clas-KNN//" + alAct + "//result" + Integer.toString(result) + ".tst");
          lineas = new StringTokenizer(cadena, "\n\r");
          aciertos = total = 0;
          valoresClase = new Vector<String>();
          while (lineas.hasMoreTokens()) {
            linea = lineas.nextToken();
            if (!(linea.startsWith("@"))) {
              tokens = new StringTokenizer(linea, " ");
              dato1 = tokens.nextToken();
              if (!valoresClase.contains(dato1)) {
                valoresClase.addElement(dato1);
              }
            }
          }
          confusionMatrix = new int[valoresClase.size()][valoresClase.size()];
          lineas = new StringTokenizer(cadena, "\n\r");
          total = 0;
          while (lineas.hasMoreTokens()) {
            linea = lineas.nextToken();
            if (!(linea.startsWith("@"))) {
              tokens = new StringTokenizer(linea, " ");
              dato1 = tokens.nextToken();
              dato2 = tokens.nextToken();
              try {
                confusionMatrix[valoresClase.indexOf(dato1)][valoresClase.indexOf(dato2)]++;
              } catch (ArrayIndexOutOfBoundsException e) {
                confusionMatrix[valoresClase.indexOf(dato1)][0]++;
              }
              total++;
            }
          }
          sumKappa = 0;
          for (l = 0; l < valoresClase.size(); l++) {
            sumKappa += confusionMatrix[l][l];
          }
          kappa = total * sumKappa;
          sumKappa = 0;
          for (l = 0; l < valoresClase.size(); l++) {
            sumi = 0;
            for (m = 0; m < valoresClase.size(); m++) {
              sumi += confusionMatrix[l][m];
            }
            sumj = 0;
            for (m = 0; m < valoresClase.size(); m++) {
              sumj += confusionMatrix[m][l];
            }
            sumKappa += sumi * sumj;
          }
          kappaV[k] = (double) (kappa - sumKappa) / (double) (total * total - sumKappa);
        }

        acc = 0;
        for (l = 0; l < accV.length; l++) {
          acc += accV[l];
        }
        acc /= (double) accV.length;
        red = 0;
        for (l = 0; l < redV.length; l++) {
          red += redV[l];
        }
        red /= (double) redV.length;
        kappa = 0;
        for (l = 0; l < kappaV.length; l++) {
          kappa += kappaV[l];
        }
        kappa /= (double) kappaV.length;

        accSD = redSD = kapSD = 0;
        for (l = 0; l < accV.length; l++) {
          accSD += (acc - accV[l]) * (acc - accV[l]);
        }
        accSD = Math.sqrt(accSD / (double) accV.length);
        for (l = 0; l < redV.length; l++) {
          redSD += (red - redV[l]) * (red - redV[l]);
        }
        redSD = Math.sqrt(redSD / (double) redV.length);
        for (l = 0; l < kappaV.length; l++) {
          kapSD += (kappa - kappaV[l]) * (kappa - kappaV[l]);
        }
        kapSD = Math.sqrt(kapSD / (double) kappaV.length);

        /*Store the values in the main matrixes*/
        accuracyAv[j][i] = acc;
        accuracySD[j][i] = accSD;
        reductionAv[j][i] = red;
        reductionSD[j][i] = redSD;
        kappaAv[j][i] = kappa;
        kappaSD[j][i] = kapSD;
        accredAv[j][i] = acc * red;
        kapredAv[j][i] = kappa * red;
      }
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaAccuracyTST.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena +=
            String.format("%6.4f", accuracyAv[i][j])
                + "\t"
                + String.format("%6.4f", accuracySD[i][j])
                + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaAccuracyTST.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaKappaTST.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena +=
            String.format("%6.4f", kappaAv[i][j])
                + "\t"
                + String.format("%6.4f", kappaSD[i][j])
                + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaKappaTST.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaAccRedTST.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena += String.format("%6.4f", accredAv[i][j]) + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaAccRedTST.txt", cadena);
    }

    /*Print the results*/
    cadena = "Datasets\t\t";
    for (i = 0; i < algoritmos.size(); i++) {
      cadena += algoritmos.elementAt(i) + "\t\t";
    }
    cadena += "\n";
    Fichero.escribeFichero("tablaKappaRedTST.txt", cadena);
    for (i = 0; i < datasets.size(); i++) {
      cadena = datasets.elementAt(i) + "\t\t";
      for (j = 0; j < algoritmos.size(); j++) {
        cadena += String.format("%6.4f", kapredAv[i][j]) + "\t";
      }
      cadena += "\n";
      Fichero.AnadirtoFichero("tablaKappaRedTST.txt", cadena);
    }

    System.out.println("FIN");
  }
Beispiel #18
0
  /** It launches the algorithm */
  public void execute() {

    int i, j, k, l;
    int t;
    int ele;
    double prob[];
    double aux;
    double NUmax = 1.5; // used for lineal ranking
    double NUmin = 0.5; // used for lineal ranking
    double pos1, pos2;
    int sel1, sel2;
    int data[][];
    int infoAttr[];
    int classData[];
    Vector<Rule> contenedor = new Vector<Rule>();
    Vector<Rule> conjR = new Vector<Rule>();
    Rule tmpRule;
    Condition tmpCondition[] = new Condition[1];
    RuleSet population[];
    RuleSet hijo1, hijo2;

    if (somethingWrong) { // We do not execute the program
      System.err.println("An error was found, the data-set has numerical values.");
      System.err.println("Aborting the program");
      // We should not use the statement: System.exit(-1);
    } else {
      Randomize.setSeed(seed);

      nClasses = train.getnClasses();

      /*Build the nominal data information*/
      infoAttr = new int[train.getnInputs()];
      for (i = 0; i < infoAttr.length; i++) {
        infoAttr[i] = train.numberValues(i);
      }

      data = new int[train.getnData()][train.getnInputs()];
      for (i = 0; i < data.length; i++) {
        for (j = 0; j < data[i].length; j++) {
          if (train.isMissing(i, j)) data[i][j] = -1;
          else data[i][j] = train.valueExample(i, j);
        }
      }

      classData = new int[train.getnData()];
      for (i = 0; i < classData.length; i++) {
        classData[i] = train.getOutputAsInteger(i);
      }

      /*Find first-order rules which result interesting*/

      for (i = 0; i < nClasses; i++) {
        for (j = 0; j < infoAttr.length; j++) {
          for (k = 0; k < infoAttr[j]; k++) {
            tmpCondition[0] = new Condition(j, k);
            tmpRule = new Rule(tmpCondition);
            if (Math.abs(computeAdjustedResidual(data, classData, tmpRule, i)) > 1.96) {
              if (!contenedor.contains(tmpRule)) {
                contenedor.add(tmpRule);
                conjR.add(tmpRule);
              }
            }
          }
        }
      }

      // Construct the Baker selection roulette
      prob = new double[popSize];
      for (j = 0; j < popSize; j++) {
        aux = (double) (NUmax - NUmin) * ((double) j / (popSize - 1));
        prob[j] = (double) (1.0 / (popSize)) * (NUmax - aux);
      }
      for (j = 1; j < popSize; j++) prob[j] = prob[j] + prob[j - 1];

      /*Steady-State Genetic Algorithm*/
      ele = 2;
      population = new RuleSet[popSize];
      while (conjR.size() >= 2) {
        t = 0;

        System.out.println("Producing rules of level " + ele);

        for (i = 0; i < population.length; i++) {
          population[i] = new RuleSet(conjR);
          population[i].computeFitness(data, classData, infoAttr, contenedor, nClasses);
        }

        Arrays.sort(population);

        while (t < numGenerations && !population[0].equals(population[popSize - 1])) {
          System.out.println("Generation " + t);
          t++;

          /*Baker's selection*/
          pos1 = Randomize.Rand();
          pos2 = Randomize.Rand();
          for (l = 0; l < popSize && prob[l] < pos1; l++) ;
          sel1 = l;
          for (l = 0; l < popSize && prob[l] < pos2; l++) ;
          sel2 = l;

          hijo1 = new RuleSet(population[sel1]);
          hijo2 = new RuleSet(population[sel2]);

          if (Randomize.Rand() < pCross) {
            RuleSet.crossover1(hijo1, hijo2);
          } else {
            RuleSet.crossover2(hijo1, hijo2);
          }

          RuleSet.mutation(hijo1, conjR, pMut, data, classData, infoAttr, contenedor, nClasses);
          RuleSet.mutation(hijo2, conjR, pMut, data, classData, infoAttr, contenedor, nClasses);

          hijo1.computeFitness(data, classData, infoAttr, contenedor, nClasses);
          hijo2.computeFitness(data, classData, infoAttr, contenedor, nClasses);

          population[popSize - 2] = new RuleSet(hijo1);
          population[popSize - 1] = new RuleSet(hijo2);

          Arrays.sort(population);
        }

        /*Decode function*/
        ele++;
        conjR.removeAllElements();
        System.out.println(
            "Fitness of the best chromosome in rule level " + ele + ": " + population[0].fitness);
        for (i = 0; i < population[0].getRuleSet().length; i++) {
          if (Math.abs(computeAdjustedResidual(data, classData, population[0].getRule(i), i))
              > 1.96) {
            if (validarRegla(population[0].getRule(i))
                && !contenedor.contains(population[0].getRule(i))) {
              contenedor.add(population[0].getRule(i));
              conjR.add(population[0].getRule(i));
            }
          }
        }
      }

      // Finally we should fill the training and test output files
      doOutput(this.val, this.outputTr, data, classData, infoAttr, contenedor, nClasses);
      doOutput(this.test, this.outputTst, data, classData, infoAttr, contenedor, nClasses);

      /*Print the rule obtained*/
      for (i = contenedor.size() - 1; i >= 0; i--) {
        if (reglaPositiva(
            this.train, data, classData, infoAttr, nClasses, contenedor.elementAt(i))) {
          Fichero.AnadirtoFichero(outputRule, contenedor.elementAt(i).toString(train));
          Fichero.AnadirtoFichero(
              outputRule,
              " -> "
                  + consecuente(
                      this.train, data, classData, infoAttr, nClasses, contenedor.elementAt(i))
                  + "\n");
        }
      }
      System.out.println("Algorithm Finished");
    }
  }
Beispiel #19
0
  protected static void escribeSalida(
      String nombreFichero,
      String instanciasIN[],
      String instanciasOUT[],
      Attribute entradas[],
      Attribute salida,
      int nEntradas,
      String relation) {

    String cadena = "";
    int i, j, k;
    int aux;

    /* Printing input attributes */
    cadena += "@relation " + relation + "\n";
    for (i = 0; i < nEntradas; i++) {
      cadena += "@attribute " + entradas[i].getName() + " ";
      if (entradas[i].getType() == Attribute.NOMINAL) {
        cadena += "{";
        for (j = 0; j < entradas[i].getNominalValuesList().size(); j++) {
          cadena += (String) entradas[i].getNominalValuesList().elementAt(j);
          if (j < entradas[i].getNominalValuesList().size() - 1) {
            cadena += ", ";
          }
        }
        cadena += "}\n";
      } else {
        if (entradas[i].getType() == Attribute.INTEGER) {
          cadena += "integer";
          cadena +=
              " ["
                  + String.valueOf((int) entradas[i].getMinAttribute())
                  + ", "
                  + String.valueOf((int) entradas[i].getMaxAttribute())
                  + "]\n";
        } else {
          cadena += "real";
          cadena +=
              " ["
                  + String.valueOf(entradas[i].getMinAttribute())
                  + ", "
                  + String.valueOf(entradas[i].getMaxAttribute())
                  + "]\n";
        }
      }
    }

    /* Printing output attribute */
    cadena += "@attribute " + salida.getName() + " ";
    if (salida.getType() == Attribute.NOMINAL) {
      cadena += "{";
      for (j = 0; j < salida.getNominalValuesList().size(); j++) {
        cadena += (String) salida.getNominalValuesList().elementAt(j);
        if (j < salida.getNominalValuesList().size() - 1) {
          cadena += ", ";
        }
      }
      cadena += "}\n";
    } else {
      cadena +=
          "integer ["
              + String.valueOf((int) salida.getMinAttribute())
              + ", "
              + String.valueOf((int) salida.getMaxAttribute())
              + "]\n";
    }

    /* Printing the data */
    cadena += "@data\n";

    Fichero.escribeFichero(nombreFichero, cadena);
    cadena = "";
    for (i = 0; i < instanciasIN.length; i++) {
      cadena += instanciasIN[i] + " " + instanciasOUT[i];

      cadena += "\n";
    }
    Fichero.AnadirtoFichero(nombreFichero, cadena);
  }
Beispiel #20
0
  public void run() {
    int i, j, k, etiqueta, pos;
    double pert_act, grado_act, ec, el, ec_tst, el_tst;

    /* We read the configutate file and we initialize the structures and variables */
    leer_conf();

    if (tabla.salir == false) {
      /* we generate the semantics of the linguistic variables */
      base_datos.Semantica();

      /* we store the DB in the report file */
      informe = "\n\nInitial Data Base: \n\n";
      for (i = 0; i < tabla.n_variables; i++) {
        informe += "  Variable " + (i + 1) + ":\n";
        for (j = 0; j < base_datos.n_etiquetas[i]; j++) {
          informe +=
              "    Label "
                  + (j + 1)
                  + ": ("
                  + base_datos.BaseDatos[i][j].x0
                  + ","
                  + base_datos.BaseDatos[i][j].x1
                  + ","
                  + base_datos.BaseDatos[i][j].x3
                  + ")\n";
        }

        informe += "\n";
      }

      informe += "\n";
      Fichero.escribeFichero(fichero_inf, informe);

      /* Inicialization of the counter of uncovered examples */
      base_reglas.n_reglas = 0;

      /* Iterative Rule Learning */
      for (i = 0; i < tabla.long_tabla; i++) {
        /* Generation of the best rule for the current example */
        for (j = 0; j < tabla.n_variables; j++) {

          /* Determination of the best label for each variable */
          grado_pertenencia[j] = 0.0;
          etiqueta = 0;

          for (k = 0; k < base_datos.n_etiquetas[j]; k++) {
            pert_act = base_reglas.Fuzzifica(tabla.datos[i].ejemplo[j], base_datos.BaseDatos[j][k]);
            if (pert_act > grado_pertenencia[j]) {
              grado_pertenencia[j] = pert_act;
              etiqueta = k;
            }
          }

          Regla_act[j] = etiqueta;
        }

        /* we calculate the covered degree */
        grado_act = 1.0;
        for (j = 0; j < tabla.n_variables; j++) {
          grado_act *= grado_pertenencia[j];
        }

        /* we insert the new rule in the RB */
        pos = Pertenece(Regla_act, Conjunto_Reglas, base_reglas.n_reglas);

        /* if the rule didn't exist */
        if (pos == -1) {
          for (j = 0; j < tabla.n_variables; j++) {
            Conjunto_Reglas[base_reglas.n_reglas].Regla[j] = Regla_act[j];
          }
          Conjunto_Reglas[base_reglas.n_reglas].grado = grado_act;
          base_reglas.n_reglas++;
        }

        /* if a rule with equal antecedet exist in the RB and the covered degree of the current rule is better, the consequent is replaced */
        else if (Conjunto_Reglas[pos].grado < grado_act) {
          Conjunto_Reglas[pos].grado = grado_act;
          if (Conjunto_Reglas[pos].Regla[tabla.n_var_estado] != Regla_act[tabla.n_var_estado]) {
            Conjunto_Reglas[pos].Regla[tabla.n_var_estado] = Regla_act[tabla.n_var_estado];
          }
        }
      }

      /* we decode the generated rules */
      base_reglas.decodifica(Conjunto_Reglas);

      /* we calcule the MSEs */
      fun_adap.Error_tra();
      ec = fun_adap.EC;
      el = fun_adap.EL;

      fun_adap.Error_tst();
      ec_tst = fun_adap.EC;
      el_tst = fun_adap.EL;

      /* we write the RB */
      cadenaReglas = base_reglas.BRtoString(peso);
      cadenaReglas += "\nECMtra: " + ec + " ECMtst: " + ec_tst + "\n";

      Fichero.escribeFichero(fichero_reglas, cadenaReglas);

      /* we write the obligatory output files*/
      String salida_tra = tabla.getCabecera();
      salida_tra += fun_adap.getSalidaObli(tabla);
      Fichero.escribeFichero(fich_tra_obli, salida_tra);

      String salida_tst = tabla_tst.getCabecera();
      salida_tst += fun_adap.getSalidaObli(tabla_tst);
      Fichero.escribeFichero(fich_tst_obli, salida_tst);

      /* we write the MSEs in specific files */
      Fichero.AnadirtoFichero(ruta_salida + "WMcomunR.txt", "" + base_reglas.n_reglas + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "WMcomunTRA.txt", "" + ec + "\n");
      Fichero.AnadirtoFichero(ruta_salida + "WMcomunTST.txt", "" + ec_tst + "\n");
    }
  }