Ejemplo n.º 1
0
  /** Creates the total selector's set for get all the possible rules */
  private Complejo hazSelectores(Dataset train) {

    Complejo almacenSelectores;
    int nClases = train.getnclases();
    almacenSelectores =
        new Complejo(nClases); // Aqui voy a almacenar los selectores (numVariable,operador,valor)
    Attribute[] atributos = null;
    int num_atributos, type;
    Vector nominalValues;
    atributos = Attributes.getAttributes();
    num_atributos = Attributes.getNumAttributes();
    Selector s;

    for (int i = 0; i < train.getnentradas(); i++) {
      type = atributos[i].getType();
      switch (type) {
        case 0: // NOMINAL
          nominalValues = atributos[i].getNominalValuesList();
          // System.out.print("{");
          for (int j = 0; j < nominalValues.size(); j++) {
            // System.out.print ((String)nominalValues.elementAt(j)+"  ");
            s = new Selector(i, 0, (String) nominalValues.elementAt(j), true); // [atr,op,valor]
            // incluimos tb los valores en double para facilitar algunas funciones
            s.setValor((double) j);
            almacenSelectores.addSelector(s);
            // s.print();
          }
          // System.out.println("}");
          break;
      }
      // System.out.println(num_atributos);
    }
    return almacenSelectores;
  }
Ejemplo n.º 2
0
  /**
   * Prints on the standard output the content of this complex object. (List -> Attribute operator
   * value)
   */
  public void print(int nominal) {
    for (int x = 0; x < compl.size(); x++) {
      Selector s = (Selector) compl.get(x);

      double[] values = s.getValues();
      String[] nValues = s.getNValues();

      // System.out.print("(Atr" + s.getAtributo() + " ");
      System.out.print("(" + attributeNames[s.getAttribute()] + " ");

      switch (s.getOperator()) {
        case 0:
          if (values.length > 1 /*|| valoresN.length>1*/) System.out.print("in");
          else System.out.print("=");
          break;
        case 1:
          System.out.print("<>");
          break;
        case 2:
          System.out.print("<=");
          break;
        default:
          System.out.print(">");
      }

      if (nominal == 0) { // el atributo es nominal
        if (nValues.length > 1) {
          System.out.print(" " + nValues[0]);
          for (int i = 1; i < nValues.length - 1; i++) {
            System.out.print(" " + nValues[i]);
          }
          System.out.print(" " + nValues[nValues.length - 1] + ")");
        } else {
          System.out.print(" " + nValues[0] + ")");
        }
      } else {
        if (values.length > 1) {
          System.out.print(" [" + values[0]);
          for (int i = 1; i < values.length - 1; i++) {
            System.out.print(" " + values[i]);
          }
          System.out.print(" " + values[values.length - 1] + "])");
        } else {
          System.out.print(" " + values[0] + ")");
        }
      }

      if (x < compl.size() - 1) {
        System.out.print(" AND ");
      }
      // System.out.print(" -- "+heuristica+" -- ");
      System.out.println();
    }
  }
Ejemplo n.º 3
0
 /**
  * Remove the selectors from the list of the selectors that have the parameter attribute o
  *
  * @param attribute the attribute
  */
 public void removeSelectorAttribute(int attribute) {
   Selector s;
   int atrib;
   for (int i = 0; i < compl.size(); i++) {
     s = (Selector) compl.get(i);
     atrib = s.getAttribute();
     if (atrib == attribute) {
       compl.remove(s);
       /*CUIDADO!!!hay q volver al indice anterior pq se ha eliminado un elemento!!*/
       i = i - 1;
     }
   }
 }
Ejemplo n.º 4
0
  /**
   * Prints as a String the complex content (List->Attribute)
   *
   * @return a String the complex content
   */
  public String printString(int[] numValues) {

    String cad = "";
    for (int x = 0; x < compl.size(); x++) {
      Selector s = (Selector) compl.get(x);
      // cad += "Atr" + s.getAtributo() + " ";
      double[] values = s.getValues();
      String[] nValues = s.getNValues();
      // si para un atributo aparecen todos sus valores, la condicion es true
      // no imprimimos condicion
      if (values.length < numValues[s.getAttribute()]) {

        if ((x < (compl.size())) && (x > 0)) {
          cad += " AND ";
        }
        cad += attributeNames[s.getAttribute()] + " ";

        switch (s.getOperator()) {
          case 0:
            if (values.length > 1) cad += "in";
            else cad += "=";
            break;
          case 1:
            cad += "<>";
            break;
          case 2:
            cad += "<=";
            break;
          case 3:
            cad += ">";
            break;
        }

        if (Attributes.getInputAttribute(s.getAttribute()).getType() == Attribute.NOMINAL) {
          if (nValues.length > 1) {
            cad += " [" + nValues[0];
            for (int i = 1; i < nValues.length - 1; i++) {
              cad += " , " + nValues[i];
            }
            cad += " , " + nValues[nValues.length - 1] + "] ";
          } else {
            cad += " " + nValues[0] + "";
          }
        } else {
          if (values.length > 1) {
            cad += " [" + values[0];
            for (int i = 1; i < values.length - 1; i++) {
              cad += " , " + values[i];
            }
            cad += " , " + values[values.length - 1] + "]";
          } else {
            cad += " " + values[0] + "";
          }
        }
      }
    }
    return cad;
  }
Ejemplo n.º 5
0
  /**
   * Checks if the rule gets the parameter instance
   *
   * @param instance the instance
   * @return boolean True if the rule gets the instance
   */
  public boolean instanceCoveredByRule(Instance instance) {
    boolean bCovered = true;
    double cadena;
    for (int i = 0; i < this.size() && bCovered; i++) {
      Selector s = this.getSelector(i);
      switch (s.getOperator()) {
        case 0: // se trata del igual
          double[] valor = s.getValues();
          bCovered = false;
          for (int j = 0; (j < valor.length) && (!bCovered); j++) {
            cadena = instance.getInputRealValues(s.getAttribute());

            if (cadena == valor[j]) bCovered = true;
            else bCovered = false;
            /*int numInputAttributes  = Attributes.getInputNumAttributes();
            int numOutputAttributes = Attributes.getOutputNumAttributes();
            int numUndefinedAttributes = Attributes.getNumAttributes();*/
          }
          break;
      }
    }
    return bCovered;
  }
Ejemplo n.º 6
0
  /**
   * Constructor with all the attributes to initialize
   *
   * @param ficheroTrain Train file
   * @param ficheroTest Test file
   * @param fSalidaTr Out-put train file
   * @param fSalidaTst Out-put test file
   * @param fsalida Out-put file
   * @param semilla seed
   */
  public Prism(
      String ficheroTrain,
      String ficheroTest,
      String fSalidaTr,
      String fSalidaTst,
      String fsalida,
      long semilla) {

    ficheroSalida = fsalida;
    ficheroSalidaTr = fSalidaTr;
    ficheroSalidaTst = fSalidaTst;
    seed = semilla;

    datosTrain = new ConjDatos(); // datosEval = new ConjDatos();
    datosTest = new ConjDatos();

    train = new Dataset();
    test = new Dataset();
    s = new Selector(0, 0, 0.);
    conjunto_reglas = new ConjReglas();

    try {
      Randomize.setSeed(seed);
      System.out.println("la semilla es " + seed);
      train.leeConjunto(ficheroTrain, true);
      test.leeConjunto(ficheroTest, false); //
      if (train.hayAtributosContinuos() /*|| train.hayAtributosDiscretos()*/) {
        System.err.println("\nPrism may not work properly with real or integer attributes.\n");
        // System.exit(-1);
        hayContinuos = true;
      }
      if (!hayContinuos) {
        train.calculaMasComunes(); // eval.calculaMasComunes();
        test.calculaMasComunes();
        datosTrain =
            creaConjunto(
                train); // Leemos los datos de entrenamiento (todos seguidos como un
                        // String)//datosEval = creaConjunto(eval);
        datosTest = creaConjunto(test);

        valores = train.getX2(); // obtengo los valores nominales
        clases = train.getC2();
        clasitas = train.getC();
        /*System.out.println(train.getndatos());
        System.out.println(train.getnentradas());
        for(int i=0;i<train.getndatos();i++){
        	for(int j=0;j<train.getnentradas();j++)
        		System.out.print(valores[i][j]);
        	System.out.print(clases[i]);System.out.println(clasitas[i]);}*/
        // COMENZAMOS EL ALGORITMO PRISM
        // FOR EACH CLASS C
        clases = train.dameClases();
        int unavez = 0, candidato;
        for (int i = 0; i < train.getnclases(); i++) {
          System.out.println("CLASE :" + clases[i] + "\n");
          // initialize E to the instance set
          /*Cuando haya que inicializar de nuevo el conjunto de instancias no es necesario insertar aquellas que se eliminaron, sino que nos va a bastar con inicializar otra vez el conjunto mediante el fichero de entrenamiento. Por eso hay un metodo para insertar una instancia*/
          train.leeConjunto(ficheroTrain, false);
          nombre_atributos = train.dameNombres();
          instancias = train.getInstanceSet();

          // While E contains instances in class C
          while (train.hayInstanciasDeClaseC(i)) {
            // Create a rule R with an empty left-hand side that predicts class C
            regla = new Complejo(train.getnclases());
            regla.setClase(i);
            regla.adjuntaNombreAtributos(nombre_atributos);
            // esto lo hacemos solo aqui pq luego vamos quitando selectores del almacen
            almacen = hazSelectores(train);
            almacen.adjuntaNombreAtributos(nombre_atributos);
            do {
              // FOR EACH ATTRIBUTE A NOT MENTIONED IN R, AND EACH VALUE V
              accuracy_ant = -1.;
              p = 0;
              int seleccionados[] = new int[almacen.size()];
              for (int jj = 0; jj < almacen.size(); jj++) seleccionados[jj] = 0;
              System.out.println();
              for (int j = 0; j < almacen.size(); j++) {
                // tenemos que quitar el selector anterior
                if (j > 0) regla.removeSelector(s);
                s = almacen.getSelector(j);
                // if(i==0)
                s.print();
                // CONSIDER ADDING THE CONDITION A=V TO THE LHS OF R
                regla.addSelector(s);
                accuracy = getAccuracy(i);
                // if(i==0)	{
                System.out.println("correctas " + num_correctas + " cubiertas " + num_cubiertas);
                System.out.println("Acurracy " + accuracy);
                // }

                if ((accuracy > accuracy_ant)
                    || ((accuracy == accuracy_ant) && (num_correctas > p))) {

                  // if((accuracy==accuracy_ant) &&(num_correctas>p)){
                  // System.out.println("atn "+accuracy_ant);
                  // System.out.println("ahora "+accuracy);
                  accuracy_ant = accuracy;
                  seleccionado = j;
                  p = num_correctas;

                  // si se encuentra un superior hay que quitar
                  // todo lo q se hay ido almacenando en esta iteracion
                  for (int jj = 0; jj < almacen.size(); jj++) seleccionados[jj] = 0;
                  // }
                } else {
                  if ((accuracy == accuracy_ant) && (num_correctas == p)) {
                    seleccionados[seleccionado] = 1;
                    seleccionados[j] = 1;
                  }
                }
              }
              // seleccionamos uno de los seleccionados en el caso de empate
              int contador = 0;
              for (int jj = 0; jj < almacen.size(); jj++) {
                if (seleccionados[jj] == 1) {
                  contador++;
                  System.out.println("OPCION " + jj);
                }
              }
              if (contador > 0) {
                candidato = Randomize.RandintClosed(1, contador);
                contador = 0;
                for (int jj = 0; jj < almacen.size(); jj++) {
                  if (seleccionados[jj] == 1) {
                    contador++;
                    if (contador == candidato) seleccionado = jj;
                  }
                }
              }
              System.out.println("ELEGIDO " + seleccionado);

              // antes hay que quitar el q metimos
              regla.removeSelector(s);
              s = almacen.getSelector(seleccionado);
              s.print();
              // ADD A=V TO R
              regla.addSelector(s);
              /*AHORA HAY QUE QUITAR DEL ALMACEN SE SELECTORES AQUELLOS QUE
              HACEN REFERENCIA AL ATRIBUTO SELECCIONADO*/
              // obtener el atributo del selector ganador
              atributo = s.getAtributo();
              // se borran todos los q tengan ese atributo
              // System.out.println("ALMACEN");almacen.print();
              almacen.removeSelectorAtributo(atributo);

              reglaPerfecta = perfectRule(regla, train);
            } while (!reglaPerfecta && (regla.size() < train.getnentradas()));

            System.out.println("\n");
            System.out.println("\nREGLA............................................");
            regla.print();
            System.out.println("\n");
            /*necesitamos evaluar la regla para obtener la salida del metodo
            para compararla con la salida esperada*/
            evaluarComplejo(regla, datosTrain);
            // INCLUIMOS ESTA REGLA YA PARA EL CONJUNTO FINAL DE REGLAS
            conjunto_reglas.addRegla(regla);
            // REMOVE THE INSTANCES COVERED BY R FROM E

            // Instance instancia;
            /*for(int k=0;k<instancias.getNumInstances();k++){
            instancia=instancias.getInstance(k);
            System.out.print(k+" ");
              	instancia.print();
            System.out.println();
              	}*/
            removeInstancesCovered(i);
            for (int k = 0; k < instancias.getNumInstances(); k++) {
              instancia = instancias.getInstance(k);
              clase = instancia.getOutputNominalValuesInt(0);
              if (clase == i) {
                System.out.print(k + " ");
                instancia.print();
                System.out.println();
              }
            }
            // instancias.print();
            System.out.println("\n");
          } // del while
        } // del for de las clases

        // EVALUAMOS LA CALIDAD DE LAS REGLAS
        int[] clasesEval;
        clasesEval = train.getC();
        muestPorClaseEval = new int[train.getnclases()];
        for (int j = 0; j < train.getnclases(); j++) {
          muestPorClaseEval[j] = 0;
          for (int i = 0; i < datosTrain.size(); i++) {
            if (
            /*valorClases[j]*/ j == clasesEval[i]) {
              muestPorClaseEval[j]++;
            }
          }
        }
        conjunto_reglas.eliminaRepetidos(1);
        evReg =
            new EvaluaCalidadReglas(
                conjunto_reglas,
                datosTrain,
                datosTest,
                muestPorClaseEval,
                muestPorClaseEval,
                clases);
        // GENERAMOS LA SALIDA
        generaSalida();
        System.out.println("la semilla es " + seed);
      } // del if
    } catch (IOException e) {
      System.err.println("There was a problem while trying to read the dataset files:");
      System.err.println("-> " + e);
      // System.exit(0);
    }
  }
Ejemplo n.º 7
0
 /**
  * Check if the complex gets the given data
  *
  * @param m Muestra The example
  * @return boolean True if gets the example
  */
 public boolean isCovered(Sample m) {
   boolean cubierto = true;
   double[] sample = m.getSample();
   for (int i = 0; i < this.size() && cubierto; i++) { // recorremos los selectores del complejo
     Selector s = this.getSelector(i);
     switch (s.getOperator()) {
       case 0: // se trata del igual
         double[] valor = s.getValues();
         cubierto = false;
         // ahora cada selector solo guarda el minimo y maximo
         // para cuando se trata de una excepcion
         if (valor.length == 1) {
           if (sample[s.getAttribute()] == valor[0]) cubierto = true;
         }
         // ahora ya sabemos que valor solo va a tener 2 componentes
         else {
           if ((sample[s.getAttribute()] >= valor[0]) && (sample[s.getAttribute()] <= valor[1]))
             cubierto = true;
         }
         break;
       case 1: // se trata del distinto
         cubierto = sample[s.getAttribute()] != s.getZeroValue();
         break;
       case 2: // menor o igual
         cubierto = sample[s.getAttribute()] <= s.getZeroValue();
         break;
       case 3: // mayor
         cubierto = sample[s.getAttribute()] > s.getZeroValue();
         break;
     }
   }
   return cubierto;
 }