List of usage examples for weka.core Instance setValue
public void setValue(Attribute att, String value);
From source file:meka.filters.multilabel.SuperNodeFilter.java
License:Open Source License
/** * Merge Labels./* ww w .j a v a2 s . c o m*/ * * @param j index 1 (assume that <code>j < k</code>) * @param k index 2 (assume that <code>j < k</code>) * @param D iInstances, with attributes in labeled by original index * @return Instaces with attributes at j and k moved to position L as (j,k), with classIndex = L-1 */ public static Instances mergeLabels(Instances D, int j, int k, int p) { int L = D.classIndex(); HashMap<String, Integer> count = new HashMap<String, Integer>(); Set<String> values = new HashSet<String>(); for (int i = 0; i < D.numInstances(); i++) { String v = encodeValue(D.instance(i).stringValue(j), D.instance(i).stringValue(k)); String w = "" + (int) D.instance(i).value(j) + (int) D.instance(i).value(k); //System.out.println("w = "+w); count.put(v, count.containsKey(v) ? count.get(v) + 1 : 1); values.add(encodeValue(D.instance(i).stringValue(j), D.instance(i).stringValue(k))); } //System.out.println("("+j+","+k+")"+values); System.out.print("pruned from " + count.size() + " to "); MLUtils.pruneCountHashMap(count, p); String y_max = (String) MLUtils.argmax(count); // @todo won't need this in the future System.out.println("" + count.size() + " with p = " + p); System.out.println("" + count); values = count.keySet(); // Create and insert the new attribute D.insertAttributeAt( new Attribute(encodeClass(D.attribute(j).name(), D.attribute(k).name()), new ArrayList(values)), L); // Set values for the new attribute for (int i = 0; i < D.numInstances(); i++) { Instance x = D.instance(i); String y_jk = encodeValue(x.stringValue(j), x.stringValue(k)); try { x.setValue(L, y_jk); // y_jk = } catch (Exception e) { //x.setMissing(L); //D.delete(i); //i--; String y_close[] = getNeighbours(y_jk, count, 1); // A+B+NEG, A+C+NEG //System.out.println("OK, that value ("+y_jk+") didn't exist ... set the closests ones ...: "+Arrays.toString(y_close)); int max_c = 0; for (String y_ : y_close) { int c = count.get(y_); if (c > max_c) { max_c = c; y_max = y_; } } //System.out.println("we actually found "+Arrays.toString(y_close)+" but will only set one for now (the one with the highest count) : "+y_max+" ..."); x.setValue(L, y_max); // ok, that value didn't exist, set the maximum one (@TODO: set the nearest one) } } // Delete separate attributes D.deleteAttributeAt(k > j ? k : j); D.deleteAttributeAt(k > j ? j : k); // Set class index D.setClassIndex(L - 1); return D; }
From source file:meka.gui.dataviewer.DataTableModel.java
License:Open Source License
/** * sets the value in the cell at columnIndex and rowIndex to aValue. but only * the value and the value can be changed * * @param aValue the new value//w ww.j a v a 2 s. c o m * @param rowIndex the row index * @param columnIndex the column index * @param notify whether to notify the listeners */ public void setValueAt(Object aValue, int rowIndex, int columnIndex, boolean notify) { int type; int index; String tmp; Instance inst; Attribute att; Object oldValue; if (!m_IgnoreChanges) { addUndoPoint(); } oldValue = getValueAt(rowIndex, columnIndex); type = getType(rowIndex, columnIndex); index = columnIndex - 1; inst = m_Data.instance(rowIndex); att = inst.attribute(index); // missing? if (aValue == null) { inst.setValue(index, Utils.missingValue()); } else { tmp = aValue.toString(); switch (type) { case Attribute.DATE: try { att.parseDate(tmp); inst.setValue(index, att.parseDate(tmp)); } catch (Exception e) { // ignore } break; case Attribute.NOMINAL: if (att.indexOfValue(tmp) > -1) { inst.setValue(index, att.indexOfValue(tmp)); } break; case Attribute.STRING: inst.setValue(index, tmp); break; case Attribute.NUMERIC: try { Double.parseDouble(tmp); inst.setValue(index, Double.parseDouble(tmp)); } catch (Exception e) { // ignore } break; case Attribute.RELATIONAL: try { inst.setValue(index, inst.attribute(index).addRelation((Instances) aValue)); } catch (Exception e) { // ignore } break; default: throw new IllegalArgumentException("Unsupported Attribute type: " + type + "!"); } } // notify only if the value has changed! if (notify && (!("" + oldValue).equals("" + aValue))) { notifyListener(new TableModelEvent(this, rowIndex, columnIndex)); } }
From source file:meka.gui.explorer.classify.PredictionsOnTestset.java
License:Open Source License
/** * Returns the action lister to use in the menu. * * @param history the current history//from www . j av a 2 s . c o m * @param index the selected history item * @return the listener */ @Override public ActionListener getActionListener(final ResultHistoryList history, final int index) { final MultiLabelClassifier classifier = (MultiLabelClassifier) getClassifier(history, index); final Instances header = getHeader(history, index); return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Runnable run = new Runnable() { @Override public void run() { ClassifyTab owner = (ClassifyTab) getOwner(); Instances test; owner.startBusy("Predictions on test..."); try { MLUtils.prepareData(owner.getTestData()); test = new Instances(owner.getTestData()); test.setClassIndex(owner.getTestData().classIndex()); String msg = header.equalHeadersMsg(test); if (msg != null) throw new IllegalArgumentException( "Model's training set and current test set are not compatible:\n" + msg); // collect predictions Instances predicted = new Instances(test, 0); for (int i = 0; i < test.numInstances(); i++) { double pred[] = classifier.distributionForInstance(test.instance(i)); // Cut off any [no-longer-needed] probabalistic information from MT classifiers. if (classifier instanceof MultiTargetClassifier) pred = Arrays.copyOf(pred, test.classIndex()); Instance predInst = (Instance) test.instance(i).copy(); for (int j = 0; j < pred.length; j++) predInst.setValue(j, pred[j]); predicted.add(predInst); if ((i + 1) % 100 == 0) owner.showStatus( "Predictions on test (" + (i + 1) + "/" + test.numInstances() + ")..."); } owner.finishBusy(); // display predictions DataViewerDialog dialog = new DataViewerDialog(GUIHelper.getParentFrame(owner), ModalityType.MODELESS); dialog.setDefaultCloseOperation(DataViewerDialog.DISPOSE_ON_CLOSE); dialog.setInstances(predicted); dialog.setSize(800, 600); dialog.setLocationRelativeTo(owner); dialog.setVisible(true); } catch (Exception e) { owner.handleException("Predictions failed on test set:", e); owner.finishBusy("Predictions failed: " + e); JOptionPane.showMessageDialog(owner, "Predictions failed:\n" + e, "Error", JOptionPane.ERROR_MESSAGE); } } }; ((ClassifyTab) getOwner()).start(run); } }; }
From source file:milk.classifiers.MINND.java
License:Open Source License
/** * Scale the given exemplar so that the returned exemplar * has the value of 0 to 1 for each dimension * /*from ww w . j ava 2 s . com*/ * @param before the given exemplar * @return the resultant exemplar after scaling * @exception if given exampler cannot be scaled properly */ private Exemplar scale(Exemplar before) throws Exception { Instances data = before.getInstances(); Exemplar after = new Exemplar(before, 0); for (int i = 0; i < data.numInstances(); i++) { Instance datum = data.instance(i); Instance inst = (Instance) datum.copy(); int k = 0; for (int j = 0; j < data.numAttributes(); j++) { if ((j != before.idIndex()) && (j != before.classIndex())) { if (data.attribute(j).isNumeric()) inst.setValue(j, (datum.value(j) - m_MinArray[k]) / (m_MaxArray[k] - m_MinArray[k])); k++; } } after.add(inst); } return after; }
From source file:milk.classifiers.SimpleMI.java
License:Open Source License
public Instances transform(Exemplars train) throws Exception { Instances data = new Instances(m_Attributes);// Data to learn a model data.deleteAttributeAt(m_IdIndex);// ID attribute useless Instances dataset = new Instances(data, 0); Instance template = new Instance(dataset.numAttributes()); template.setDataset(dataset);//from ww w. j av a2s.c om double N = train.numExemplars(); // Number of exemplars for (int i = 0; i < N; i++) { Exemplar exi = train.exemplar(i); Instances insts = exi.getInstances(); int attIdx = 0; Instance newIns = new Instance(template); newIns.setDataset(dataset); for (int j = 0; j < insts.numAttributes(); j++) { if ((j == m_IdIndex) || (j == m_ClassIndex)) continue; double value; if (m_TransformMethod == 1) { value = insts.meanOrMode(j); } else { double[] minimax = minimax(insts, j); value = (minimax[0] + minimax[1]) / 2.0; } newIns.setValue(attIdx++, value); } newIns.setClassValue(exi.classValue()); data.add(newIns); } return data; }
From source file:milk.experiment.MIInstancesResultListener.java
License:Open Source License
/** * Collects each instance and adjusts the header information. * * @param rp the ResultProducer that generated the result * @param key The key for the results.//w w w .j av a2 s . c o m * @param result The actual results. * @exception Exception if the result could not be accepted. */ public void acceptResult(MIResultProducer rp, Object[] key, Object[] result) throws Exception { if (m_RP != rp) { throw new Error("Unrecognized ResultProducer sending results!!"); } Instance newInst = new Instance(m_AttributeTypes.length); for (int i = 0; i < m_AttributeTypes.length; i++) { Object val = null; if (i < key.length) { val = key[i]; } else { val = result[i - key.length]; } if (val == null) { newInst.setValue(i, Instance.missingValue()); } else { switch (m_AttributeTypes[i]) { case Attribute.NOMINAL: String str = (String) val; Double index = (Double) m_NominalIndexes[i].get(str); if (index == null) { index = new Double(m_NominalStrings[i].size()); m_NominalIndexes[i].put(str, index); m_NominalStrings[i].addElement(str); } newInst.setValue(i, index.doubleValue()); break; case Attribute.NUMERIC: double dou = ((Double) val).doubleValue(); newInst.setValue(i, (double) dou); break; default: newInst.setValue(i, Instance.missingValue()); } } } m_Instances.addElement(newInst); }
From source file:ml.ann.BackPropagation.java
License:Open Source License
@Override public double[] distributionForInstance(Instance instance) throws Exception { Instance currentInstance; // default model? if (useDefaultModel) { return zeroR.distributionForInstance(instance); }//w w w. j a va 2 s . c om // Make a copy of the instance so that it isn't modified currentInstance = (Instance) instance.copy(); for (int noa = 0; noa < currentInstance.numAttributes(); noa++) { if (noa != neuronTopology.instances.classIndex()) { if (attributeRanges[noa] != 0) { currentInstance.setValue(noa, (currentInstance.value(noa) - attributeBases[noa]) / attributeRanges[noa]); } else { currentInstance.setValue(noa, currentInstance.value(noa) - attributeBases[noa]); } } } // resetNetwork(); // initInputAndTarget(currentInstance); int lastLayerIdx = neuronTopology.numLayers - 1; for (int layers = 0; layers < neuronTopology.numLayers; layers++) { for (int neu = 0; neu < neuronTopology.numNeuronEachLayer[layers]; neu++) { neuronTopology.output[layers][neu] = sigmoidFunction(layers, neu); } } double[] jancuk = new double[neuronTopology.numNeuronEachLayer[lastLayerIdx]]; for (int i = 0; i < neuronTopology.numNeuronEachLayer[lastLayerIdx]; i++) { jancuk[i] = neuronTopology.output[lastLayerIdx][i]; } // now normalize the array double count = 0; for (int noa = 0; noa < neuronTopology.numClasses; noa++) { count += jancuk[noa]; } if (count <= 0) { // return zeroR.distributionForInstance(i); } for (int noa = 0; noa < neuronTopology.numClasses; noa++) { jancuk[noa] /= count; } return jancuk; }
From source file:mlflex.learners.WekaLearner.java
License:Open Source License
private static Instance GetInstance(Instances wekaInstances, FastVector wekaAttributeVector, Prediction prediction) throws Exception { Instance wekaInstance = new Instance(wekaAttributeVector.size()); wekaInstance.setDataset(wekaInstances); wekaInstance.setValue((Attribute) wekaAttributeVector.elementAt(0), prediction.Prediction); wekaInstance.setValue((Attribute) wekaAttributeVector.elementAt(1), prediction.DependentVariableValue); return wekaInstance; }
From source file:mlflex.WekaInMemoryLearner.java
License:Open Source License
private static void SetAttributeValue(Instance wekaInstance, Attribute attribute, String value) { try {/* w w w. ja v a2 s . c om*/ if (value.equals(Settings.MISSING_VALUE_STRING)) { wekaInstance.setMissing(attribute); } else { if (attribute.isNominal()) { wekaInstance.setValue(attribute, value); } else { wekaInstance.setValue(attribute, Double.parseDouble(value)); } } } catch (Exception ex) { Utilities.Log.Debug("Data point name: " + attribute.name()); Utilities.Log.Debug("Data point value:"); Utilities.Log.Debug(value); Utilities.Log.Debug("Is double: " + DataTypes.IsDouble(value)); Utilities.Log.Debug("Is binary: " + DataTypes.IsBinary(value)); Utilities.Log.Debug("Is integer: " + DataTypes.IsInteger(value)); Utilities.Log.ExceptionFatal(ex); } }
From source file:ml_project.ML_Project.java
public String classify(String testFileName, String modelFileName) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(testFileName)); String str;//from w w w . j a v a 2 s .co m testInput = ""; while ((str = reader.readLine()) != null) { testInput = testInput + " " + str; } reader.close(); ObjectInputStream in = new ObjectInputStream(new FileInputStream(modelFileName)); Object tmp = in.readObject(); classifier = (FilteredClassifier) tmp; in.close(); Attribute testInputAttr = new Attribute("testInput", (FastVector) null); FastVector classVals = new FastVector(6); classVals.addElement("Course"); classVals.addElement("Department"); classVals.addElement("Faculty"); classVals.addElement("Project"); classVals.addElement("Staff"); classVals.addElement("Student"); Attribute classAttr = new Attribute("class", classVals); FastVector attrs = new FastVector(2); attrs.addElement(testInputAttr); attrs.addElement(classAttr); instances = new Instances("Test relation", attrs, 1); instances.setClassIndex(1); Instance instance = new Instance(2); instance.setValue(testInputAttr, testInput); instances.add(instance); double pred = classifier.classifyInstance(instances.instance(0)); return instances.classAttribute().value((int) pred); }