List of usage examples for weka.core Instance value
public double value(Attribute att);
From source file:edu.oregonstate.eecs.mcplan.ml.WekaGlue.java
License:Open Source License
public static double[] toDoubleArray(final Instance inst) { final double[] v = new double[inst.numAttributes()]; for (int i = 0; i < inst.numAttributes(); ++i) { v[i] = inst.value(i); }//from ww w.ja va 2 s . c o m return v; }
From source file:edu.oregonstate.eecs.mcplan.ml.WekaGlue.java
License:Open Source License
public static SequentialProjectionHashLearner createSequentialProjectionHashLearner(final RandomGenerator rng, final Instances labeled, final Instances unlabeled, final int K, final double eta, final double alpha) { assert (labeled.classIndex() >= 0); final int Nfeatures = labeled.numAttributes() - 1; final RealMatrix X = new Array2DRowRealMatrix(Nfeatures, labeled.size() + unlabeled.size()); final RealMatrix XL = new Array2DRowRealMatrix(Nfeatures, labeled.size() * 2); final RealMatrix S = new Array2DRowRealMatrix(XL.getColumnDimension(), XL.getColumnDimension()); for (int j = 0; j < labeled.size(); ++j) { final Instance inst = labeled.get(j); for (int i = 0; i < XL.getRowDimension(); ++i) { X.setEntry(i, j, inst.value(i)); XL.setEntry(i, j, inst.value(i)); }//from w w w. j a va 2 s .c o m int sj = -1; Instance s = null; do { sj = rng.nextInt(labeled.size()); s = labeled.get(sj); } while (s == inst || s.classValue() != inst.classValue()); S.setEntry(j, sj, 1); int dj = -1; Instance d = null; do { dj = rng.nextInt(labeled.size()); d = labeled.get(dj); } while (d == inst || d.classValue() == inst.classValue()); S.setEntry(j, dj, -1); } for (int j = 0; j < unlabeled.size(); ++j) { final Instance inst = unlabeled.get(j); for (int i = 0; i < X.getRowDimension(); ++i) { X.setEntry(i, labeled.size() + j, inst.value(i)); } } return new SequentialProjectionHashLearner(X, XL, S, K, eta, alpha); }
From source file:edu.umbc.cs.maple.utils.WekaUtils.java
License:Open Source License
/** Converts a set of instances to svm-light format * @param data the weka instances// w w w. j av a 2 s. co m * @return the weka instances in svm-light format */ public static String arffToSVMLight(Instances data, SVMLightLabelFormat labelFormat) { if (labelFormat == SVMLightLabelFormat.CLASSIFICATION && data.numClasses() != 2) { throw new IllegalArgumentException( "SVM-light classification label format requires that the data contain only two classes."); } String str = ""; String endline = System.getProperty("line.separator"); int numInstances = data.numInstances(); int numAttributes = data.numAttributes(); int classAttIdx = data.classIndex(); for (int instIdx = 0; instIdx < numInstances; instIdx++) { Instance inst = data.instance(instIdx); // convert the instance label if (labelFormat == SVMLightLabelFormat.CLASSIFICATION) { str += (inst.classValue() == 0) ? "-1" : "1"; } else { str += inst.classValue(); } str += " "; // convert each feature for (int attIdx = 0; attIdx < numAttributes; attIdx++) { // skip the class attribute if (attIdx == classAttIdx) continue; str += (attIdx + 1) + ":" + inst.value(attIdx) + " "; } // append the instance info string str += "# " + instIdx; str += endline; } return str; }
From source file:edu.umbc.cs.maple.utils.WekaUtils.java
License:Open Source License
/** Converts a set of instances to svm-light format * @param data the weka instances// w w w . j a va 2s.co m * @return the weka instances in svm-light format */ public static String arffToSVMLight(Instance data, SVMLightLabelFormat labelFormat) { if (labelFormat == SVMLightLabelFormat.CLASSIFICATION && data.numClasses() != 2) { throw new IllegalArgumentException( "SVM-light classification label format requires that the data contain only two classes."); } String str = ""; String endline = System.getProperty("line.separator"); int numAttributes = data.numAttributes(); int classAttIdx = data.classIndex(); // convert the instance label if (labelFormat == SVMLightLabelFormat.CLASSIFICATION) { str += (data.classValue() == 0) ? "-1" : "1"; } else { str += data.classValue(); } str += " "; // convert each feature for (int attIdx = 0; attIdx < numAttributes; attIdx++) { // skip the class attribute if (attIdx == classAttIdx) continue; str += (attIdx + 1) + ":" + data.value(attIdx) + " "; } // append the instance info string str += "#"; str += endline; return str; }
From source file:elh.eus.absa.WekaWrapper.java
License:Open Source License
/** * Simple function to print the results of a multilabel prediction. * // w ww . j av a 2s.c o m * @param HashMap<Instance, double[]> pred hashmap containing a set of instances and their corresponding * multilabel prediction, as computed by the multiLabelPrediction() function in this class. */ public void printMultilabelPredictions(HashMap<Instance, double[]> pred) { for (Instance i : pred.keySet()) { double[] kk = pred.get(i); int c = 0; System.out.print("instance " + Integer.parseInt(Double.toString(i.value(0))) + " (" + i.classValue() + "|" + i.stringValue(i.classIndex()) + ") --> "); for (double d : kk) { System.out.print("cl_" + c + "=" + d + "; "); c++; } System.out.print("\n"); } }
From source file:elh.eus.absa.WekaWrapper.java
License:Open Source License
/** * Train one vs all models over the given training data. * //ww w . j a va2 s.com * @param modelpath directory to store each model for the one vs. all method * @param prefix prefix the models should have (each model will have the name of its class appended * @throws Exception */ public HashMap<Integer, HashMap<String, Double>> predictOneVsAll(String modelpath, String prefix) throws Exception { HashMap<Integer, HashMap<String, Double>> rslt = new HashMap<Integer, HashMap<String, Double>>(); if ((testdata == null) || testdata.isEmpty()) { System.err.println("WekaWrapper: testModel() - no test data available, model won't be evaluated"); System.exit(9); } Enumeration<Object> classValues = traindata.classAttribute().enumerateValues(); HashMap<String, Classifier> cls = new HashMap<String, Classifier>(); while (classValues.hasMoreElements()) { String v = (String) classValues.nextElement(); //needed because of weka's sparse data format problems THIS IS TROUBLE! ... if (v.equalsIgnoreCase("dummy")) { continue; } try { Classifier cl = loadModel(modelpath + File.separator + prefix + "_" + v + ".model"); cls.put(v, cl); } catch (Exception e) { System.err.println("classifier for class " + v + " could not be loaded, prediction aborted"); System.exit(9); } } for (int i = 0; i < testdata.numInstances(); i++) { HashMap<String, Double> clResults = new HashMap<String, Double>(); Instance inst = testdata.instance(i); int instId = (int) inst.value(testdata.attribute("instanceId").index()); inst.setClassMissing(); for (String currentClass : cls.keySet()) { double[] dist = cls.get(currentClass).distributionForInstance(inst); String[] classes = { "dummy", currentClass, "UNKNOWN" }; System.out.print("instance " + instId + " (" + currentClass + ") --> "); for (int c = 0; c < dist.length; c++) { System.out.print("\t cl_" + c + " (" + classes[c] + ") = " + dist[c] + "; "); } System.out.print("\n"); //first class is always the class to identify, if unknown class has better score store -1 for the class clResults.put(currentClass, dist[1]); } rslt.put(instId, clResults); } return rslt; }
From source file:elh.eus.absa.WekaWrapper.java
License:Open Source License
/** * Train one vs all models over the given training data. * //from ww w . j a v a 2s.c om * @param modelpath directory to store each model for the one vs. all method * @param prefix prefix the models should have (each model will have the name of its class appended * @throws Exception */ public HashMap<Integer, HashMap<String, Double>> addOneVsAllPredictions(String modelpath, String prefix, double thres) throws Exception { HashMap<Integer, HashMap<String, Double>> rslt = new HashMap<Integer, HashMap<String, Double>>(); if ((testdata == null) || testdata.isEmpty()) { System.err.println("WekaWrapper: testModel() - no test data available, model won't be evaluated"); System.exit(9); } Enumeration<Object> classValues = traindata.classAttribute().enumerateValues(); HashMap<String, Classifier> cls = new HashMap<String, Classifier>(); while (classValues.hasMoreElements()) { String v = (String) classValues.nextElement(); //needed because of weka's sparse data format problems THIS IS TROUBLE! ... if (v.equalsIgnoreCase("dummy")) { continue; } try { Classifier cl = loadModel(modelpath + File.separator + prefix + "_" + v + ".model"); cls.put(v, cl); } catch (Exception e) { System.err.println("classifier for class " + v + " could not be loaded, prediction aborted"); System.exit(9); } } for (int i = 0; i < testdata.numInstances(); i++) { HashMap<String, Double> clResults = new HashMap<String, Double>(); Instance inst = testdata.instance(i); int instId = (int) inst.value(testdata.attribute("instanceId").index()); inst.setClassMissing(); for (String currentClass : cls.keySet()) { double[] dist = cls.get(currentClass).distributionForInstance(inst); System.out.print("instance " + instId + " (" + currentClass + ") --> \n"); /* for (int c=0; c<dist.length; c++) { System.out.print("\t cl_"+c+" ("+") = "+dist[c]+"; "); } System.out.print("\n"); */ //first class is always the class to identify, if unknown class has better score store -1 for the class clResults.put(currentClass, dist[1]); } rslt.put(instId, clResults); } return rslt; }
From source file:en_deep.mlprocess.manipulation.featmodif.FeatureModifierFilter.java
License:Open Source License
/** * Convert a single instance over if the class is nominal. The converted * instance is added to the end of the output queue. * * @param instance the instance to convert *//*from www. j av a2s .c om*/ private void convertInstance(Instance instance) { double[] vals = new double[outputFormatPeek().numAttributes()]; String[] stringVals = new String[vals.length]; int attSoFar = 0; for (int j = 0; j < getInputFormat().numAttributes(); j++) { Attribute att = instance.attribute(j); if (!m_Columns.isInRange(j)) { vals[attSoFar] = instance.value(j); attSoFar++; } else { // store new string values, make double values "missing" for now (if some string // values are missing, the double values will remain missing) if (instance.value(0) == 12 && instance.value(1) == 9 && att.name().equals("sempos")) { attSoFar = attSoFar; } attSoFar += getAttributeOutputValue(att, instance.value(j), vals, stringVals, attSoFar); } } Instance inst = null; if (instance instanceof SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new DenseInstance(instance.weight(), vals); } inst.setDataset(getOutputFormat()); copyValues(inst, false, instance.dataset(), getOutputFormat()); // add new string values to the output data set and to the instance for (int i = 0; i < stringVals.length; ++i) { if (stringVals[i] != null) { vals[i] = inst.dataset().attribute(i).addStringValue(stringVals[i]); } } inst.replaceMissingValues(vals); inst.setDataset(getOutputFormat()); push(inst); }
From source file:en_deep.mlprocess.manipulation.SetAwareNominalToBinary.java
License:Open Source License
/** * Convert a single instance over if the class is nominal. The converted * instance is added to the end of the output queue. * * @param instance the instance to convert *//*from w w w . j a v a 2 s . c o m*/ private void convertInstance(Instance instance) { double[] vals = new double[outputFormatPeek().numAttributes()]; int attSoFar = 0; for (int j = 0; j < getInputFormat().numAttributes(); j++) { Attribute att = getInputFormat().attribute(j); if (!att.isNominal() || (j == getInputFormat().classIndex()) || !m_Columns.isInRange(j)) { vals[attSoFar] = instance.value(j); attSoFar++; } else { if ((att.numValues() <= 2) && (!m_TransformAll)) { vals[attSoFar] = instance.value(j); attSoFar++; } else { attSoFar += setConvertedAttribute(att, instance.value(j), vals, attSoFar); } } } Instance inst = null; if (instance instanceof SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new DenseInstance(instance.weight(), vals); } inst.setDataset(getOutputFormat()); copyValues(inst, false, instance.dataset(), getOutputFormat()); inst.setDataset(getOutputFormat()); push(inst); }
From source file:ergasia2pkg.LP_ROS.java
/** * Groups instances by their labels/*from w w w . jav a 2 s. c o m*/ * * @param MultilabelInstances labeled instances * @return HashMap<String,List<Instance>> returned Hashmap with grouping */ public HashMap groupByLabelSet(MultiLabelInstances mlData) { Instances inst = mlData.getDataSet(); Set<Attribute> atts = mlData.getLabelAttributes(); HashMap LabelSetGroups = new HashMap<String, List<Instance>>(); for (int i = 0; i < inst.numInstances(); i++) { Instance in = inst.get(i); String labelsetName = ""; for (Attribute att : atts) { if (in.value(att) != 0) { labelsetName = labelsetName + att.name(); } } if (LabelSetGroups.containsKey(labelsetName)) { List myList = (List) LabelSetGroups.get(labelsetName); myList.add(in); LabelSetGroups.put(labelsetName, myList); } else { List<Instance> myList = new ArrayList<Instance>(); myList.add(in); LabelSetGroups.put(labelsetName, myList); } } return LabelSetGroups; }