List of usage examples for weka.core Instance setValue
public void setValue(Attribute att, String value);
From source file:mulan.transformations.multiclass.Ignore.java
License:Open Source License
/** * Transforms a multi-label example with a single annotation to a * single-label example and ignores multi-label example with more * annotations/* w w w. j a v a 2s .com*/ * * @param instance a multi-label example * @return a list that is either empty or contains the transformed * single-label example */ List<Instance> transformInstance(Instance instance) { List<Instance> result = new ArrayList<Instance>(); int indexOfSingleLabel = -1; int counter = 0; for (int labelCounter = 0; labelCounter < numOfLabels; labelCounter++) { int index = labelIndices[labelCounter]; if (instance.attribute(index).value((int) instance.value(index)).equals("1")) { counter++; indexOfSingleLabel = labelCounter; } if (counter > 1) { break; } } if (counter > 1 || counter == 0) { return result; } Instance transformedInstance; try { transformedInstance = RemoveAllLabels.transformInstance(instance, labelIndices); transformedInstance.setDataset(null); transformedInstance.insertAttributeAt(transformedInstance.numAttributes()); transformedInstance.setValue(transformedInstance.numAttributes() - 1, indexOfSingleLabel); result.add(transformedInstance); } catch (Exception ex) { Logger.getLogger(Ignore.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:mulan.transformations.multiclass.SelectBasedOnFrequency.java
License:Open Source License
/** * Transforms a multi-label example to a list containing a single-label * multi-class example by selecting the most/least frequent label in the * training set/*from w ww . ja va 2 s . c o m*/ * * @param instance * @return */ List<Instance> transformInstance(Instance instance) { int value = labelOccurance[0]; int labelSelected = 0; for (int counter = 1; counter < numOfLabels; counter++) { if (instance.attribute(labelIndices[counter]).value((int) instance.value(labelIndices[counter])) .equals("1")) { boolean test = false; switch (type) { case MIN: test = labelOccurance[counter] < value ? true : false; break; case MAX: test = labelOccurance[counter] > value ? true : false; break; } if (test) { value = labelOccurance[counter]; labelSelected = counter; } } } Instance transformed = null; try { transformed = RemoveAllLabels.transformInstance(instance, labelIndices); transformed.setDataset(null); transformed.insertAttributeAt(transformed.numAttributes()); transformed.setValue(transformed.numAttributes() - 1, labelSelected); } catch (Exception ex) { Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, ex); } List<Instance> result = new ArrayList<Instance>(); result.add(transformed); return result; }
From source file:mulan.transformations.multiclass.SelectRandom.java
License:Open Source License
/** * Transforms a multi-label example to a list containing a single-label * multi-class example by randomly selecting one of the labels * //ww w. j a v a 2 s. c o m * @param instance the multi-label example * @return the list with the single-label multi-class example */ List<Instance> transformInstance(Instance instance) { ArrayList<Integer> labels = new ArrayList<Integer>(); for (int counter = 0; counter < numOfLabels; counter++) { if (instance.attribute(labelIndices[counter]).value((int) instance.value(labelIndices[counter])) .equals("1")) { labels.add(counter); } } int randomLabel = labels.get((int) (Math.random() * labels.size())); Instance transformed = null; try { transformed = RemoveAllLabels.transformInstance(instance, labelIndices); transformed.setDataset(null); transformed.insertAttributeAt(transformed.numAttributes()); transformed.setValue(transformed.numAttributes() - 1, randomLabel); } catch (Exception ex) { Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, ex); } List<Instance> result = new ArrayList<Instance>(); result.add(transformed); return result; }
From source file:mulan.transformations.PT6Transformation.java
License:Open Source License
public Instances transformInstances(MultiLabelInstances mlData) throws Exception { int numLabels = mlData.getNumLabels(); labelIndices = mlData.getLabelIndices(); // remove all labels Instances transformed = RemoveAllLabels.transformInstances(mlData); // add at the end an attribute with values the label names ArrayList<String> labelNames = new ArrayList<String>(numLabels); for (int counter = 0; counter < numLabels; counter++) { labelNames.add(mlData.getDataSet().attribute(labelIndices[counter]).name()); }//from w w w .j av a2s . com Attribute attrLabel = new Attribute("Label", labelNames); transformed.insertAttributeAt(attrLabel, transformed.numAttributes()); // and at the end a binary attribute ArrayList<String> binaryValues = new ArrayList<String>(2); binaryValues.add("0"); binaryValues.add("1"); Attribute classAttr = new Attribute("Class", binaryValues); transformed.insertAttributeAt(classAttr, transformed.numAttributes()); // add instances transformed = new Instances(transformed, 0); transformed.setClassIndex(transformed.numAttributes() - 1); Instances data = mlData.getDataSet(); for (int instanceIndex = 0; instanceIndex < data.numInstances(); instanceIndex++) { for (int labelCounter = 0; labelCounter < numLabels; labelCounter++) { Instance temp; temp = RemoveAllLabels.transformInstance(data.instance(instanceIndex), labelIndices); temp.setDataset(null); temp.insertAttributeAt(temp.numAttributes()); temp.insertAttributeAt(temp.numAttributes()); temp.setDataset(transformed); temp.setValue(temp.numAttributes() - 2, (String) labelNames.get(labelCounter)); if (data.attribute(labelIndices[labelCounter]) .value((int) data.instance(instanceIndex).value(labelIndices[labelCounter])).equals("1")) { temp.setValue(temp.numAttributes() - 1, "1"); } else { temp.setValue(temp.numAttributes() - 1, "0"); } transformed.add(temp); } } return transformed; }
From source file:mulan.transformations.regression.SingleTargetTransformation.java
License:Open Source License
/** * Remove all target attributes except labelToKeep * /*from w ww . ja v a 2 s . com*/ * @param instance the instance to be transformed * @param targetToKeep the target to keep * @return transformed Instance */ public Instance transformInstance(Instance instance, int targetToKeep) { Instance transformedInstance; remove.input(instance); transformedInstance = remove.output(); add.input(transformedInstance); transformedInstance = add.output(); transformedInstance.setDataset(shell); int[] targetIndices = data.getLabelIndices(); transformedInstance.setValue(shell.numAttributes() - 1, instance.value(targetIndices[targetToKeep])); return transformedInstance; }
From source file:mx.itesm.arch.mvc.MvcAnalyzer.java
License:Open Source License
/** * Classify each class in the specified List into one of the layers of the * MVC pattern./*from w ww . j a v a2 s . c om*/ * * @param dependencies * List containing the dependencies for each class to classify. * @param internalPackages * Project's internal packages. * @return Map containing the classification layer for each class. * @throws Exception * If an Exception occurs during classification. */ private static Map<String, Layer> classifyClasses(final List<ClassDependencies> dependencies, final Map<String, Set<String>> internalPackages) throws Exception { int viewCount; int modelCount; int instanceLayer; Instance instance; boolean valueFound; int controllerCount; Instances instances; String instanceType; String[] typeValues; Layer componentLayer; String[] suffixValues; Layer dependencyLayer; FastVector attributes; String[] externalApiValues; Map<String, Layer> returnValue; Set<String> currentPackageContent; Map<String, Layer> packagesClassification; Map<String, String[]> externalApiPackages; // Model variables attributes = new FastVector(); for (Variable variable : Variable.values()) { attributes.addElement(variable.getAttribute()); } // Layer variable attributes.addElement(Layer.attribute); // Set the test instances, the Layer variable is unknown instances = new Instances("mvc", attributes, 0); instances.setClassIndex(Variable.values().length); // Valid suffixes to look for in the class names suffixValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Suffix.getVariableName()); // Valid file types to look for in the component names typeValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Type.getVariableName()); // Valid external api packages to look for in the classes dependencies externalApiValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.ExternalAPI.getVariableName()); externalApiPackages = new HashMap<String, String[]>(externalApiValues.length); for (int i = 0; i < externalApiValues.length; i++) { if (!externalApiValues[i].equals("none")) { externalApiPackages.put(externalApiValues[i], MvcAnalyzer.getPropertyValues("externalApi." + externalApiValues[i] + ".packages")); } } returnValue = new HashMap<String, Layer>(dependencies.size()); for (ClassDependencies classDependencies : dependencies) { // Variables + Layer instance = new Instance(Variable.values().length + 1); // Type instanceType = "java"; for (String validType : typeValues) { if (classDependencies.getClassName().endsWith("." + validType)) { instanceType = validType; break; } } instance.setValue(Variable.Type.getAttribute(), instanceType); // ExternalAPI valueFound = false; externalApi: for (String externalApi : externalApiValues) { if (externalApi.equals("none")) { continue; } // Check if any of the class' external dependencies match with // one of the key external dependencies if (classDependencies.getExternalDependencies() != null) { for (String externalDependency : classDependencies.getExternalDependencies()) { for (String externalPackage : externalApiPackages.get(externalApi)) { if (externalDependency.toLowerCase().startsWith(externalPackage)) { valueFound = true; instance.setValue(Variable.ExternalAPI.getAttribute(), externalApi); break externalApi; } } } } } // No key external dependency found if (!valueFound) { instance.setValue(Variable.ExternalAPI.getAttribute(), "none"); } // Suffix valueFound = false; for (String suffix : suffixValues) { if (classDependencies.getClassName().toLowerCase().endsWith(suffix)) { valueFound = true; instance.setValue(Variable.Suffix.getAttribute(), suffix); break; } } // No key suffix found if (!valueFound) { instance.setValue(Variable.Suffix.getAttribute(), "none"); } // Layer, the unknown variable instance.setMissing(Layer.attribute); instances.add(instance); instance.setDataset(instances); try { instanceLayer = (int) MvcAnalyzer.classifier.classifyInstance(instance); } catch (Exception e) { // Default value instanceLayer = 0; logger.severe("Unable to classify: " + instance); } returnValue.put(classDependencies.getClassName(), Layer.values()[instanceLayer]); logger.info( classDependencies.getClassName() + " : " + returnValue.get(classDependencies.getClassName())); } // Check for any invalid relation packagesClassification = new HashMap<String, Layer>(internalPackages.size()); for (String currentPackage : internalPackages.keySet()) { modelCount = viewCount = controllerCount = 0; currentPackageContent = internalPackages.get(currentPackage); for (String component : currentPackageContent) { componentLayer = returnValue.get(component); if (componentLayer == Layer.Model) { modelCount++; } else if (componentLayer == Layer.View) { viewCount++; } else if (componentLayer == Layer.Controller) { controllerCount++; } } if ((modelCount > viewCount) && (modelCount > controllerCount)) { packagesClassification.put(currentPackage, Layer.Model); } else if ((viewCount > modelCount) && (viewCount > controllerCount)) { packagesClassification.put(currentPackage, Layer.View); } else if ((controllerCount > viewCount) && (controllerCount > modelCount)) { packagesClassification.put(currentPackage, Layer.Controller); } else { packagesClassification.put(currentPackage, null); } } for (ClassDependencies classDependencies : dependencies) { // Code relations valueFound = false; componentLayer = returnValue.get(classDependencies.getClassName()); if (classDependencies.getInternalDependencies() != null) { for (String internalDependency : classDependencies.getInternalDependencies()) { dependencyLayer = returnValue.get(internalDependency); if (!componentLayer.isValidRelation(dependencyLayer)) { valueFound = true; returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer)); logger.info("Invalid relation detected between: " + classDependencies.getClassName() + " and " + internalDependency); } } } // Package relations if (!valueFound) { dependencyLayer = packagesClassification.get(classDependencies.getPackageName()); if ((dependencyLayer != null) && (componentLayer != dependencyLayer)) { returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer)); } } } return returnValue; }
From source file:mx.itesm.web2mexadl.mvc.MvcAnalyzer.java
License:Open Source License
/** * Generate the architecture document associated to the specified web * application data.//from w ww .j a va 2s .c om * * @param dependencies * List containing the dependencies for each class to classify. * @param internalPackages * Project's internal packages. * @return Map containing the classification layer for each class. * @throws Exception * If an Exception occurs during classification. */ private static Map<String, Layer> generateArchitecture(final List<ClassDependencies> dependencies, final Map<String, Set<String>> internalPackages, final File outputDir) throws Exception { int viewCount; int modelCount; int instanceLayer; Instance instance; boolean valueFound; int controllerCount; Instances instances; String instanceType; String[] typeValues; Layer componentLayer; String[] suffixValues; Layer dependencyLayer; FastVector attributes; String[] externalApiValues; Map<String, Layer> returnValue; Set<String> currentPackageContent; Map<String, Layer> packagesClassification; Map<String, String[]> externalApiPackages; StringBuilder modelPackages; StringBuilder viewPackages; StringBuilder controllerPackages; // Model variables attributes = new FastVector(); for (Variable variable : Variable.values()) { attributes.addElement(variable.getAttribute()); } // Layer variable attributes.addElement(Layer.attribute); // Set the test instances, the Layer variable is unknown instances = new Instances("mvc", attributes, 0); instances.setClassIndex(Variable.values().length); // Valid suffixes to look for in the class names suffixValues = Util.getPropertyValues(Util.Variable.Suffix.getVariableName()); // Valid file types to look for in the component names typeValues = Util.getPropertyValues(Util.Variable.Type.getVariableName()); // Valid external api packages to look for in the classes dependencies externalApiValues = Util.getPropertyValues(Util.Variable.ExternalAPI.getVariableName()); externalApiPackages = new HashMap<String, String[]>(externalApiValues.length); for (int i = 0; i < externalApiValues.length; i++) { if (!externalApiValues[i].equals("none")) { externalApiPackages.put(externalApiValues[i], Util.getPropertyValues("externalApi." + externalApiValues[i] + ".packages")); } } returnValue = new HashMap<String, Layer>(dependencies.size()); for (ClassDependencies classDependencies : dependencies) { // Variables + Layer instance = new Instance(Variable.values().length + 1); // Type instanceType = "java"; for (String validType : typeValues) { if (classDependencies.getClassName().endsWith("." + validType)) { instanceType = validType; break; } } instance.setValue(Variable.Type.getAttribute(), instanceType); // ExternalAPI valueFound = false; externalApi: for (String externalApi : externalApiValues) { if (externalApi.equals("none")) { continue; } // Check if any of the class' external dependencies match with // one of the key external dependencies if (classDependencies.getExternalDependencies() != null) { for (String externalDependency : classDependencies.getExternalDependencies()) { for (String externalPackage : externalApiPackages.get(externalApi)) { if (externalDependency.toLowerCase().startsWith(externalPackage)) { valueFound = true; instance.setValue(Variable.ExternalAPI.getAttribute(), externalApi); break externalApi; } } } } } // No key external dependency found if (!valueFound) { instance.setValue(Variable.ExternalAPI.getAttribute(), "none"); } // Suffix valueFound = false; for (String suffix : suffixValues) { if (classDependencies.getClassName().toLowerCase().endsWith(suffix)) { valueFound = true; instance.setValue(Variable.Suffix.getAttribute(), suffix); break; } } // No key suffix found if (!valueFound) { instance.setValue(Variable.Suffix.getAttribute(), "none"); } // Layer, the unknown variable instance.setMissing(Layer.attribute); instances.add(instance); instance.setDataset(instances); try { instanceLayer = (int) Util.classifier.classifyInstance(instance); } catch (Exception e) { // Default value instanceLayer = 0; logger.severe("Unable to classify: " + instance); } returnValue.put(classDependencies.getClassName(), Layer.values()[instanceLayer]); logger.info( classDependencies.getClassName() + " : " + returnValue.get(classDependencies.getClassName())); } // Check for any invalid relation viewPackages = new StringBuilder(); modelPackages = new StringBuilder(); controllerPackages = new StringBuilder(); packagesClassification = new HashMap<String, Layer>(internalPackages.size()); for (String currentPackage : internalPackages.keySet()) { modelCount = viewCount = controllerCount = 0; currentPackageContent = internalPackages.get(currentPackage); for (String component : currentPackageContent) { componentLayer = returnValue.get(component); if (componentLayer == Layer.Model) { modelCount++; } else if (componentLayer == Layer.View) { viewCount++; } else if (componentLayer == Layer.Controller) { controllerCount++; } } if ((modelCount > viewCount) && (modelCount > controllerCount)) { packagesClassification.put(currentPackage, Layer.Model); Util.addImplementationPackage(modelPackages, currentPackage); } else if ((viewCount > modelCount) && (viewCount > controllerCount)) { packagesClassification.put(currentPackage, Layer.View); Util.addImplementationPackage(viewPackages, currentPackage); } else if ((controllerCount > viewCount) && (controllerCount > modelCount)) { packagesClassification.put(currentPackage, Layer.Controller); Util.addImplementationPackage(controllerPackages, currentPackage); } else { packagesClassification.put(currentPackage, null); } } for (ClassDependencies classDependencies : dependencies) { // Code relations valueFound = false; componentLayer = returnValue.get(classDependencies.getClassName()); if (classDependencies.getInternalDependencies() != null) { for (String internalDependency : classDependencies.getInternalDependencies()) { dependencyLayer = returnValue.get(internalDependency); if (!componentLayer.isValidRelation(dependencyLayer)) { valueFound = true; returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer)); logger.info("Invalid relation detected between: " + classDependencies.getClassName() + " and " + internalDependency); } } } // Package relations if (!valueFound) { dependencyLayer = packagesClassification.get(classDependencies.getPackageName()); if ((dependencyLayer != null) && (componentLayer != dependencyLayer)) { returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer)); } } } // Export MexADL architecture MvcAnalyzer.exportToMexADL(outputDir, modelPackages.toString(), controllerPackages.toString(), viewPackages.toString()); return returnValue; }
From source file:myclassifier.wekaCode.java
public static void classifyUnseenData(String[] attributes, Classifier classifiers, Instances data) throws Exception { Instance newInstance = new Instance(data.numAttributes()); newInstance.setDataset(data);//from ww w . j av a 2s.c o m for (int i = 0; i < data.numAttributes() - 1; i++) { if (Attribute.NUMERIC == data.attribute(i).type()) { Double value = Double.valueOf(attributes[i]); newInstance.setValue(i, value); } else { newInstance.setValue(i, attributes[i]); } } double clsLabel = classifiers.classifyInstance(newInstance); newInstance.setClassValue(clsLabel); String result = data.classAttribute().value((int) clsLabel); System.out.println("Hasil Classify Unseen Data Adalah: " + result); }
From source file:myclusterer.WekaCode.java
public static void classifyUnseenData(String[] attributes, Clusterer clusterer, Instances data) throws Exception { Instance newInstance = new Instance(data.numAttributes()); newInstance.setDataset(data);// www . j a v a 2 s . c o m for (int i = 0; i < data.numAttributes() - 1; i++) { if (Attribute.NUMERIC == data.attribute(i).type()) { Double value = Double.valueOf(attributes[i]); newInstance.setValue(i, value); } else { newInstance.setValue(i, attributes[i]); } } double clsLabel = clusterer.clusterInstance(newInstance); newInstance.setClassValue(clsLabel); String result = data.classAttribute().value((int) clsLabel); System.out.println("Hasil Classify Unseen Data Adalah: " + result); }
From source file:myid3andc45classifier.Model.MyC45.java
@Override public void buildClassifier(Instances data) throws Exception { getCapabilities().testWithFail(data); data = new Instances(data); data.deleteWithMissingClass();//from w ww.j a v a2 s . c o m Enumeration enumAtt = data.enumerateAttributes(); while (enumAtt.hasMoreElements()) { Attribute attr = (Attribute) enumAtt.nextElement(); if (attr.isNumeric()) { ArrayList<Double> mid = new ArrayList<Double>(); Instances savedData = null; double temp, max = Double.NEGATIVE_INFINITY; // TODO: split nominal data.sort(attr); for (int i = 0; i < data.numInstances() - 1; i++) { if (data.instance(i).classValue() != data.instance(i + 1).classValue()) { if (data.attribute(attr.name() + " " + (data.instance(i + 1).value(attr) + data.instance(i).value(attr)) / 2) == null) { data = convertInstances(data, attr, (data.instance(i + 1).value(attr) + data.instance(i).value(attr)) / 2); //temp = computeInfoGainRatio(newData, newData.attribute(newData.numAttributes()-1)); //System.out.println("attribute "+newData.attribute(newData.numAttributes()-1).name()); //if (temp > max) { // max = temp; // savedData = newData; //} } } } //Penanganan Missing Value AttributeStats attributeStats = data.attributeStats(attr.index()); double mean = attributeStats.numericStats.mean; if (Double.isNaN(mean)) mean = 0; // Replace missing value with mean Enumeration instEnumerate = data.enumerateInstances(); while (instEnumerate.hasMoreElements()) { Instance instance = (Instance) instEnumerate.nextElement(); if (instance.isMissing(attr.index())) { instance.setValue(attr.index(), mean); } } //data = new Instances(savedData); } else { //Penanganan Missing Value AttributeStats attributeStats = data.attributeStats(attr.index()); int maxIndex = 0; for (int i = 1; i < attr.numValues(); i++) { if (attributeStats.nominalCounts[maxIndex] < attributeStats.nominalCounts[i]) { maxIndex = i; } } // Replace missing value with max index Enumeration instEnumerate = data.enumerateInstances(); while (instEnumerate.hasMoreElements()) { Instance instance = (Instance) instEnumerate.nextElement(); if (instance.isMissing(attr.index())) { instance.setValue(attr.index(), maxIndex); } } } } makeMyC45Tree(data); }