List of usage examples for weka.core Instance value
public double value(Attribute att);
From source file:lu.lippmann.cdb.lab.mds.ClassicMDS.java
License:Open Source License
public static void main(String[] args) throws Exception { final Instances ds = WekaDataAccessUtil.loadInstancesFromARFFOrCSVFile( //new File("./samples/csv/uci/zoo.csv")); new File("./samples/csv/test50bis.csv")); //new File("./samples/arff/UCI/cmc.arff")); //new File("./samples/csv/direct-marketing-bank-reduced.csv")); //new File("./samples/csv/bank.csv")); //new File("./samples/csv/preswissroll.csv")); //new File("./samples/csv/preswissroll-mod4.csv")); ds.setClassIndex(-1);// ww w . j a va2s . c o m final int N = ds.size(); final int M = ds.numAttributes(); SimpleMatrix dist = new SimpleMatrix(N, N); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { Instance xi = ds.instance(i); Instance xj = ds.instance(j); double d = 0, s = 0, a = 0, b = 0; for (int k = 1; k < M; k++) { s += xi.value(k) * xj.value(k); a += xi.value(k) * xi.value(k); b += xi.value(k) * xi.value(k); } d = 1 - s / (Math.sqrt(a) * Math.sqrt(b)); dist.set(i, j, d); dist.set(j, i, d); } } final MDSResult res = ClassicMDS.doMDSV1(ds, dist); JXPanel p2 = MDSViewBuilder.buildMDSViewFromDataSet(ds, res, 5000, null); p2.setPreferredSize(new Dimension(800, 600)); final JXFrame f = new JXFrame(); f.setPreferredSize(new Dimension(1024, 768)); final Container c = f.getContentPane(); c.add(p2); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JXFrame.EXIT_ON_CLOSE); System.out.println("Kruskal stress : =" + getKruskalStressFromMDSResult(res)); }
From source file:lu.lippmann.cdb.lab.mds.MDSViewBuilder.java
License:Open Source License
/** * //from www .j a v a 2 s . co m */ private static void buildFilteredSeries(final MDSResult mdsResult, final XYPlot xyPlot, final String... attrNameToUseAsPointTitle) throws Exception { final CollapsedInstances distMdsRes = mdsResult.getCInstances(); final Instances instances = distMdsRes.getInstances(); final SimpleMatrix coordinates = mdsResult.getCoordinates(); final Instances collapsedInstances = mdsResult.getCollapsedInstances(); int maxSize = 0; if (distMdsRes.isCollapsed()) { final List<Instances> clusters = distMdsRes.getCentroidMap().getClusters(); final int nbCentroids = clusters.size(); maxSize = clusters.get(0).size(); for (int i = 1; i < nbCentroids; i++) { final int currentSize = clusters.get(i).size(); if (currentSize > maxSize) { maxSize = currentSize; } } } Attribute clsAttribute = null; int nbClass = 1; if (instances.classIndex() != -1) { clsAttribute = instances.classAttribute(); nbClass = clsAttribute.numValues(); } final XYSeriesCollection dataset = (XYSeriesCollection) xyPlot.getDataset(); final int fMaxSize = maxSize; final List<XYSeries> lseries = new ArrayList<XYSeries>(); //No class : add one dummy serie if (nbClass <= 1) { lseries.add(new XYSeries("Serie #1", false)); } else { //Some class : add one serie per class for (int i = 0; i < nbClass; i++) { lseries.add(new XYSeries(clsAttribute.value(i), false)); } } dataset.removeAllSeries(); /** * Initialize filtered series */ final List<Instances> filteredInstances = new ArrayList<Instances>(); for (int i = 0; i < lseries.size(); i++) { filteredInstances.add(new Instances(collapsedInstances, 0)); } final Map<Tuple<Integer, Integer>, Integer> correspondanceMap = new HashMap<Tuple<Integer, Integer>, Integer>(); for (int i = 0; i < collapsedInstances.numInstances(); i++) { final Instance oInst = collapsedInstances.instance(i); int indexOfSerie = 0; if (oInst.classIndex() != -1) { if (distMdsRes.isCollapsed()) { indexOfSerie = getStrongestClass(i, distMdsRes); } else { indexOfSerie = (int) oInst.value(oInst.classAttribute()); } } lseries.get(indexOfSerie).add(coordinates.get(i, 0), coordinates.get(i, 1)); filteredInstances.get(indexOfSerie).add(oInst); if (distMdsRes.isCollapsed()) { correspondanceMap.put(new Tuple<Integer, Integer>(indexOfSerie, filteredInstances.get(indexOfSerie).numInstances() - 1), i); } } final List<Paint> colors = new ArrayList<Paint>(); for (final XYSeries series : lseries) { dataset.addSeries(series); } if (distMdsRes.isCollapsed()) { final XYLineAndShapeRenderer xyRenderer = new XYLineAndShapeRenderer(false, true) { private static final long serialVersionUID = -6019883886470934528L; @Override public void drawItem(Graphics2D g2, XYItemRendererState state, java.awt.geom.Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (distMdsRes.isCollapsed()) { final Integer centroidIndex = correspondanceMap .get(new Tuple<Integer, Integer>(series, item)); final Instances cluster = distMdsRes.getCentroidMap().getClusters().get(centroidIndex); int size = cluster.size(); final int shapeSize = (int) (MAX_POINT_SIZE * size / fMaxSize + 1); final double x1 = plot.getDataset().getX(series, item).doubleValue(); final double y1 = plot.getDataset().getY(series, item).doubleValue(); Map<Object, Integer> mapRepartition = new HashMap<Object, Integer>(); mapRepartition.put("No class", size); if (cluster.classIndex() != -1) { mapRepartition = WekaDataStatsUtil.getClassRepartition(cluster); } final RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); final RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); final double fx = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); final double fy = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); setSeriesShape(series, new Ellipse2D.Double(-shapeSize / 2, -shapeSize / 2, shapeSize, shapeSize)); super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); //Draw pie if (ENABLE_PIE_SHART) { createPieChart(g2, (int) (fx - shapeSize / 2), (int) (fy - shapeSize / 2), shapeSize, mapRepartition, size, colors); } } else { super.drawItem(g2, state, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState, pass); } } }; xyPlot.setRenderer(xyRenderer); } final XYToolTipGenerator gen = new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { if (distMdsRes.isCollapsed()) { final StringBuilder res = new StringBuilder("<html>"); final Integer centroidIndex = correspondanceMap.get(new Tuple<Integer, Integer>(series, item)); final Instance centroid = distMdsRes.getCentroidMap().getCentroids().get(centroidIndex); final Instances cluster = distMdsRes.getCentroidMap().getClusters().get(centroidIndex); //Set same class index for cluster than for original instances //System.out.println("Cluster index = " + cluster.classIndex() + "/" + instances.classIndex()); cluster.setClassIndex(instances.classIndex()); Map<Object, Integer> mapRepartition = new HashMap<Object, Integer>(); mapRepartition.put("No class", cluster.size()); if (cluster.classIndex() != -1) { mapRepartition = WekaDataStatsUtil.getClassRepartition(cluster); } res.append(InstanceFormatter.htmlFormat(centroid, false)).append("<br/>"); for (final Map.Entry<Object, Integer> entry : mapRepartition.entrySet()) { if (entry.getValue() != 0) { res.append("Class :<b>'" + StringEscapeUtils.escapeHtml(entry.getKey().toString()) + "</b>' -> " + entry.getValue()).append("<br/>"); } } res.append("</html>"); return res.toString(); } else { //return InstanceFormatter.htmlFormat(filteredInstances.get(series).instance(item),true); return InstanceFormatter.shortHtmlFormat(filteredInstances.get(series).instance(item)); } } }; final Shape shape = new Ellipse2D.Float(0f, 0f, MAX_POINT_SIZE, MAX_POINT_SIZE); ((XYLineAndShapeRenderer) xyPlot.getRenderer()).setUseOutlinePaint(true); for (int p = 0; p < nbClass; p++) { xyPlot.getRenderer().setSeriesToolTipGenerator(p, gen); ((XYLineAndShapeRenderer) xyPlot.getRenderer()).setLegendShape(p, shape); xyPlot.getRenderer().setSeriesOutlinePaint(p, Color.BLACK); } for (int ii = 0; ii < nbClass; ii++) { colors.add(xyPlot.getRenderer().getItemPaint(ii, 0)); } if (attrNameToUseAsPointTitle.length > 0) { final Attribute attrToUseAsPointTitle = instances.attribute(attrNameToUseAsPointTitle[0]); if (attrToUseAsPointTitle != null) { final XYItemLabelGenerator lg = new XYItemLabelGenerator() { @Override public String generateLabel(final XYDataset dataset, final int series, final int item) { return filteredInstances.get(series).instance(item).stringValue(attrToUseAsPointTitle); } }; xyPlot.getRenderer().setBaseItemLabelGenerator(lg); xyPlot.getRenderer().setBaseItemLabelsVisible(true); } } }
From source file:lu.lippmann.cdb.lab.mds.MDSViewBuilder.java
License:Open Source License
/** * /*from w w w .java2 s .c o m*/ * @param clusters */ public static void buildKMeansChart(final List<Instances> clusters) { final XYSeriesCollection dataset = new XYSeriesCollection(); final JFreeChart chart = ChartFactory.createScatterPlot("", // title "X", "Y", // axis labels dataset, // dataset PlotOrientation.VERTICAL, true, // legend? yes true, // tooltips? yes false // URLs? no ); final XYPlot xyPlot = (XYPlot) chart.getPlot(); ((NumberAxis) xyPlot.getDomainAxis()).setTickUnit(new NumberTickUnit(2.0)); ((NumberAxis) xyPlot.getRangeAxis()).setTickUnit(new NumberTickUnit(2.0)); Attribute clsAttribute = null; int nbClass = 1; Instances cluster0 = clusters.get(0); if (cluster0.classIndex() != -1) { clsAttribute = cluster0.classAttribute(); nbClass = clsAttribute.numValues(); } if (nbClass <= 1) { dataset.addSeries(new XYSeries("Serie #1", false)); } else { for (int i = 0; i < nbClass; i++) { dataset.addSeries(new XYSeries(clsAttribute.value(i), false)); } } final XYToolTipGenerator gen = new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { return "TODO"; } }; for (int i = 0; i < nbClass; i++) { dataset.getSeries(i).clear(); xyPlot.getRenderer().setSeriesToolTipGenerator(i, gen); } final int nbClusters = clusters.size(); for (int i = 0; i < nbClusters; i++) { Instances instances = clusters.get(i); final int nbInstances = instances.numInstances(); for (int j = 0; j < nbInstances; j++) { final Instance oInst = instances.instance(j); dataset.getSeries(i).add(oInst.value(0), oInst.value(1)); } } final TitledBorder titleBorder = new TitledBorder("Kmeans of projection"); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setMouseWheelEnabled(true); chartPanel.setPreferredSize(new Dimension(1200, 900)); chartPanel.setBorder(titleBorder); chartPanel.setBackground(Color.WHITE); JXFrame frame = new JXFrame(); frame.getContentPane().add(chartPanel); frame.setVisible(true); frame.pack(); }
From source file:lu.lippmann.cdb.lab.mds.UniversalMDS.java
License:Open Source License
public JXPanel buildMDSViewFromDataSet(Instances ds, MDSTypeEnum type) throws Exception { final XYSeriesCollection dataset = new XYSeriesCollection(); final JFreeChart chart = ChartFactory.createScatterPlot("", // title "X", "Y", // axis labels dataset, // dataset PlotOrientation.VERTICAL, true, // legend? yes true, // tooltips? yes false // URLs? no );//from w w w . j a v a 2 s . c om final XYPlot xyPlot = (XYPlot) chart.getPlot(); chart.setTitle(type.name() + " MDS"); Attribute clsAttribute = null; int nbClass = 1; if (ds.classIndex() != -1) { clsAttribute = ds.classAttribute(); nbClass = clsAttribute.numValues(); } final List<XYSeries> lseries = new ArrayList<XYSeries>(); if (nbClass <= 1) { lseries.add(new XYSeries("Serie #1", false)); } else { for (int i = 0; i < nbClass; i++) { lseries.add(new XYSeries(clsAttribute.value(i), false)); } } dataset.removeAllSeries(); /** * Initialize filtered series */ final List<Instances> filteredInstances = new ArrayList<Instances>(); for (int i = 0; i < lseries.size(); i++) { filteredInstances.add(new Instances(ds, 0)); } for (int i = 0; i < ds.numInstances(); i++) { final Instance oInst = ds.instance(i); int indexOfSerie = 0; if (oInst.classIndex() != -1) { indexOfSerie = (int) oInst.value(oInst.classAttribute()); } lseries.get(indexOfSerie).add(coordinates[i][0], coordinates[i][1]); filteredInstances.get(indexOfSerie).add(oInst); } final List<Paint> colors = new ArrayList<Paint>(); for (final XYSeries series : lseries) { dataset.addSeries(series); } final XYToolTipGenerator gen = new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { return InstanceFormatter.htmlFormat(filteredInstances.get(series).instance(item), true); } }; final Shape shape = new Ellipse2D.Float(0f, 0f, 5f, 5f); ((XYLineAndShapeRenderer) xyPlot.getRenderer()).setUseOutlinePaint(true); for (int p = 0; p < nbClass; p++) { xyPlot.getRenderer().setSeriesToolTipGenerator(p, gen); ((XYLineAndShapeRenderer) xyPlot.getRenderer()).setLegendShape(p, shape); xyPlot.getRenderer().setSeriesOutlinePaint(p, Color.BLACK); } for (int ii = 0; ii < nbClass; ii++) { colors.add(xyPlot.getRenderer().getItemPaint(ii, 0)); } final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setMouseWheelEnabled(true); chartPanel.setPreferredSize(new Dimension(1200, 900)); chartPanel.setBorder(new TitledBorder("MDS Projection")); chartPanel.setBackground(Color.WHITE); final JXPanel allPanel = new JXPanel(); allPanel.setLayout(new BorderLayout()); allPanel.add(chartPanel, BorderLayout.CENTER); return allPanel; }
From source file:machinelearning.KnnClassifier.java
public double classifyInstance(Instance instance, int k) { int size = trainingData.numInstances(); int attributes = trainingData.numAttributes() - 1; float dist;/*w w w . j a v a2 s . c o m*/ Map<Float, Instance> neighbors = new TreeMap<>(); Instance test; for (int i = 0; i < size; i++) { dist = 0; test = trainingData.instance(i); for (int j = 0; j < attributes; j++) { if (test.attribute(j).isNominal()) { if (instance.attribute(j).equals(test.attribute(j))) dist++; } else dist += Math.abs(test.value(test.attribute(j)) - instance.value(test.attribute(j))); } neighbors.put(dist, test); } return findMostCommon(neighbors, k); }
From source file:machinelearningcw.EnhancedLinearPerceptron.java
@Override public double classifyInstance(Instance instnc) throws Exception { double y = 0; //create a new instance so it doesnt change the orginal dataset Instance newInstance = new DenseInstance(instnc); if (setStandardiseAttributes) { standardizeAtrrbutes(newInstance); }// www.java2 s . co m for (int i = 0; i < newInstance.numAttributes() - 1; i++) { y += w[i] * (newInstance.value(i)); } return (y >= 0) ? 1 : 0; }
From source file:machinelearningcw.EnhancedLinearPerceptron.java
public double offlinePerceptron(Instances ins) { double error_count = 0;//count the number of errors double changeinWeights[]; for (int h = 0; h < numberofiterations; h++) { changeinWeights = new double[ins.numAttributes() - 1]; //error_count = 0; for (Instance instance : ins) { double y = 0; for (int i = 0; i < ins.numAttributes() - 1; i++) { y += w[i] * (instance.value(i)); }/*from w w w. j a va 2s. c om*/ double match; if (y >= 0) { match = 1; } else { match = 0; } double difference = instance.classValue() - match; for (int j = 0; j < ins.numAttributes() - 1; j++) { changeinWeights[j] = changeinWeights[j] + (0.5 * learning_rate) * ((difference) * instance.value(j)); } error_count += (difference * difference); } /* for (int j = 0; j < ins.numAttributes() - 1; j++) { System.out.print("w[" + j + "]: " + changeinWeights[j] + "|"); } System.out.println("");*/ //update all the weights at the end for (int j = 0; j < w.length; j++) { w[j] += changeinWeights[j]; } } error_count = error_count / numberofiterations;// average error count return error_count; }
From source file:machinelearningcw.EnhancedLinearPerceptron.java
public double perceptron(Instances ins) { double error_count = 0;//count the number of errors for (int h = 0; h < numberofiterations; h++)//stopping condition {/*from w ww .j a v a 2 s. c o m*/ error_count = 0; for (Instance instance : ins) { double y = 0; for (int i = 0; i < ins.numAttributes() - 1; i++) { y += w[i] * (instance.value(i)); } // System.out.println(y); double match; if (y >= 0) { match = 1; } else { match = 0; } double difference = instance.classValue() - match; // System.out.println(match); for (int j = 0; j < ins.numAttributes() - 1; j++) { w[j] = w[j] + 0.5 * learning_rate * ((difference) * instance.value(j)); // System.out.print(w[j] + ", "); } error_count += difference * difference; } } return error_count; }
From source file:machinelearningcw.EnhancedLinearPerceptron.java
public Instance standardizeAtrrbutes(Instance ins) { for (int n = 0; n < ins.numAttributes() - 1; n++) { double x = ((ins.value(n) - means[n]) / std[n]); ins.setValue(n, x);//from ww w .j a v a2s . c om } return ins; }
From source file:machinelearningcw.EnhancedLinearPerceptron.java
public Instances standardizeAtrrbutes(Instances ins) { for (Instance i : ins) { for (int n = 0; n < i.numAttributes() - 1; n++) { double x = ((i.value(n) - means[n]) / std[n]); i.setValue(n, x);//ww w . j ava 2s . c o m } } return ins; }