Java Code Examples for weka.core.Attribute#name()

The following examples show how to use weka.core.Attribute#name() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PerformanceKnowledgeBase.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public Instance getInstanceForIndividualCI(final String benchmarkName, final ComponentInstance ci, final double score) {
	Instances instancesInd = this.performanceInstancesIndividualComponents.get(benchmarkName).get(ci.getComponent().getName());
	DenseInstance instanceInd = new DenseInstance(instancesInd.numAttributes());
	for (int i = 0; i < instancesInd.numAttributes() - 1; i++) {
		Attribute attr = instancesInd.attribute(i);
		String attrFQN = attr.name();
		String attrName = attrFQN.substring(attrFQN.indexOf("::") + 2);
		Parameter param = ci.getComponent().getParameterWithName(attrName);
		String value;
		if (ci.getParametersThatHaveBeenSetExplicitly().contains(param)) {
			value = ci.getParameterValues().get(param.getName());
		} else {
			value = param.getDefaultValue().toString();
		}
		if (value != null) {
			if (param.isCategorical()) {
				boolean attrContainsValue = false;
				Enumeration<Object> possibleValues = attr.enumerateValues();
				while (possibleValues.hasMoreElements() && !attrContainsValue) {
					Object o = possibleValues.nextElement();
					if (o.equals(value)) {
						attrContainsValue = true;
					}
				}
				if (attrContainsValue) {
					instanceInd.setValue(attr, value);
				}
			} else if (param.isNumeric()) {
				double finalValue = Double.parseDouble(value);
				instanceInd.setValue(attr, finalValue);
			}
		}
	}
	Attribute scoreAttrInd = instancesInd.classAttribute();
	instanceInd.setValue(scoreAttrInd, score);
	return instanceInd;
}
 
Example 2
Source File: WekaInstancesUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static IAttribute transformWEKAAttributeToAttributeType(final Attribute att) {
	String attributeName = att.name();
	if (att.isNumeric()) {
		return new NumericAttribute(attributeName);
	} else if (att.isNominal()) {
		List<String> domain = new LinkedList<>();
		for (int i = 0; i < att.numValues(); i++) {
			domain.add(att.value(i));
		}
		return new IntBasedCategoricalAttribute(attributeName, domain);
	}
	throw new IllegalArgumentException("Can only transform numeric or categorical attributes");
}
 
Example 3
Source File: MekaInstancesUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static IAttribute transformWEKAAttributeToAttributeType(final Attribute att) {
	String attributeName = att.name();
	if (att.isNumeric()) {
		return new NumericAttribute(attributeName);
	} else if (att.isNominal()) {
		List<String> domain = new LinkedList<>();
		for (int i = 0; i < att.numValues(); i++) {
			domain.add(att.value(i));
		}
		return new IntBasedCategoricalAttribute(attributeName, domain);
	}
	throw new IllegalArgumentException("Can only transform numeric or categorical attributes");
}
 
Example 4
Source File: Utils.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Copies the attribute name and values of a given nominal attribute
 * @param oldAttribute attribute to copy
 * @return duplicated nominal attribute
 */
public static Attribute copyNominalAttribute(Attribute oldAttribute) {
  String[] classValues = new String[oldAttribute.numValues()];
  for (int classValI = 0; classValI < oldAttribute.numValues(); classValI++) {
    classValues[classValI] = oldAttribute.value(classValI);
  }
  return new Attribute(oldAttribute.name(), Arrays.asList(classValues));
}
 
Example 5
Source File: Result.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert a list of Results into an Instances.
 * @param results An ArrayList of Results
 * @return	Instances
 */
public static Instances getResultsAsInstances(ArrayList<HashMap<String,Object>> metrics) {

	HashMap<String,Object> o_master = metrics.get(0);
	ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
	for (String key : o_master.keySet())  {
		if (o_master.get(key) instanceof Double) {
			//System.out.println("key="+key);
			attInfo.add(new Attribute(key));
		}
	}

	Instances resultInstances = new Instances("Results",attInfo,metrics.size());

	for (HashMap<String,Object> o : metrics) {
		Instance rx = new DenseInstance(attInfo.size());
		for (Attribute att : attInfo) {
			String name = att.name();
			rx.setValue(att,(double)o.get(name));
		}
		resultInstances.add(rx);
	}

	//System.out.println(""+resultInstances);
	return resultInstances;

}
 
Example 6
Source File: Utils.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Copies the attribute name and values of a given nominal attribute
 * @param oldAttribute attribute to copy
 * @return duplicated nominal attribute
 */
public static Attribute copyNominalAttribute(Attribute oldAttribute) {
  String[] classValues = new String[oldAttribute.numValues()];
  for (int classValI = 0; classValI < oldAttribute.numValues(); classValI++) {
    classValues[classValI] = oldAttribute.value(classValI);
  }
  return new Attribute(oldAttribute.name(), Arrays.asList(classValues));
}
 
Example 7
Source File: NaiveBayes.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
  * Calculates the class membership probabilities for the given test 
  * instance.
  *
  * @param instance the instance to be classified
  * @return predicted class probability distribution
  * @exception Exception if there is a problem generating the prediction
  */
 public double [] distributionForInstance(Instance instance) 
   throws Exception { 

   if (m_UseDiscretization) {
     m_Disc.input(instance);
     instance = m_Disc.output();
   }
   double [] probs = new double[m_NumClasses];
   for (int j = 0; j < m_NumClasses; j++) {
     probs[j] = m_ClassDistribution.getProbability(j);
   }
   Enumeration enumAtts = instance.enumerateAttributes();
   int attIndex = 0;
   while (enumAtts.hasMoreElements()) {
     Attribute attribute = (Attribute) enumAtts.nextElement();
     if (!instance.isMissing(attribute)) {
double temp, max = 0;
for (int j = 0; j < m_NumClasses; j++) {
  temp = Math.max(1e-75, Math.pow(m_Distributions[attIndex][j].
                                         getProbability(instance.value(attribute)), 
                                         m_Instances.attribute(attIndex).weight()));
  probs[j] *= temp;
  if (probs[j] > max) {
    max = probs[j];
  }
  if (Double.isNaN(probs[j])) {
    throw new Exception("NaN returned from estimator for attribute "
                               + attribute.name() + ":\n"
                               + m_Distributions[attIndex][j].toString());
  }
}
if ((max > 0) && (max < 1e-75)) { // Danger of probability underflow
  for (int j = 0; j < m_NumClasses; j++) {
    probs[j] *= 1e75;
  }
}
     }
     attIndex++;
   }

   // Display probabilities
   Utils.normalize(probs);
   return probs;
 }
 
Example 8
Source File: InputMappedClassifier.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
private StringBuffer createMappingReport() {
  StringBuffer result = new StringBuffer();
  result.append("Attribute mappings:\n\n");
  
  int maxLength = 0;
  for (int i = 0; i < m_modelHeader.numAttributes(); i++) {
    if (m_modelHeader.attribute(i).name().length() > maxLength) {
      maxLength = m_modelHeader.attribute(i).name().length();        
    }
  }
  maxLength += 12;
  
  int minLength = 16;
  String headerS = "Model attributes";
  String sep = "----------------";

  if (maxLength < minLength) {
    maxLength = minLength;
  }
  
  headerS = getFixedLengthString(headerS, ' ', maxLength);
  sep = getFixedLengthString(sep, '-', maxLength);
  sep += "\t    ----------------\n";
  headerS += "\t    Incoming attributes\n";
  result.append(headerS);
  result.append(sep);
  
  for (int i = 0; i < m_modelHeader.numAttributes(); i++) {
    Attribute temp = m_modelHeader.attribute(i);
    String attName = "("
      + ((temp.isNumeric())
         ? "numeric)"
         : "nominal)") 
      + " " + temp.name();
    attName = getFixedLengthString(attName, ' ', maxLength);
    attName +=  "\t--> ";
    result.append(attName);
    String inAttNum = "";
    if (m_attributeStatus[i] == NO_MATCH) {
      inAttNum += "- ";
      result.append(inAttNum + "missing (no match)\n");
    } else if (m_attributeStatus[i] == TYPE_MISMATCH) {       
      inAttNum += (m_attributeMap[i] + 1) + " ";
      result.append(inAttNum + "missing (type mis-match)\n");
    } else {
      Attribute inAtt = m_inputHeader.attribute(m_attributeMap[i]);
      String inName = "" + (m_attributeMap[i] + 1) + " (" +
      ((inAtt.isNumeric())
          ? "numeric)"
          : "nominal)")
          + " " + inAtt.name();
      result.append(inName + "\n");
    }
  }
  
  return result;
}
 
Example 9
Source File: MergeManyValues.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
  * Input an instance for filtering. The instance is processed
  * and made available for output immediately.
  *
  * @param instance 	the input instance
  * @return 		true if the filtered instance may now be
  * 			collected with output().
  * @throws IllegalStateException	if no input format has been set.
  */
 public boolean input(Instance instance) {
   if (getInputFormat() == null) {
     throw new IllegalStateException("No input instance format defined");
   }
   if (m_NewBatch) {
     resetQueue();
     m_NewBatch = false;
   }

   Attribute att = getInputFormat().attribute(m_AttIndex.getIndex());
   FastVector newVals = new FastVector(att.numValues() - 1);
   for (int i = 0; i < att.numValues(); i++) {
     boolean inMergeList = false;

     if(att.value(i).equalsIgnoreCase(m_Label)){
//don't want to add this one.
inMergeList = true;		
     }else{
inMergeList = m_MergeRange.isInRange(i);
     }

     if(!inMergeList){
//add it.
newVals.addElement(att.value(i));
     }
   }
   newVals.addElement(m_Label);

   Attribute temp = new Attribute(att.name(), newVals);

   Instance newInstance = (Instance)instance.copy();    
   if (!newInstance.isMissing(m_AttIndex.getIndex())) {
     String currValue = newInstance.stringValue(m_AttIndex.getIndex());
     if(temp.indexOfValue(currValue) == -1)
newInstance.setValue(m_AttIndex.getIndex(), temp.indexOfValue(m_Label));
     else
newInstance.setValue(m_AttIndex.getIndex(), temp.indexOfValue(currValue));
   }

   push(newInstance);
   return true;
 }
 
Example 10
Source File: WekaUtil.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Attribute getNewClassAttribute(final Attribute attribute, final List<String> classes) {
	return new Attribute(attribute.name(), classes);
}
 
Example 11
Source File: TweetCentroid.java    From AffectiveTweets with GNU General Public License v3.0 2 votes vote down vote up
@Override
protected Instances process(Instances instances) throws Exception {



	Instances result = getOutputFormat();

	for(String word:this.wordInfo.keySet()){
		// get the word vector
		WordRep wordRep=this.wordInfo.get(word);

		// We just consider valid words
		if(wordRep.numDoc>=this.minInstDocs){
			double[] values = new double[result.numAttributes()];


			for(String wordFeat:wordRep.wordSpace.keySet()){
				// only include valid words
				if(this.m_Dictionary.containsKey(wordFeat)){
					int attIndex=this.m_Dictionary.getInt(wordFeat);
					// we normalise the value by the number of documents
					values[attIndex]=((double)wordRep.wordSpace.getInt(wordFeat))/wordRep.numDoc;					
				}
			}


			if(this.considerNumericAtts){
				for(Attribute metaAtt:this.numericAttributes){
					String metaAttName=metaAtt.name();
					values[result.attribute(metaAttName).index()]= wordRep.metaData.getDouble(metaAtt.name())/wordRep.numDoc;
				}


			}


			int wordNameIndex=result.attribute("WORD_NAME").index();
			values[wordNameIndex]=result.attribute(wordNameIndex).addStringValue(word);					


			Instance inst=new SparseInstance(1, values);

			inst.setDataset(result);

			result.add(inst);

		}


	}



	return result;





}