Example usage for weka.core Instances classAttribute

List of usage examples for weka.core Instances classAttribute

Introduction

In this page you can find the example usage for weka.core Instances classAttribute.

Prototype


publicAttribute classAttribute() 

Source Link

Document

Returns the class attribute.

Usage

From source file:edu.oregonstate.eecs.mcplan.domains.frogger.FroggerRepresentationConverter.java

License:Open Source License

public static Instances absoluteToRelative(final FroggerParameters params, final Instances src,
        final int vision) {
    final ArrayList<Attribute> attributes = new ArrayList<Attribute>();
    attributes.add(new Attribute("x"));
    attributes.add(new Attribute("y"));
    for (int i = vision; i >= -vision; --i) {
        for (int j = -vision; j <= vision; ++j) {
            if (i == 0 && j == 0) {
                continue;
            }/*from  w  w  w.j  a  va  2  s  .c om*/

            final String name = "car_x" + (j >= 0 ? "+" : "") + j + "_y" + (i >= 0 ? "+" : "") + i;
            attributes.add(new Attribute(name));
        }
    }
    attributes.add(src.classAttribute());

    final Instances dest = new Instances(src.relationName() + "_relative", attributes, src.size());
    for (final Instance inst : src) {
        final double[] phi = new double[attributes.size()];
        int idx = 0;

        final int x = (int) inst.value(0);
        final int y = (int) inst.value(1);
        phi[idx++] = x;
        phi[idx++] = y;

        for (int i = vision; i >= -vision; --i) {
            for (int j = -vision; j <= vision; ++j) {
                if (i == 0 && j == 0) {
                    continue;
                }

                final int xoff = x + j;
                final int yoff = y + i;

                if (xoff >= 0 && xoff < params.road_length && yoff >= 1 && yoff <= params.lanes) {
                    final int car = (int) inst.value(2 + (yoff - 1) * params.road_length + xoff);
                    phi[idx] = car; // s.grid[dy][dx] == Tile.Car ? 1.0 : 0.0; // fv[2 + (dy-1)*road_length + dx]
                }
                idx += 1;
            }
        }

        phi[idx++] = inst.classValue();
        assert (idx == phi.length);

        WekaUtil.addInstance(dest, new DenseInstance(inst.weight(), phi));
    }

    return dest;
}

From source file:edu.uga.cs.fluxbuster.classification.Classifier.java

License:Open Source License

/**
 * Executes the classifier./*from ww w.j a v  a  2s  .  com*/
 * 
 * @param prepfeatures the prepared features in arff format
 * @param modelfile the path to the serialized model
 * @param clusters the clusters to classify
 * @return a map of the classified clusters, the keys are the classes
 *       and the values are lists of cluster id's belonging to those classes
 */
private Map<ClusterClass, List<StoredDomainCluster>> executeClassifier(String prepfeatures, String modelfile,
        List<StoredDomainCluster> clusters) {
    Map<ClusterClass, List<StoredDomainCluster>> retval = new HashMap<ClusterClass, List<StoredDomainCluster>>();
    try {
        DataSource source = new DataSource(new ByteArrayInputStream(prepfeatures.getBytes()));
        Instances data = source.getDataSet();
        if (data.classIndex() == -1) {
            data.setClassIndex(data.numAttributes() - 1);
        }
        String[] options = weka.core.Utils.splitOptions("-p 0");
        J48 cls = (J48) weka.core.SerializationHelper.read(modelfile);
        cls.setOptions(options);
        for (int i = 0; i < data.numInstances(); i++) {
            double pred = cls.classifyInstance(data.instance(i));
            ClusterClass clusClass = ClusterClass
                    .valueOf(data.classAttribute().value((int) pred).toUpperCase());
            if (!retval.containsKey(clusClass)) {
                retval.put(clusClass, new ArrayList<StoredDomainCluster>());
            }
            retval.get(clusClass).add(clusters.get(i));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error executing classifier.", e);
        }
    }
    return retval;
}

From source file:edu.umbc.cs.maple.utils.WekaUtils.java

License:Open Source License

/** Converts the instances in the given dataset to binary, setting the specified labels to positive.
 * Note this method is destructive to data, directly modifying its contents.
 * @param data the multiclass dataset to be converted to binary.
 * @param positiveClassValue the class value to treat as positive.
 *//*from   ww  w . j  a v a2  s. co  m*/
public static void convertMulticlassToBinary(Instances data, String positiveClassValue) {

    // ensure that data is nominal
    if (!data.classAttribute().isNominal())
        throw new IllegalArgumentException("Instances must have a nominal class.");

    // create the new class attribute
    FastVector newClasses = new FastVector(2);
    newClasses.addElement("Y");
    newClasses.addElement("N");
    Attribute newClassAttribute = new Attribute("class", newClasses);

    // alter the class attribute to be binary
    int newClassAttIdx = data.classIndex();
    data.insertAttributeAt(newClassAttribute, newClassAttIdx);
    int classAttIdx = data.classIndex();

    // set the instances classes to be binary, with the labels [Y,N] (indices 0 and 1 respectively)
    int numInstances = data.numInstances();
    for (int instIdx = 0; instIdx < numInstances; instIdx++) {
        Instance inst = data.instance(instIdx);
        if (inst.stringValue(classAttIdx).equals(positiveClassValue)) {
            inst.setValue(newClassAttIdx, 0); // set it to the first class, which will be Y
        } else {
            inst.setValue(newClassAttIdx, 1); // set it to the second class, which will be 0
        }
    }

    // switch the class index to the new class and delete the old class
    data.setClassIndex(newClassAttIdx);
    data.deleteAttributeAt(classAttIdx);

    // alter the dataset name
    data.setRelationName(data.relationName() + "-" + positiveClassValue);
}

From source file:fantail.core.Tools.java

License:Open Source License

public static boolean isClassAttributeRelational(Instances data) throws Exception {
    if (data == null) {
        throw new Exception("data can't be null.");
    }/* w  w  w . j  a v a  2 s  . co m*/
    return data.classAttribute().isRelationValued();
}

From source file:fantail.core.Tools.java

License:Open Source License

public static Instances loadFantailARFFInstances(String arffPath) throws Exception {
    ArffLoader loader = new ArffLoader();
    loader.setSource(new File(arffPath));
    Instances data = loader.getDataSet();
    data.setClassIndex(data.numAttributes() - 1);
    if (data.classAttribute().isRelationValued() != true) {
        throw new Exception("The last attribute needs to be 'RelationValued'");
    }//from w  w w.j a  v  a 2 s  . c o  m
    return data;
}

From source file:ffnn.MultilayerPerceptron.java

License:Open Source License

/**
 * This function sets what the m_numeric flag to represent the passed class it
 * also performs the normalization of the attributes if applicable and sets up
 * the info to normalize the class. (note that regardless of the options it
 * will fill an array with the range and base, set to normalize all attributes
 * and the class to be between -1 and 1)
 * //from  w ww.j a  v a  2s  . c  o  m
 * @param inst the instances.
 * @return The modified instances. This needs to be done. If the attributes
 *         are normalized then deep copies will be made of all the instances
 *         which will need to be passed back out.
 */
private Instances setClassType(Instances inst) throws Exception {
    if (inst != null) {
        // x bounds
        m_attributeRanges = new double[inst.numAttributes()];
        m_attributeBases = new double[inst.numAttributes()];
        for (int noa = 0; noa < inst.numAttributes(); noa++) {
            double min = Double.POSITIVE_INFINITY;
            double max = Double.NEGATIVE_INFINITY;
            for (int i = 0; i < inst.numInstances(); i++) {
                if (!inst.instance(i).isMissing(noa)) {
                    double value = inst.instance(i).value(noa);
                    if (value < min) {
                        min = value;
                    }
                    if (value > max) {
                        max = value;
                    }
                }
            }
            m_attributeRanges[noa] = (max - min) / 2;
            m_attributeBases[noa] = (max + min) / 2;
        }

        if (m_normalizeAttributes) {
            for (int i = 0; i < inst.numInstances(); i++) {
                Instance currentInstance = inst.instance(i);
                double[] instance = new double[inst.numAttributes()];
                for (int noa = 0; noa < inst.numAttributes(); noa++) {
                    if (noa != inst.classIndex()) {
                        if (m_attributeRanges[noa] != 0) {
                            instance[noa] = (currentInstance.value(noa) - m_attributeBases[noa])
                                    / m_attributeRanges[noa];
                        } else {
                            instance[noa] = currentInstance.value(noa) - m_attributeBases[noa];
                        }
                    } else {
                        instance[noa] = currentInstance.value(noa);
                    }
                }
                inst.set(i, new DenseInstance(currentInstance.weight(), instance));
            }
        }

        if (inst.classAttribute().isNumeric()) {
            m_numeric = true;
        } else {
            m_numeric = false;
        }
    }
    return inst;
}

From source file:FinalMineria.Reconocimiento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w . j  a v  a  2  s.  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {

    String accion = request.getParameter("accion");
    BufferedReader br = null;
    String ruta = request.getServletContext().getRealPath("/Recursos");
    br = new BufferedReader(new FileReader(ruta + "/nombres.txt"));
    linea = br.readLine();
    br.close();
    if ("Detener".equals(accion)) {
        grabar.finish();
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ex) {
            Logger.getLogger(GrabarAudio.class.getName()).log(Level.SEVERE, null, ex);
        }
        String comando = "cmd /c " + request.getServletContext().getRealPath("/Recursos/OpenSmile")
                + "\\SMILExtract_Release.exe -C " + request.getServletContext().getRealPath("/Recursos/config")
                + "\\IS12_speaker_trait.conf -I " + request.getServletContext().getRealPath("/Recursos/audios")
                + "\\prueba.wav -O " + request.getServletContext().getRealPath("/Recursos/arff")
                + "\\prueba.arff -classes {" + linea + "} -classlabel ?";
        Process proceso = Runtime.getRuntime().exec(comando);
        proceso.waitFor();
        Instances prueba, conocimiento;
        try (BufferedReader archivoBase = new BufferedReader(new FileReader(
                request.getServletContext().getRealPath("/Recursos/arff") + "\\baseDatos.arff"))) {
            conocimiento = new Instances(archivoBase);
        }
        try (BufferedReader archivoPrueba = new BufferedReader(
                new FileReader(request.getServletContext().getRealPath("/Recursos/arff") + "\\prueba.arff"))) {
            prueba = new Instances(archivoPrueba);
        }

        conocimiento.deleteStringAttributes();
        conocimiento.setClassIndex(981);
        prueba.deleteStringAttributes();
        prueba.setClassIndex(981);
        Classifier clasificadorModelo = (Classifier) new NaiveBayes();
        clasificadorModelo.buildClassifier(conocimiento);
        double valorP = clasificadorModelo.classifyInstance(prueba.instance(prueba.numInstances() - 1));
        String prediccion = prueba.classAttribute().value((int) valorP);
        System.out.println(prediccion);
        request.setAttribute("prediccion", prediccion);
        RequestDispatcher dispatcher = request.getRequestDispatcher("./Hablante.jsp");
        dispatcher.forward(request, response);
    } else if ("Grabar".equals(accion)) {
        ruta = request.getServletContext().getRealPath("/Recursos/audios");
        grabar = new Grabador(ruta + "\\" + "prueba");
        Thread stopper = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(tiempo);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                grabar.finish();
            }
        });

        stopper.start();

        // start recording
        grabar.start();
        response.sendRedirect("./grabar.jsp");
    }
}

From source file:gate.plugin.learningframework.data.CorpusRepresentationWeka.java

public static weka.core.Instance wekaInstanceFromMalletInstance(Instances wekaDataset,
        cc.mallet.types.Instance malletInstance) {
    FeatureVector fv = (FeatureVector) malletInstance.getData();
    int size = fv.numLocations();
    int wekaTargetIndex = wekaDataset.classIndex();
    // TODO: for now we just directly copy over the mallet values to the weka values
    // We may need to handle certain cases with missing values separately!

    // create  the arrays with one more entry which will be the target, if we have a target

    //int indices[] = haveTarget ? new int[size + 1] : new int[size];
    // experimental change: always allocate the space for the class attribute! 
    // We do this because Weka Random Forest threw an exception and complained about a missing
    // class. //from ww w.jav a2 s .c  o m
    int indices[] = new int[size + 1];
    double values[] = new double[size + 1];
    for (int i = 0; i < size; i++) {
        indices[i] = fv.indexAtLocation(i);
        values[i] = fv.valueAtLocation(i);
    }
    // now set the target, if we have one 
    Object malletValue = malletInstance.getTarget();
    if (malletValue != null) { // we do have a target value, could be a class label or a numeric value
        indices[size] = wekaTargetIndex;
        // if we have a target alphabet, convert the label to a class index, otherwise expect
        // a double value directly
        if (malletInstance.getTargetAlphabet() == null) {
            values[size] = (double) malletInstance.getTarget();
        } else {
            LabelAlphabet la = (LabelAlphabet) malletInstance.getTargetAlphabet();
            Label malletLabel = (Label) malletInstance.getTarget();
            int targetIndex = malletLabel.getIndex();
            String targetString = malletLabel.toString();
            int wekaIndex = wekaDataset.classAttribute().indexOfValue(targetString);
            values[size] = (double) wekaIndex;
            if (targetIndex != wekaIndex) {
                System.err.println("DEBUG ASSERTION FAILED: malletIndex for target is not equal to wekaIndex");
            }
        }
    } else { // we do not have a target value, so lets create a missing value target for weka
        indices[size] = wekaDataset.classIndex();
        values[size] = Double.NaN;
    }
    weka.core.SparseInstance wekaInstance = new weka.core.SparseInstance(1.0, values, indices, values.length);
    // TODO: is this necessary, is this useful?
    // What does this actually do? Hopefully not actually add or modify anything in the wekaDataset
    // and just give the instance a chance to know about the attributes?
    wekaInstance.setDataset(wekaDataset);
    return wekaInstance;
}

From source file:GClass.EvaluationInternal.java

License:Open Source License

/**
 * Initializes all the counters for the evaluation and also takes a
 * cost matrix as parameter./*from www  . j  a v a2  s  . co  m*/
 *
 * @param data set of instances, to get some header information
 * @param costMatrix the cost matrix---if null, default costs will be used
 * @exception Exception if cost matrix is not compatible with
 * data, the class is not defined or the class is numeric
 */
public EvaluationInternal(Instances data, CostMatrix costMatrix) throws Exception {

    m_NumClasses = data.numClasses();
    m_NumFolds = 1;
    m_ClassIsNominal = data.classAttribute().isNominal();

    if (m_ClassIsNominal) {
        m_ConfusionMatrix = new double[m_NumClasses][m_NumClasses];
        m_ClassNames = new String[m_NumClasses];
        for (int i = 0; i < m_NumClasses; i++) {
            m_ClassNames[i] = data.classAttribute().value(i);
        }
    }
    m_CostMatrix = costMatrix;
    if (m_CostMatrix != null) {
        if (!m_ClassIsNominal) {
            throw new Exception("Class has to be nominal if cost matrix " + "given!");
        }
        if (m_CostMatrix.size() != m_NumClasses) {
            throw new Exception("Cost matrix not compatible with data!");
        }
    }
    m_ClassPriors = new double[m_NumClasses];
    setPriors(data);
    m_MarginCounts = new double[k_MarginResolution + 1];
}

From source file:GClass.EvaluationInternal.java

License:Open Source License

/**
 * Performs a (stratified if class is nominal) cross-validation
 * for a classifier on a set of instances.
 *
 * @param classifier the classifier with any options set.
 * @param data the data on which the cross-validation is to be
 * performed/*from  w w w.j av a 2s  . c  o  m*/
 * @param numFolds the number of folds for the cross-validation
 * @param random random number generator for randomization
 * @exception Exception if a classifier could not be generated
 * successfully or the class is not defined
 */
public void crossValidateModel(Classifier classifier, Instances data, int numFolds, Random random)
        throws Exception {

    // Make a copy of the data we can reorder
    data = new Instances(data);
    data.randomize(random);
    if (data.classAttribute().isNominal()) {
        data.stratify(numFolds);
    }
    // Do the folds
    for (int i = 0; i < numFolds; i++) {
        Instances train = data.trainCV(numFolds, i, random);
        setPriors(train);
        Classifier copiedClassifier = Classifier.makeCopy(classifier);
        copiedClassifier.buildClassifier(train);
        Instances test = data.testCV(numFolds, i);
        evaluateModel(copiedClassifier, test);
    }
    m_NumFolds = numFolds;
}