Java Code Examples for weka.core.Instance#numClasses()

The following examples show how to use weka.core.Instance#numClasses() . 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: ClassifierDecList.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/** 
  * Classifies an instance.
  *
  * @exception Exception if something goes wrong
  */
 public double classifyInstance(Instance instance)
      throws Exception {

   double maxProb = -1;
   double currentProb;
   int maxIndex = 0;
   int j;

   for (j = 0; j < instance.numClasses();
 j++){
     currentProb = getProbs(j,instance,1);
     if (Utils.gr(currentProb,maxProb)){
maxIndex = j;
maxProb = currentProb;
     }
   }
   if (Utils.eq(maxProb,0))
     return -1.0;
   else
     return (double)maxIndex;
 }
 
Example 2
Source File: AbstractClassifier.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Predicts the class memberships for a given instance. If
 * an instance is unclassified, the returned array elements
 * must be all zero. If the class is numeric, the array
 * must consist of only one element, which contains the
 * predicted value. Note that a classifier MUST implement
 * either this or classifyInstance().
 *
 * @param instance the instance to be classified
 * @return an array containing the estimated membership
 * probabilities of the test instance in each class
 * or the numeric prediction
 * @exception Exception if distribution could not be
 * computed successfully
 */
public double[] distributionForInstance(Instance instance) throws Exception {

  double[] dist = new double[instance.numClasses()];
  switch (instance.classAttribute().type()) {
    case Attribute.NOMINAL:
      double classification = classifyInstance(instance);
      if (Utils.isMissingValue(classification)) {
        return dist;
      } else {
        dist[(int)classification] = 1.0;
      }
      return dist;
    case Attribute.NUMERIC:
      dist[0] = classifyInstance(instance);
      return dist;
    default:
      return dist;
  }
}
 
Example 3
Source File: ClassifierTree.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/** 
  * Returns class probabilities for a weighted instance.
  *
  * @param instance the instance to get the distribution for
  * @param useLaplace whether to use laplace or not
  * @return the distribution
  * @throws Exception if something goes wrong
  */
 public final double [] distributionForInstance(Instance instance,
					 boolean useLaplace) 
      throws Exception {

   double [] doubles = new double[instance.numClasses()];

   for (int i = 0; i < doubles.length; i++) {
     if (!useLaplace) {
doubles[i] = getProbs(i, instance, 1);
     } else {
doubles[i] = getProbsLaplace(i, instance, 1);
     }
   }

   return doubles;
 }
 
Example 4
Source File: DMNBtext.java    From tsml with GNU General Public License v3.0 6 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_numClasses == 2) {
    // System.out.println(m_binaryClassifiers[0].getProbForTargetClass(instance));
    return m_binaryClassifiers[0].distributionForInstance(instance);
  }
  double[] logDocGivenClass = new double[instance.numClasses()];
  for (int i = 0; i < m_numClasses; i++)
    logDocGivenClass[i] = m_binaryClassifiers[i].getLogProbForTargetClass(instance);


  double max = logDocGivenClass[Utils.maxIndex(logDocGivenClass)];
  for(int i = 0; i<m_numClasses; i++)
    logDocGivenClass[i] = Math.exp(logDocGivenClass[i] - max);


  try {
    Utils.normalize(logDocGivenClass);
  } catch (Exception e) {
    e.printStackTrace();


  }

  return logDocGivenClass;
}
 
Example 5
Source File: RandomCommittee.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Calculates the class membership probabilities for the given test
  * instance.
  *
  * @param instance the instance to be classified
  * @return preedicted class probability distribution
  * @exception Exception if distribution can't be computed successfully 
  */
 public double[] distributionForInstance(Instance instance) throws Exception {

   double [] sums = new double [instance.numClasses()], newProbs; 
   
   for (int i = 0; i < m_NumIterations; i++) {
     if (instance.classAttribute().isNumeric() == true) {
sums[0] += m_Classifiers[i].classifyInstance(instance);
     } else {
newProbs = m_Classifiers[i].distributionForInstance(instance);
for (int j = 0; j < newProbs.length; j++)
  sums[j] += newProbs[j];
     }
   }
   if (instance.classAttribute().isNumeric() == true) {
     sums[0] /= (double)m_NumIterations;
     return sums;
   } else if (Utils.eq(Utils.sum(sums), 0)) {
     return sums;
   } else {
     Utils.normalize(sums);
     return sums;
   }
 }
 
Example 6
Source File: BoTSWEnsemble.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    double[] classHist = new double[instance.numClasses()];
    
    //get votes from all windows 
    double sum = 0;
    for (BoTSWWindow classifier : classifiers) {
        double classification = classifier.classifyInstance(instance);
        classHist[(int)classification]++;
        sum++;
    }
    
    if (sum != 0)
        for (int i = 0; i < classHist.length; ++i)
            classHist[i] /= sum;
    
    return classHist;
}
 
Example 7
Source File: MOA.java    From moa with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Predicts the class memberships for a given instance. If
 * an instance is unclassified, the returned array elements
 * must be all zero. If the class is numeric, the array
 * must consist of only one element, which contains the
 * predicted value.
 *
 * @param instance the instance to be classified
 * @return an array containing the estimated membership
 * probabilities of the test instance in each class
 * or the numeric prediction
 * @throws Exception if distribution could not be
 * computed successfully
 */
public double[] distributionForInstance(Instance instance) throws Exception {
	double[]	result;

	result = m_ActualClassifier.getVotesForInstance(instanceConverter.samoaInstance(instance));
      // ensure that the array has as many elements as there are
      // class values!
      if (result.length < instance.numClasses()) {
        double[] newResult = new double[instance.numClasses()];
        System.arraycopy(result, 0, newResult, 0, result.length);
        result = newResult;
      }

	try {
		Utils.normalize(result);
	}
	catch (Exception e) {
		result = new double[instance.numClasses()];
	}

	return result;
}
 
Example 8
Source File: BOSSSpatialPyramids_BD.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    double[] classHist = new double[instance.numClasses()];
    double sum = 0;
    
    //get votes from all windows 
    for (BOSSWindow classifier : classifiers) {
        if (serOption == SerialiseOptions.STORE_LOAD)
            classifier.load();
        double classification = classifier.classifyInstance(instance);
        if (serOption == SerialiseOptions.STORE_LOAD)
            classifier.clearClassifier();
        
        classHist[(int)classification]++;
        sum++;
    }
    
    if (sum != 0)
        for (int i = 0; i < classHist.length; ++i)
            classHist[i] /= sum;
    
    return classHist;
}
 
Example 9
Source File: ClassificationViaRegression.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Returns the distribution for an instance.
  *
  * @param inst the instance to get the distribution for
  * @return the computed distribution
  * @throws Exception if the distribution can't be computed successfully
  */
 public double[] distributionForInstance(Instance inst) throws Exception {
   
   double[] probs = new double[inst.numClasses()];
   Instance newInst;
   double sum = 0;

   for (int i = 0; i < inst.numClasses(); i++) {
     m_ClassFilters[i].input(inst);
     m_ClassFilters[i].batchFinished();
     newInst = m_ClassFilters[i].output();
     probs[i] = m_Classifiers[i].classifyInstance(newInst);
     if (probs[i] > 1) {
       probs[i] = 1;
     }
     if (probs[i] < 0){
probs[i] = 0;
     }
     sum += probs[i];
   }
   if (sum != 0) {
     Utils.normalize(probs, sum);
   } 
   return probs;
 }
 
Example 10
Source File: LMT.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Classifies an instance.
  *
  * @param instance the instance to classify
  * @return the classification
  * @throws Exception if instance can't be classified successfully
  */
 public double classifyInstance(Instance instance) throws Exception {

   double maxProb = -1;
   int maxIndex = 0;
     
   //classify by maximum probability
   double[] probs = distributionForInstance(instance);       
   for (int j = 0; j < instance.numClasses(); j++) {
     if (Utils.gr(probs[j], maxProb)) {
maxIndex = j;
maxProb = probs[j];
     }
   }     
   return (double)maxIndex;      
 }
 
Example 11
Source File: FlipHistory.java    From collective-classification-weka-package with GNU General Public License v3.0 5 votes vote down vote up
/**
 * returns the last distribution for the given instance, only 0s if it cannot
 * be found
 * 
 * @param inst      the instance to retrieve the last distribution for
 * @return          the distribution for the given instance
 */
public double[] getLast(Instance inst) {
  int       index;
  double[]  result;

  index  = find(inst);
  if (index < 0)
    result = new double[inst.numClasses()];
  else
    result = m_Last[index];

  return result;
}
 
Example 12
Source File: FastShapelets.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    double c=classifyInstance(instance);
    double[] r=new double[instance.numClasses()];
    r[(int)c]=1;
    return r;
}
 
Example 13
Source File: MakeDecList.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/** 
  * Returns the class distribution for an instance.
  *
  * @exception Exception if distribution can't be computed
  */
 public double[] distributionForInstance(Instance instance) 
      throws Exception {

   double [] currentProbs = null;
   double [] sumProbs;
   double currentWeight, weight = 1;
   int i,j;

   // Get probabilities.
   sumProbs = new double [instance.numClasses()];
   i = 0;
   while (Utils.gr(weight,0)){
     currentWeight = 
((ClassifierDecList)theRules.elementAt(i)).weight(instance);
     if (Utils.gr(currentWeight,0)) {
currentProbs = ((ClassifierDecList)theRules.elementAt(i)).
  distributionForInstance(instance);
for (j = 0; j < sumProbs.length; j++)
  sumProbs[j] += weight*currentProbs[j];
weight = weight*(1-currentWeight);
     }
     i++;
   }

   return sumProbs;
 }
 
Example 14
Source File: DMNBtext.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Updates the classifier with the given instance.
 *
 * @param instance the new training instance to include in the model
 * @exception Exception if the instance could not be incorporated in
 * the model.
 */

public void updateClassifier(Instance instance) throws Exception {

  if (m_numClasses == 2) {
    m_binaryClassifiers[0].updateClassifier(instance);
  } else {
    for (int i = 0; i < instance.numClasses(); i++)
      m_binaryClassifiers[i].updateClassifier(instance);
  }
}
 
Example 15
Source File: NaiveBayesSimple.java    From tsml with GNU General Public License v3.0 5 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 distribution can't be computed
  */
 public double[] distributionForInstance(Instance instance) throws Exception {
   
   double [] probs = new double[instance.numClasses()];
   int attIndex;
   
   for (int j = 0; j < instance.numClasses(); j++) {
     probs[j] = 1;
     Enumeration enumAtts = instance.enumerateAttributes();
     attIndex = 0;
     while (enumAtts.hasMoreElements()) {
Attribute attribute = (Attribute) enumAtts.nextElement();
if (!instance.isMissing(attribute)) {
  if (attribute.isNominal()) {
    probs[j] *= m_Counts[j][attIndex][(int)instance.value(attribute)];
  } else {
    probs[j] *= normalDens(instance.value(attribute),
			   m_Means[j][attIndex],
			   m_Devs[j][attIndex]);}
}
attIndex++;
     }
     probs[j] *= m_Priors[j];
   }

   // Normalize probabilities
   Utils.normalize(probs);

   return probs;
 }
 
Example 16
Source File: WekaInstancesUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Instance transformInstanceToWekaInstance(final ILabeledInstanceSchema schema, final ILabeledInstance instance) throws UnsupportedAttributeTypeException {
	if (instance.getNumAttributes() != schema.getNumAttributes()) {
		throw new IllegalArgumentException("Schema and instance do not coincide. The schema defines " + schema.getNumAttributes() + " attributes but the instance has " + instance.getNumAttributes() + " attributes.");
	}
	if (instance instanceof WekaInstance) {
		return ((WekaInstance) instance).getElement();
	}
	Objects.requireNonNull(schema);
	Instances dataset = createDatasetFromSchema(schema);
	Instance iNew = new DenseInstance(dataset.numAttributes());
	iNew.setDataset(dataset);
	for (int i = 0; i < instance.getNumAttributes(); i++) {
		if (schema.getAttribute(i) instanceof INumericAttribute) {
			iNew.setValue(i, ((INumericAttribute) schema.getAttribute(i)).getAsAttributeValue(instance.getAttributeValue(i)).getValue());
		} else if (schema.getAttribute(i) instanceof ICategoricalAttribute) {
			iNew.setValue(i, ((ICategoricalAttribute) schema.getAttribute(i)).getAsAttributeValue(instance.getAttributeValue(i)).getValue());
		} else {
			throw new UnsupportedAttributeTypeException("Only categorical and numeric attributes are supported!");
		}
	}

	if (schema.getLabelAttribute() instanceof INumericAttribute) {
		iNew.setValue(iNew.numAttributes() - 1, ((INumericAttribute) schema.getLabelAttribute()).getAsAttributeValue(instance.getLabel()).getValue());
	} else if (schema.getLabelAttribute() instanceof ICategoricalAttribute) {
		iNew.setValue(iNew.numAttributes() - 1, ((ICategoricalAttribute) schema.getLabelAttribute()).getAsAttributeValue(instance.getLabel()).getValue());
	} else {
		throw new UnsupportedAttributeTypeException("Only categorical and numeric attributes are supported!");
	}
	if (iNew.numClasses() != dataset.numClasses()) {
		throw new IllegalStateException();
	}
	return iNew;
}
 
Example 17
Source File: MultiClassClassifierUpdateable.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns the distribution for an instance.
 * 
 * @param inst the instance to get the distribution for
 * @return the distribution
 * @throws Exception if the distribution can't be computed successfully
 */
@Override
public double[] distributionForInstance(Instance inst) throws Exception {

  if (m_Classifiers.length == 1) {
    return m_Classifiers[0].distributionForInstance(inst);
  }

  double[] probs = new double[inst.numClasses()];
  if (m_Method == METHOD_1_AGAINST_1) {
    double[][] r = new double[inst.numClasses()][inst.numClasses()];
    double[][] n = new double[inst.numClasses()][inst.numClasses()];

    for (int i = 0; i < m_ClassFilters.length; i++) {
      if (m_Classifiers[i] != null && m_SumOfWeights[i] > 0) {
        Instance tempInst = (Instance) inst.copy();
        tempInst.setDataset(m_TwoClassDataset);
        double[] current = m_Classifiers[i].distributionForInstance(tempInst);
        Range range = new Range(
            ((RemoveWithValues) m_ClassFilters[i]).getNominalIndices());
        range.setUpper(m_ClassAttribute.numValues());
        int[] pair = range.getSelection();
        if (m_pairwiseCoupling && inst.numClasses() > 2) {
          r[pair[0]][pair[1]] = current[0];
          n[pair[0]][pair[1]] = m_SumOfWeights[i];
        } else {
          if (current[0] > current[1]) {
            probs[pair[0]] += 1.0;
          } else {
            probs[pair[1]] += 1.0;
          }
        }
      }
    }
    if (m_pairwiseCoupling && inst.numClasses() > 2) {
      try {
        return pairwiseCoupling(n, r);
      } catch (IllegalArgumentException ex) {
      }
    }
    if (Utils.gr(Utils.sum(probs), 0)) {
      Utils.normalize(probs);
    }
    return probs;
  } else {
    probs = super.distributionForInstance(inst);
  }

  /*
   * if (probs.length == 1) { // ZeroR made the prediction return new
   * double[m_ClassAttribute.numValues()]; }
   */

  return probs;
}
 
Example 18
Source File: Grading.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns class probabilities for a given instance using the stacked classifier.
 * One class will always get all the probability mass (i.e. probability one).
 *
 * @param instance the instance to be classified
 * @throws Exception if instance could not be classified
 * successfully
 * @return the class distribution for the given instance
 */
public double[] distributionForInstance(Instance instance) throws Exception {

  double maxPreds;
  int numPreds=0;
  int numClassifiers=m_Classifiers.length;
  int idxPreds;
  double [] predConfs = new double[numClassifiers];
  double [] preds;

  for (int i=0; i<numClassifiers; i++) {
    preds = m_MetaClassifiers[i].distributionForInstance(metaInstance(instance,i));
    if (m_MetaClassifiers[i].classifyInstance(metaInstance(instance,i))==1)
      predConfs[i]=preds[1];
    else
      predConfs[i]=-preds[0];
  }
  if (predConfs[Utils.maxIndex(predConfs)]<0.0) { // no correct classifiers
    for (int i=0; i<numClassifiers; i++)   // use neg. confidences instead
      predConfs[i]=1.0+predConfs[i];
  } else {
    for (int i=0; i<numClassifiers; i++)   // otherwise ignore neg. conf
      if (predConfs[i]<0) predConfs[i]=0.0;
  }

  /*System.out.print(preds[0]);
  System.out.print(":");
  System.out.print(preds[1]);
  System.out.println("#");*/

  preds=new double[instance.numClasses()];
  for (int i=0; i<instance.numClasses(); i++) preds[i]=0.0;
  for (int i=0; i<numClassifiers; i++) {
    idxPreds=(int)(m_Classifiers[i].classifyInstance(instance));
    preds[idxPreds]+=predConfs[i];
  }

  maxPreds=preds[Utils.maxIndex(preds)];
  int MaxInstPerClass=-100;
  int MaxClass=-1;
  for (int i=0; i<instance.numClasses(); i++) {
    if (preds[i]==maxPreds) {
      numPreds++;
      if (m_InstPerClass[i]>MaxInstPerClass) {
        MaxInstPerClass=(int)m_InstPerClass[i];
        MaxClass=i;
      }
    }
  }

  int predictedIndex;
  if (numPreds==1)
    predictedIndex = Utils.maxIndex(preds);
  else
  {
    // System.out.print("?");
    // System.out.print(instance.toString());
    // for (int i=0; i<instance.numClasses(); i++) {
    //   System.out.print("/");
    //   System.out.print(preds[i]);
    // }
    // System.out.println(MaxClass);
    predictedIndex = MaxClass;
  }
  double[] classProbs = new double[instance.numClasses()];
  classProbs[predictedIndex] = 1.0;
  return classProbs;
}
 
Example 19
Source File: TransformEnsembles.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
public double[] distributionForInstance(Instance ins) throws Exception{
	double[][] preds;
	if(rebuild){	
		preds=new double[nosTransforms][];
		if(all[0]!=null)
			preds[0]=all[0].distributionForInstance(ins);
//Nasty hack because I've implemented them as batch filters		
		Instances temp=new Instances(train.get(0),0);
		temp.add(ins);
		Instances temp2;
		if(all[1]!=null){
			temp2=ps.process(temp);
			if(normaliseAtts){
				temp2=nPs.process(temp2);
			}
			preds[1]=all[1].distributionForInstance(temp2.instance(0));
		}
		if(all[2]!=null){
			temp2=acf.process(temp);
			if(normaliseAtts){
				temp2=nAcf.process(temp2);
			}
			preds[2]=all[2].distributionForInstance(temp2.instance(0));
		}
		if(all[3]!=null){
			Instance t= pca.convertInstance(ins);
			preds[3]=all[3].distributionForInstance(t);
		}
		predictions.add(preds);
	}
	else{
		preds=predictions.get(testPos);
		testPos++;
	}
	//Weight each
	double[] dist=new double[ins.numClasses()];
	for(int i=0;i<nosTransforms;i++){
		if(transformWeights[i]>0){	//Equivalent to all[i]!=null
			for(int j=0;j<dist.length;j++)
				dist[j]+=transformWeights[i]*preds[i][j];
		}
	}
	
	return dist;
}
 
Example 20
Source File: LibSVM.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
  * Computes the distribution for a given instance. 
  * In case of 1-class classification, 1 is returned at index 0 if libsvm 
  * returns 1 and NaN (= missing) if libsvm returns -1.
  *
  * @param instance 		the instance for which distribution is computed
  * @return 			the distribution
  * @throws Exception 		if the distribution can't be computed successfully
  */
 public double[] distributionForInstance (Instance instance) throws Exception {	
   int[] labels = new int[instance.numClasses()];
   double[] prob_estimates = null;

   if (m_ProbabilityEstimates) {
     invokeMethod(
  Class.forName(CLASS_SVM).newInstance(),
  "svm_get_labels",
  new Class[]{
    Class.forName(CLASS_SVMMODEL), 
    Array.newInstance(Integer.TYPE, instance.numClasses()).getClass()},
    new Object[]{
    m_Model, 
    labels});

     prob_estimates = new double[instance.numClasses()];
   }
   
   if (!getDoNotReplaceMissingValues()) {
     m_ReplaceMissingValues.input(instance);
     m_ReplaceMissingValues.batchFinished();
     instance = m_ReplaceMissingValues.output();
   }
   
   if (m_Filter != null) {
     m_Filter.input(instance);
     m_Filter.batchFinished();
     instance = m_Filter.output();
   }

   Object x = instanceToArray(instance);
   double v;
   double[] result = new double[instance.numClasses()];
   if (    m_ProbabilityEstimates 
 && ((m_SVMType == SVMTYPE_C_SVC) || (m_SVMType == SVMTYPE_NU_SVC)) ) {
     v = ((Double) invokeMethod(
         Class.forName(CLASS_SVM).newInstance(),
         "svm_predict_probability",
         new Class[]{
           Class.forName(CLASS_SVMMODEL), 
           Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass(),
           Array.newInstance(Double.TYPE, prob_estimates.length).getClass()},
         new Object[]{
           m_Model, 
           x,
           prob_estimates})).doubleValue();

     // Return order of probabilities to canonical weka attribute order
     for (int k = 0; k < prob_estimates.length; k++) {
       result[labels[k]] = prob_estimates[k];
     }
   }
   else {
     v = ((Double) invokeMethod(
         Class.forName(CLASS_SVM).newInstance(),
         "svm_predict",
         new Class[]{
           Class.forName(CLASS_SVMMODEL), 
           Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass()},
         new Object[]{
           m_Model, 
           x})).doubleValue();
     
     if (instance.classAttribute().isNominal()) {
if (m_SVMType == SVMTYPE_ONE_CLASS_SVM) {
  if (v > 0)
    result[0] = 1;
  else
    result[0] = Double.NaN;  // outlier
}
else {
  result[(int) v] = 1;
}
     }
     else {
result[0] = v;
     }
   }

   return result;                
 }