List of usage examples for weka.core Instance setValue
public void setValue(Attribute att, String value);
From source file:cezeri.utils.FactoryInstance.java
public static Instances getSubsetData(Instances data, String[] attList) { Instances temp = new Instances(data); for (int i = 0; i < data.numAttributes(); i++) { if (!temp.attribute(0).equals(temp.classAttribute())) { temp.deleteAttributeAt(0);/*w w w . ja va 2s.c o m*/ } } double[][] m = new double[attList.length + 1][data.numInstances()]; for (int i = 0; i < attList.length; i++) { int n = attList.length - 1 - i; String str = attList[n]; Attribute t = data.attribute(str); double[] d = data.attributeToDoubleArray(t.index()); m[n] = d; temp.insertAttributeAt(t, 0); } m[attList.length] = data.attributeToDoubleArray(data.classIndex()); m = CMatrix.getInstance(m).transpose().get2DArrayDouble(); FastVector att = new FastVector(); for (int i = 0; i < temp.numAttributes(); i++) { att.addElement(temp.attribute(i)); } Instances ret = new Instances(temp.relationName(), att, m.length); for (int i = 0; i < m.length; i++) { Instance ins = new Instance(m[0].length); for (int j = 0; j < m[0].length; j++) { ins.setValue(j, m[i][j]); } ret.add(ins); } ret.setClassIndex(temp.classIndex()); return ret; }
From source file:clasificacion.Clasificacion.java
public String clasificar(String[] testCases) throws Exception { String ruta = "nursery_model.model"; InputStream classModelStream; classModelStream = getClass().getResourceAsStream(ruta); //classModel = (Classifier)SerializationHelper.read(classModelStream); Classifier clasify = (Classifier) SerializationHelper.read(classModelStream); FastVector parents = new FastVector(); parents.addElement("usual"); parents.addElement("pretentious"); parents.addElement("great_pret"); Attribute _parent = new Attribute("parents", parents); FastVector nurs = new FastVector(); nurs.addElement("proper"); nurs.addElement("less_proper"); nurs.addElement("improper"); nurs.addElement("critical"); nurs.addElement("very_crit"); Attribute _has_nurs = new Attribute("has_nurs", nurs); FastVector form = new FastVector(); form.addElement("complete"); form.addElement("completed"); form.addElement("incomplete"); form.addElement("foster"); Attribute _form = new Attribute("form", form); FastVector children = new FastVector(); children.addElement("1"); children.addElement("2"); children.addElement("3"); children.addElement("more"); Attribute _children = new Attribute("children", children); FastVector housing = new FastVector(); housing.addElement("convenient"); housing.addElement("less_conv"); housing.addElement("critical"); Attribute _housing = new Attribute("housing", housing); FastVector finance = new FastVector(); finance.addElement("convenient"); finance.addElement("inconv"); Attribute _finance = new Attribute("finance", finance); FastVector social = new FastVector(); social.addElement("nonprob"); social.addElement("slightly_prob"); social.addElement("problematic"); Attribute _social = new Attribute("social", social); FastVector health = new FastVector(); health.addElement("recommended"); health.addElement("priority"); health.addElement("not_recom"); Attribute _health = new Attribute("health", health); FastVector Class = new FastVector(); Class.addElement("not_recom"); Class.addElement("recommend"); Class.addElement("very_recom"); Class.addElement("priority"); Class.addElement("spec_prior"); Attribute _Class = new Attribute("class", Class); FastVector atributos = new FastVector(9); atributos.addElement(_parent);// www .j av a 2 s . com atributos.addElement(_has_nurs); atributos.addElement(_form); atributos.addElement(_children); atributos.addElement(_housing); atributos.addElement(_finance); atributos.addElement(_social); atributos.addElement(_health); atributos.addElement(_Class); ArrayList<Attribute> atributs = new ArrayList<>(); atributs.add(_parent); atributs.add(_has_nurs); atributs.add(_form); atributs.add(_children); atributs.add(_housing); atributs.add(_finance); atributs.add(_social); atributs.add(_health); atributs.add(_Class); //Aqu se crea la instacia, que tiene todos los atributos del modelo Instances dataTest = new Instances("TestCases", atributos, 1); dataTest.setClassIndex(8); Instance setPrueba = new Instance(9); int index = -1; for (int i = 0; i < 8; i++) { index = atributs.get(i).indexOfValue(testCases[i]); //System.out.println(i + " " + atributs.get(i) + " " + index + " " + testCases[i]); setPrueba.setValue(atributs.get(i), index); } //Agregando el set que se desea evaluar. dataTest.add(setPrueba); //Realizando la Prediccin //La instancia es la 0 debido a que es la unica que se encuentra. double valorP = clasify.classifyInstance(dataTest.instance(0)); //get the name of the class value String prediccion = dataTest.classAttribute().value((int) valorP); return prediccion; }
From source file:classes.AbdoAgglomerativeClusterer.java
/** * calculates the with-in-cluster variance as the sum squares of differences * between instances contained in the cluster and its mean divided by * cluster size/*from www . j av a 2s . c om*/ * * @param cluster * @return */ double calcWithinVariance(Vector<Integer> cluster) { double variance = 0.0; double[] fValues1 = new double[m_instances.numAttributes()]; for (int i = 0; i < cluster.size(); i++) { Instance instance = m_instances.instance(cluster.elementAt(i)); for (int j = 0; j < m_instances.numAttributes(); j++) { fValues1[j] += instance.value(j); } } for (int j = 0; j < m_instances.numAttributes(); j++) { fValues1[j] /= cluster.size(); } // set up two instances for distance function Instance centroid = (Instance) m_instances.instance(cluster.elementAt(0)).copy(); for (int j = 0; j < m_instances.numAttributes(); j++) { centroid.setValue(j, fValues1[j]); } for (int i = 0; i < cluster.size(); i++) { double temp = 0; Instance instance = m_instances.instance(cluster.elementAt(i)); for (int j = 0; j < m_instances.numAttributes(); j++) { temp += (instance.value(j) - centroid.value(j)); } variance += temp * temp; } return variance / cluster.size(); }
From source file:cluster.ABC.ClusterUtils.java
License:Open Source License
/** Normalizes the values of a normal Instance in L2 norm * * @author Sugato Basu/*www . java 2s.com*/ * @param inst Instance to be normalized */ public static void normalizeInstance(Instance inst) throws Exception { double norm = 0; double values[] = inst.toDoubleArray(); if (inst instanceof SparseInstance) { System.err.println("Is SparseInstance, using normalizeSparseInstance function instead"); normalizeSparseInstance(inst); } for (int i = 0; i < values.length; i++) { if (i != inst.classIndex()) { // don't normalize the class index norm += values[i] * values[i]; } } norm = Math.sqrt(norm); for (int i = 0; i < values.length; i++) { if (i != inst.classIndex()) { // don't normalize the class index values[i] /= norm; } } for (int i = 0; i < inst.numAttributes(); i++) { inst.setValue(i, values[i]); } //inst.setValueArray(values); }
From source file:cluster.ABC.ClusterUtils.java
License:Open Source License
/** This function divides every attribute value in an instance by * the instance weight -- useful to find the mean of a cluster in * Euclidean space // w ww. j a v a 2 s. c o m * @param inst Instance passed in for normalization (destructive update) */ public static void normalizeByWeight(Instance inst) { double weight = inst.weight(); if (inst instanceof SparseInstance) { for (int i = 0; i < inst.numValues(); i++) { inst.setValueSparse(i, inst.valueSparse(i) / weight); } } else if (!(inst instanceof SparseInstance)) { for (int i = 0; i < inst.numAttributes(); i++) { inst.setValue(i, inst.value(i) / weight); } } }
From source file:cn.ict.zyq.bestConf.bestConf.BestConf.java
License:Open Source License
public Instances loadPropertiesAsInstancesPre(String Path) { HashMap<String, String> pmap = null; try {/*from ww w . j a va 2 s. co m*/ pmap = Yaml.loadType(new FileInputStream(yamlPath), HashMap.class); } catch (FileNotFoundException e) { e.printStackTrace(); } atts = new ArrayList<Attribute>(); Instance dfIns = new DenseInstance(pmap.size()); int pos = 0; double[] vals = new double[pmap.size()]; for (Map.Entry<String, String> ent : pmap.entrySet()) { try { double val = Double.valueOf(String.valueOf(ent.getValue())); vals[pos] = val; Properties p1 = new Properties(); double upper, lower; if (val != 0) { upper = val * (1. + 0.5); lower = val * (1. - 0.5); } else { lower = val; upper = 1; } p1.setProperty("range", "[" + String.valueOf(lower) + "," + String.valueOf(upper) + "]"); ProtectedProperties prop1 = new ProtectedProperties(p1); atts.add(new Attribute(String.valueOf(ent.getKey()), prop1)); pos++; } catch (Exception e) { } } Instances dfProp = new Instances("DefaultConfig", atts, 1); dfProp.add(dfIns); dfIns.setDataset(dfProp); for (int i = 0; i < pos; i++) { dfIns.setValue(atts.get(i), vals[i]); //System.err.println(atts.get(i)+":"+vals[i]); } return dfProp; }
From source file:cn.ict.zyq.bestConf.bestConf.BestConf.java
License:Open Source License
public Instances loadPropertiesAsInstances(String Path) { HashMap<String, String> pmap = null; HashMap rangeMap = null;/*w ww. j a va 2 s . c om*/ try { pmap = Yaml.loadType(new FileInputStream(yamlPath), HashMap.class); rangeMap = Yaml.loadType(new FileInputStream(yamlPath + "_range"), HashMap.class); } catch (FileNotFoundException e) { e.printStackTrace(); } atts = new ArrayList<Attribute>(); int pos = 0; double[] vals = new double[pmap.size()]; Object range = null; for (Map.Entry<String, String> ent : pmap.entrySet()) { try { double val = Double.valueOf(String.valueOf(ent.getValue())); vals[pos] = val; Properties p1 = new Properties(); range = rangeMap.get(ent.getKey()); if (range != null) { String list = (String) range; if (list.indexOf('[') == -1 && list.indexOf('(') == -1) throw new Exception("No Range for You" + ent.getKey()); p1.setProperty("range", list.trim()); } else { double upper, lower; if (val != 0) { upper = val * (1. + 0.5); lower = val * (1. - 0.5); } else { lower = val; upper = 1; } p1.setProperty("range", "[" + String.valueOf(lower) + "," + String.valueOf(upper) + "]"); } ProtectedProperties prop1 = new ProtectedProperties(p1); atts.add(new Attribute(String.valueOf(ent.getKey()), prop1)); pos++; } catch (Exception e) { } } Instances dfProp = new Instances("DefaultConfig", atts, 1); Instance dfIns = new DenseInstance(atts.size()); for (int i = 0; i < pos; i++) { dfIns.setValue(atts.get(i), vals[i]); //System.err.println(atts.get(i)+":"+vals[i]); } dfProp.add(dfIns); dfIns.setDataset(dfProp); return dfProp; }
From source file:cn.ict.zyq.bestConf.cluster.Main.AutoTestAdjust.java
License:Open Source License
public Instances runExp(Instances samplePoints, String perfAttName) { Instances retVal = null;//from ww w .jav a 2 s .com if (samplePoints.attribute(perfAttName) == null) { Attribute performance = new Attribute(perfAttName); samplePoints.insertAttributeAt(performance, samplePoints.numAttributes()); } int pos = samplePoints.numInstances(); int count = 0; for (int i = 0; i < pos; i++) { Instance ins = samplePoints.get(i); HashMap hm = new HashMap(); int tot = 0; for (int j = 0; j < ins.numAttributes(); j++) { hm.put(ins.attribute(j).name(), ins.value(ins.attribute(j))); } boolean testRet; if (Double.isNaN(ins.value(ins.attribute(ins.numAttributes() - 1)))) { testRet = this.startTest(hm, i, isInterrupt); double y = 0; if (!testRet) {// the setting does not work, we skip it y = -1; count++; if (count >= targetTestErrorNum) { System.out.println( "There must be somthing wrong with the system. Please check and restart....."); System.exit(1); } } else { y = getPerformanceByType(performanceType); count = 0; } ins.setValue(samplePoints.numAttributes() - 1, y); writePerfstoFile(ins); } else { continue; } } retVal = samplePoints; retVal.setClassIndex(retVal.numAttributes() - 1); return retVal; }
From source file:cn.ict.zyq.bestConf.cluster.Main.AutoTestAdjust.java
License:Open Source License
@Override public Instances collectPerfs(Instances samplePoints, String perfAttName) { Instances retVal = null;//from w ww . ja v a 2 s . c om if (samplePoints.attribute(perfAttName) == null) { Attribute performance = new Attribute(perfAttName); samplePoints.insertAttributeAt(performance, samplePoints.numAttributes()); } File perfFolder = new File(perfsfilepath); int tot = 0; if (perfFolder.exists()) { //let's get all the name set for the sample points Iterator<Instance> itr = samplePoints.iterator(); TreeSet<String> insNameSet = new TreeSet<String>(); HashMap<String, Integer> mapping = new HashMap<String, Integer>(); int pos = 0; while (itr.hasNext()) { String mdstr = getMD5(itr.next()); insNameSet.add(mdstr); mapping.put(mdstr, new Integer(pos++)); } //now we collect File[] perfFiles = perfFolder.listFiles(new PerfsFileFilter(insNameSet)); tot = perfFiles.length; if (tot > 0) isInterrupt = true; for (int i = 0; i < tot; i++) { Instance ins = samplePoints.get(mapping.get(perfFiles[i].getName())); double[] results = getPerf(perfFiles[i].getAbsolutePath()); if (results != null) { ins.setValue(samplePoints.numAttributes() - 1, results[0]); } } } retVal = samplePoints; retVal.setClassIndex(retVal.numAttributes() - 1); System.out.println("Total number of collected performances is : " + tot); return retVal; }
From source file:cn.ict.zyq.bestConf.COMT2.Branch2.java
License:Open Source License
public Instance maxPoint(Instances dataset) throws Exception { Instance max = new DenseInstance(dataset.numAttributes()); max.setDataset(dataset);/*www . jav a 2s. c o m*/ double[] combinedCoefs = null; int len = 0; for (PreConstructedLinearModel model : linearModelList) { //initialization if (combinedCoefs == null) { len = model.coefficients().length; combinedCoefs = new double[len]; for (int i = 0; i < len; i++) combinedCoefs[i] = 0; } for (int i = 0; i < len; i++) combinedCoefs[i] += model.coefficients()[i]; } //the max value is obtained at ends of a range for (Map.Entry<Attribute, Range<Double>> ent : rangeMap.entrySet()) { int attIdx = ent.getKey().index(); if (combinedCoefs[attIdx] > 0) { //use the upper bound if (ent.getValue().hasUpperBound()) max.setValue(attIdx, ent.getValue().upperEndpoint()); } else if (combinedCoefs[attIdx] < 0) { //use the lower bound if (ent.getValue().hasLowerBound()) max.setValue(attIdx, ent.getValue().lowerEndpoint()); } } //now we set the predicted values double y = 0; for (PreConstructedLinearModel model : linearModelList) { y += model.classifyInstance(max); } y /= linearModelList.size(); max.setClassValue(y); return max; }