List of usage examples for weka.core Instances instance
publicInstance instance(int index)
From source file:adams.flow.transformer.WekaSetInstancesValue.java
License:Open Source License
/** * Executes the flow item.// w ww .j a v a 2 s . c o m * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; Instances inst; int row; int index; result = null; inst = (Instances) m_InputToken.getPayload(); inst = new Instances(inst); m_Row.setMax(inst.numInstances()); m_Column.setData(inst); row = m_Row.getIntIndex(); index = m_Column.getIntIndex(); if (row == -1) result = "Failed to retrieve row: " + m_Row.getIndex(); else if (index == -1) result = "Failed to retrieve column: " + m_Column.getIndex(); if (result == null) { try { if (m_Value.equals("?")) { inst.instance(row).setMissing(index); } else { switch (inst.attribute(index).type()) { case Attribute.NUMERIC: inst.instance(row).setValue(index, Utils.toDouble(m_Value)); break; case Attribute.DATE: inst.instance(row).setValue(index, inst.attribute(index).parseDate(m_Value)); break; case Attribute.NOMINAL: case Attribute.STRING: inst.instance(row).setValue(index, m_Value); break; case Attribute.RELATIONAL: result = "Relational attributes cannot be set!"; break; default: result = "Unhandled attribute type: " + inst.attribute(index).type(); } } } catch (Exception e) { result = handleException("Failed to set value: " + m_Column.getIndex() + " -> " + m_Value, e); } } // broadcast data if (result == null) m_OutputToken = new Token(inst); return result; }
From source file:adams.flow.transformer.WekaSubsets.java
License:Open Source License
/** * Executes the flow item./*ww w . jav a 2 s . com*/ * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; Instances data; Double old; Double curr; int i; int index; Instance inst; result = null; m_Queue.clear(); // copy and sort data data = new Instances((Instances) m_InputToken.getPayload()); m_Index.setData(data); ; index = m_Index.getIntIndex(); data.sort(index); // create subsets old = null; i = 0; while (i < data.numInstances()) { inst = data.instance(i); curr = inst.value(index); if ((old == null) || !curr.equals(old)) { m_Queue.add(new Instances(data, data.numInstances())); old = curr; } m_Queue.get(m_Queue.size() - 1).add(inst); i++; } // compact subsets for (Instances sub : m_Queue) sub.compactify(); return result; }
From source file:adams.gui.tools.previewbrowser.InstanceExplorerHandler.java
License:Open Source License
/** * Creates the actual view.//from w w w . ja v a2s . co m * * @param file the file to create the view for * @return the view */ @Override protected PreviewPanel createPreview(File file) { InstancePanel result; Instances dataset; int i; Instance inst; List<InstanceContainer> data; result = new InstancePanel(); try { data = new ArrayList<InstanceContainer>(); dataset = DataSource.read(file.getAbsolutePath()); for (i = 0; i < dataset.numInstances(); i++) { inst = new Instance(); inst.set(dataset.instance(i)); inst.setID((i + 1) + "." + dataset.relationName()); data.add(result.getContainerManager().newContainer(inst)); } result.getContainerManager().addAll(data); } catch (Exception e) { getLogger().log(Level.SEVERE, "Failed to load dataset '" + file + "':", e); } return new PreviewPanel(result); }
From source file:adams.gui.visualization.instance.InstanceExplorer.java
License:Open Source License
/** * pops up SQL Viewer for SQL statement. *///from ww w. ja v a 2 s . c om public void loadDataFromDatabase() { InstanceQuery query; List<InstanceContainer> data; Instances dataset; Instance inst; int i; if (m_LoadFromDatabaseDialog == null) { if ((getParentFrame() != null) && (getParentFrame() instanceof JFrame)) m_LoadFromDatabaseDialog = new SqlViewerDialog((JFrame) getParentFrame()); else m_LoadFromDatabaseDialog = new SqlViewerDialog(null); } m_LoadFromDatabaseDialog.setVisible(true); if (m_LoadFromDatabaseDialog.getReturnValue() != JOptionPane.OK_OPTION) return; try { showStatus("Executing query: " + m_LoadFromDatabaseDialog.getQuery()); query = new InstanceQuery(); query.setDatabaseURL(m_LoadFromDatabaseDialog.getURL()); query.setUsername(m_LoadFromDatabaseDialog.getUser()); query.setPassword(m_LoadFromDatabaseDialog.getPassword()); query.setQuery(m_LoadFromDatabaseDialog.getQuery()); query.setSparseData(m_LoadFromDatabaseDialog.getGenerateSparseData()); if (query.isConnected()) query.disconnectFromDatabase(); query.connectToDatabase(); showStatus("Loading data..."); data = new ArrayList<>(); dataset = query.retrieveInstances(); for (i = 0; i < dataset.numInstances(); i++) { inst = new Instance(); inst.set(dataset.instance(i)); inst.setID(dataset.relationName() + "." + i); data.add(getContainerManager().newContainer(inst)); showStatus("Loading data " + (i + 1) + "/" + dataset.numInstances()); } loadData(dataset, data); } catch (Exception e) { GUIHelper.showErrorMessage(this, "Failed to load data from database:\n" + Utils.throwableToString(e), "Database error"); } showStatus(""); }
From source file:adams.gui.visualization.instance.InstanceExplorer.java
License:Open Source License
/** * pops up file dialog for loading dataset form disk. * * @param file an optional file, use null to ignore *///from w ww. j a v a 2s .c o m public void loadDataFromDisk(File file) { if (m_LoadFromDiskDialog == null) { if (getParentDialog() != null) m_LoadFromDiskDialog = new LoadDatasetDialog(getParentDialog()); else m_LoadFromDiskDialog = new LoadDatasetDialog(getParentFrame()); m_LoadFromDiskDialog.setCurrent(new File(getProperties().getPath("InitialDir", "%h"))); m_LoadFromDiskDialog.setDefaultAttributeRange(getProperties().getPath("AttributeRange", "first-last")); m_LoadFromDiskDialog.setDefaultClassIndex(getProperties().getPath("ClassIndex", "")); m_LoadFromDiskDialog.setDefaultSortIndex(getProperties().getPath("SortIndex", "")); m_LoadFromDiskDialog.setDefaultIncludeAttributes(Attribute.NUMERIC, getProperties().getBoolean("IncludeNumericAttributes", true)); m_LoadFromDiskDialog.setDefaultIncludeAttributes(Attribute.DATE, getProperties().getBoolean("IncludeDateAttributes", false)); m_LoadFromDiskDialog.setDefaultIncludeAttributes(Attribute.NOMINAL, getProperties().getBoolean("IncludeNominalAttributes", false)); m_LoadFromDiskDialog.setDefaultIncludeAttributes(Attribute.STRING, getProperties().getBoolean("IncludeStringAttributes", false)); m_LoadFromDiskDialog.setDefaultIncludeAttributes(Attribute.RELATIONAL, getProperties().getBoolean("IncludeRelationalAttributes", false)); m_LoadFromDiskDialog.setAcceptListener((ChangeEvent e) -> { int[] indices = m_LoadFromDiskDialog.getIndices(); if (indices == null) return; if (m_RecentFilesHandler != null) m_RecentFilesHandler.addRecentItem(m_LoadFromDiskDialog.getCurrent()); HashSet<Integer> attTypes = new HashSet<>(); if (m_LoadFromDiskDialog.getIncludeAttributes(Attribute.NUMERIC)) attTypes.add(Attribute.NUMERIC); if (m_LoadFromDiskDialog.getIncludeAttributes(Attribute.DATE)) attTypes.add(Attribute.DATE); if (m_LoadFromDiskDialog.getIncludeAttributes(Attribute.NOMINAL)) attTypes.add(Attribute.NOMINAL); if (m_LoadFromDiskDialog.getIncludeAttributes(Attribute.STRING)) attTypes.add(Attribute.STRING); if (m_LoadFromDiskDialog.getIncludeAttributes(Attribute.RELATIONAL)) attTypes.add(Attribute.RELATIONAL); showStatus("Loading data..."); List<InstanceContainer> data = new ArrayList<>(); Instances dataset = m_LoadFromDiskDialog.getDataset(); int[] additional = m_LoadFromDiskDialog.getAdditionalAttributes(); Range range = m_LoadFromDiskDialog.getCurrentAttributeRange(); int id = m_LoadFromDiskDialog.getCurrentIDIndex(); for (int i = 0; i < indices.length; i++) { weka.core.Instance winst = dataset.instance(indices[i]); Instance inst = new Instance(); inst.set(winst, i, additional, range, attTypes); if (id == -1) { inst.setID((indices[i] + 1) + "." + dataset.relationName()); } else { if (winst.attribute(id).isNumeric()) inst.setID("" + winst.value(id)); else inst.setID(winst.stringValue(id)); } data.add(getContainerManager().newContainer(inst)); showStatus("Loading data " + (i + 1) + "/" + dataset.numInstances()); } loadData(dataset, data); showStatus(""); }); } if (file != null) m_LoadFromDiskDialog.setCurrent(file); m_LoadFromDiskDialog.setVisible(true); }
From source file:adams.gui.visualization.instances.instancestable.Histogram.java
License:Open Source License
/** * Allows the user to generate a plot from either a row or a column. * * @param data the instances to use/* w w w . j a va 2 s . c o m*/ * @param isColumn whether to use column or row * @param index the index of the row/column */ protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) { TDoubleArrayList list; HistogramFactory.SetupDialog setup; HistogramFactory.Dialog dialog; int i; ArrayHistogram last; int col; int row; Object value; // let user customize histogram if (GUIHelper.getParentDialog(table) != null) setup = HistogramFactory.getSetupDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL); else setup = HistogramFactory.getSetupDialog(GUIHelper.getParentFrame(table), true); setup.setDefaultCloseOperation(HistogramFactory.SetupDialog.DISPOSE_ON_CLOSE); setup.setTitle("Histogram setup"); last = (ArrayHistogram) table.getLastSetup(getClass(), true, !isColumn); if (last == null) last = new ArrayHistogram(); setup.setCurrent(last); setup.setLocationRelativeTo(GUIHelper.getParentComponent(table)); setup.setVisible(true); if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION) return; last = (ArrayHistogram) setup.getCurrent(); table.addLastSetup(getClass(), true, !isColumn, last); // get data from instances list = new TDoubleArrayList(); if (isColumn) { col = index + 1; for (i = 0; i < table.getRowCount(); i++) { value = table.getValueAt(i, col); if ((value != null) && (Utils.isDouble(value.toString()))) list.add(Utils.toDouble(value.toString())); } } else { row = index; for (i = 0; i < data.numAttributes(); i++) { if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i)) list.add(data.instance(row).value(i)); } } // calculate histogram last.clear(); // display histogram if (GUIHelper.getParentDialog(table) != null) dialog = HistogramFactory.getDialog(GUIHelper.getParentDialog(table), ModalityType.MODELESS); else dialog = HistogramFactory.getDialog(GUIHelper.getParentFrame(table), false); dialog.setDefaultCloseOperation(HistogramFactory.Dialog.DISPOSE_ON_CLOSE); if (isColumn) dialog.add(last, list.toArray(), "Column " + (index + 1) + "/" + data.attribute(index).name()); else dialog.add(last, list.toArray(), "Row " + (index + 1)); dialog.setLocationRelativeTo(GUIHelper.getParentComponent(table)); dialog.setVisible(true); }
From source file:adams.gui.visualization.instances.instancestable.JFreeChart.java
License:Open Source License
/** * Allows the user to generate a plot from either a row or a column. * * @param data the instances to use/* w ww .ja v a 2 s . co m*/ * @param isColumn whether the to use column or row * @param index the index of the row/column */ protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) { final List<Double> list; List<Double> tmp; GenericObjectEditorDialog setup; int i; final String title; SwingWorker worker; adams.flow.sink.JFreeChartPlot last; int numPoints; String newPoints; int col; int row; Object value; final SpreadSheet sheet; Row srow; boolean sorted; boolean asc; numPoints = isColumn ? data.numInstances() : data.numAttributes(); if (numPoints > MAX_POINTS) { newPoints = GUIHelper.showInputDialog(null, "More than " + MAX_POINTS + " data points to plot - enter sample size:", "" + numPoints); if (newPoints == null) return; if (!Utils.isInteger(newPoints)) return; if (Integer.parseInt(newPoints) != numPoints) numPoints = Integer.parseInt(newPoints); else numPoints = -1; } else { numPoints = -1; } // let user customize plot if (GUIHelper.getParentDialog(table) != null) setup = new GenericObjectEditorDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL); else setup = new GenericObjectEditorDialog(GUIHelper.getParentFrame(table), true); setup.setDefaultCloseOperation(GenericObjectEditorDialog.DISPOSE_ON_CLOSE); setup.getGOEEditor().setClassType(Actor.class); setup.getGOEEditor().setCanChangeClassInDialog(false); last = (adams.flow.sink.JFreeChartPlot) table.getLastSetup(getClass(), true, !isColumn); if (last == null) last = new adams.flow.sink.JFreeChartPlot(); setup.setCurrent(last); setup.setLocationRelativeTo(GUIHelper.getParentComponent(table)); setup.setVisible(true); if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION) return; last = (adams.flow.sink.JFreeChartPlot) setup.getCurrent(); table.addLastSetup(getClass(), true, !isColumn, last); // get data from instances tmp = new ArrayList<>(); sorted = false; asc = table.isAscending(); if (isColumn) { col = index + 1; sorted = (table.getSortColumn() == col); for (i = 0; i < table.getRowCount(); i++) { value = table.getValueAt(i, col); if ((value != null) && (Utils.isDouble(value.toString()))) tmp.add(Utils.toDouble(value.toString())); } } else { row = index; for (i = 0; i < data.numAttributes(); i++) { if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i)) tmp.add(data.instance(row).value(i)); } } if (numPoints > -1) { numPoints = Math.min(numPoints, tmp.size()); Collections.shuffle(tmp, new Random(1)); list = tmp.subList(0, numPoints); if (sorted) { Collections.sort(list); if (!asc) Collections.reverse(list); } } else { list = tmp; } // create new spreadsheet sheet = new DefaultSpreadSheet(); sheet.getHeaderRow().addCell("x").setContentAsString(isColumn ? "Row" : "Column"); sheet.getHeaderRow().addCell("y") .setContentAsString(isColumn ? data.attribute(index).name() : ("Row " + (index + 1))); for (i = 0; i < list.size(); i++) { srow = sheet.addRow(); srow.addCell("x").setContent((double) i + 1.0); srow.addCell("y").setContent(list.get(i)); } // generate plot if (isColumn) title = "Column " + (index + 1) + "/" + data.attribute(index).name(); else title = "Row " + (index + 1); last.getChart().setTitle(sheet.getColumnName(1)); worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { Flow flow = new Flow(); flow.setDefaultCloseOperation(BaseFrame.DISPOSE_ON_CLOSE); StorageValue sv = new StorageValue(); sv.setStorageName(new StorageName("values")); flow.add(sv); Object last = table.getLastSetup(JFreeChart.this.getClass(), true, !isColumn); adams.flow.sink.JFreeChartPlot plot = (adams.flow.sink.JFreeChartPlot) ((adams.flow.sink.JFreeChartPlot) last) .shallowCopy(); plot.setShortTitle(true); plot.setName(title); plot.setX(-2); plot.setY(-2); flow.add(plot); flow.setUp(); flow.getStorage().put(new StorageName("values"), sheet); flow.execute(); flow.wrapUp(); return null; } }; worker.execute(); }
From source file:adams.gui.visualization.instances.instancestable.SimplePlot.java
License:Open Source License
/** * Allows the user to generate a plot from either a row or a column. * * @param data the instances to use//w w w . j av a2s . co m * @param isColumn whether the to use column or row * @param index the index of the row/column */ protected void plot(final InstancesTable table, final Instances data, final boolean isColumn, int index) { final List<Double> list; List<Double> tmp; GenericObjectEditorDialog setup; int i; final String title; SwingWorker worker; adams.flow.sink.SimplePlot last; int numPoints; String newPoints; int col; int row; Object value; boolean sorted; boolean asc; numPoints = isColumn ? data.numInstances() : data.numAttributes(); if (numPoints > MAX_POINTS) { newPoints = GUIHelper.showInputDialog(null, "More than " + MAX_POINTS + " data points to plot - enter sample size:", "" + numPoints); if (newPoints == null) return; if (!Utils.isInteger(newPoints)) return; if (Integer.parseInt(newPoints) != numPoints) numPoints = Integer.parseInt(newPoints); else numPoints = -1; } else { numPoints = -1; } // let user customize plot if (GUIHelper.getParentDialog(table) != null) setup = new GenericObjectEditorDialog(GUIHelper.getParentDialog(table), ModalityType.DOCUMENT_MODAL); else setup = new GenericObjectEditorDialog(GUIHelper.getParentFrame(table), true); setup.setDefaultCloseOperation(GenericObjectEditorDialog.DISPOSE_ON_CLOSE); setup.getGOEEditor().setClassType(Actor.class); setup.getGOEEditor().setCanChangeClassInDialog(false); last = (adams.flow.sink.SimplePlot) table.getLastSetup(getClass(), true, !isColumn); if (last == null) { last = new adams.flow.sink.SimplePlot(); last.setNoToolTips(true); last.setMouseClickAction(new ViewDataClickAction()); } setup.setCurrent(last); setup.setLocationRelativeTo(GUIHelper.getParentComponent(table)); setup.setVisible(true); if (setup.getResult() != GenericObjectEditorDialog.APPROVE_OPTION) return; last = (adams.flow.sink.SimplePlot) setup.getCurrent(); table.addLastSetup(getClass(), true, !isColumn, last); // get data from instances tmp = new ArrayList<>(); sorted = false; asc = table.isAscending(); if (isColumn) { col = index + 1; sorted = (table.getSortColumn() == col); for (i = 0; i < table.getRowCount(); i++) { value = table.getValueAt(i, col); if ((value != null) && (Utils.isDouble(value.toString()))) tmp.add(Utils.toDouble(value.toString())); } } else { row = index; for (i = 0; i < data.numAttributes(); i++) { if (data.attribute(i).isNumeric() && !data.instance(row).isMissing(i)) tmp.add(data.instance(row).value(i)); } } if (numPoints > -1) { numPoints = Math.min(numPoints, tmp.size()); Collections.shuffle(tmp, new Random(1)); list = tmp.subList(0, numPoints); if (sorted) { Collections.sort(list); if (!asc) Collections.reverse(list); } } else { list = tmp; } // generate plot if (isColumn) title = "Column " + (index + 1) + "/" + data.attribute(index).name(); else title = "Row " + (index + 1); worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { Flow flow = new Flow(); flow.setDefaultCloseOperation(BaseFrame.DISPOSE_ON_CLOSE); StorageValue sv = new StorageValue(); sv.setStorageName(new StorageName("values")); flow.add(sv); ArrayToSequence a2s = new ArrayToSequence(); flow.add(a2s); MakePlotContainer mpc = new MakePlotContainer(); mpc.setPlotName(title); flow.add(mpc); Object last = table.getLastSetup(SimplePlot.this.getClass(), true, !isColumn); adams.flow.sink.SimplePlot plot = (adams.flow.sink.SimplePlot) ((adams.flow.sink.SimplePlot) last) .shallowCopy(); plot.setShortTitle(true); plot.setShowSidePanel(false); plot.setName(title); plot.setX(-2); plot.setY(-2); flow.add(plot); flow.setUp(); flow.getStorage().put(new StorageName("values"), list.toArray(new Double[list.size()])); flow.execute(); flow.wrapUp(); return null; } }; worker.execute(); }
From source file:adams.gui.visualization.instances.InstancesTable.java
License:Open Source License
/** * Exports the data./* w w w .ja v a2s . c o m*/ * * @param range what data to export */ protected void saveAs(TableRowRange range) { int retVal; AbstractFileSaver saver; File file; Instances original; Instances data; int[] selRows; int i; retVal = m_FileChooser.showSaveDialog(InstancesTable.this); if (retVal != WekaFileChooser.APPROVE_OPTION) return; saver = m_FileChooser.getWriter(); file = m_FileChooser.getSelectedFile(); original = getInstances(); switch (range) { case ALL: data = original; break; case SELECTED: data = new Instances(original, 0); selRows = getSelectedRows(); for (i = 0; i < selRows.length; i++) data.add((Instance) original.instance(getActualRow(selRows[i])).copy()); break; case VISIBLE: data = new Instances(original, 0); for (i = 0; i < getRowCount(); i++) data.add((Instance) original.instance(getActualRow(i)).copy()); break; default: throw new IllegalStateException("Unhandled range type: " + range); } try { saver.setFile(file); saver.setInstances(data); saver.writeBatch(); } catch (Exception ex) { GUIHelper.showErrorMessage(InstancesTable.this, "Failed to save data (" + range + ") to: " + file, ex); } }
From source file:adams.opt.optimise.genetic.fitnessfunctions.AttributeSelection.java
License:Open Source License
public double evaluate(OptData opd) { init();/* w w w .j a va 2 s. c o m*/ int cnt = 0; int[] weights = getWeights(opd); Instances newInstances = new Instances(getInstances()); for (int i = 0; i < getInstances().numInstances(); i++) { Instance in = newInstances.instance(i); cnt = 0; for (int a = 0; a < getInstances().numAttributes(); a++) { if (a == getInstances().classIndex()) continue; if (weights[cnt++] == 0) { in.setValue(a, 0); } else { in.setValue(a, in.value(a)); } } } Classifier newClassifier = null; try { newClassifier = (Classifier) OptionUtils.shallowCopy(getClassifier()); // evaluate classifier on data Evaluation evaluation = new Evaluation(newInstances); evaluation.crossValidateModel(newClassifier, newInstances, getFolds(), new Random(getCrossValidationSeed())); // obtain measure double measure = 0; if (getMeasure() == Measure.ACC) measure = evaluation.pctCorrect(); else if (getMeasure() == Measure.CC) measure = evaluation.correlationCoefficient(); else if (getMeasure() == Measure.MAE) measure = evaluation.meanAbsoluteError(); else if (getMeasure() == Measure.RAE) measure = evaluation.relativeAbsoluteError(); else if (getMeasure() == Measure.RMSE) measure = evaluation.rootMeanSquaredError(); else if (getMeasure() == Measure.RRSE) measure = evaluation.rootRelativeSquaredError(); else throw new IllegalStateException("Unhandled measure '" + getMeasure() + "'!"); measure = getMeasure().adjust(measure); return (measure); // process fitness } catch (Exception e) { getLogger().log(Level.SEVERE, "Error evaluating", e); } return 0; }