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

The following examples show how to use weka.core.Instance#value() . 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: AbstractAugmentedSpaceSampler.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static Instance generateAugPoint(final List<Instance> insts) {
	if(insts.isEmpty()) {
		throw new IllegalArgumentException("Cannot generate augmented point from an empty list.");
	}
	int numAttributes = insts.get(0).numAttributes();
	Instance augPoint = new DenseInstance(numAttributes * 2);

	for (int i = 0; i < numAttributes; i++) {
		double lowerBound = Double.POSITIVE_INFINITY;
		double upperBound = Double.NEGATIVE_INFINITY;

		for (Instance inst : insts) {
			double attrValue = inst.value(i);
			lowerBound = Math.min(lowerBound, attrValue);
			upperBound = Math.max(upperBound, attrValue);
		}

		augPoint.setValue(2 * i, lowerBound);
		augPoint.setValue((2 * i) + 1, upperBound);
	}

	return augPoint;
}
 
Example 2
Source File: OneR.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Classifies a given instance.
  *
  * @param inst the instance to be classified
  * @return the classification of the instance
  */
 public double classifyInstance(Instance inst) throws Exception {

   // default model?
   if (m_ZeroR != null) {
     return m_ZeroR.classifyInstance(inst);
   }
   
   int v = 0;
   if (inst.isMissing(m_rule.m_attr)) {
     if (m_rule.m_missingValueClass != -1) {
return m_rule.m_missingValueClass;
     } else {
return 0;  // missing values occur in test but not training set    
     }
   }
   if (m_rule.m_attr.isNominal()) {
     v = (int) inst.value(m_rule.m_attr);
   } else {
     while (v < m_rule.m_breakpoints.length &&
     inst.value(m_rule.m_attr) >= m_rule.m_breakpoints[v]) {
v++;
     }
   }
   return m_rule.m_classifications[v];
 }
 
Example 3
Source File: LbMsm.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Lower bound distance for MSM with early abandon
 *
 * @param q           first time series
 * @param c           second time series
 * @param cc          c param
 * @param qMax        max of first time series
 * @param qMin        min of second time series
 * @param cutOffValue cutoff value for early abandon
 * @return lower bound distance
 */
public static double distance(final Instance q, final Instance c, final double cc, final double qMax, final double qMin, final double cutOffValue) {
    final int len = q.numAttributes() - 1;

    double d = Math.abs(q.value(0) - c.value(0));

    for (int i = 1; i < len; i++) {
        final double curr = c.value(i);
        final double prev = c.value(i - 1);
        if (prev >= curr && curr > qMax) {
            d += Math.min(Math.abs(curr - qMax), cc);
            if (d >= cutOffValue)
                return Double.MAX_VALUE;
        } else if (prev <= curr && curr < qMin) {
            d += Math.min(Math.abs(curr - qMin), cc);
            if (d >= cutOffValue)
                return Double.MAX_VALUE;
        }
    }

    return d;
}
 
Example 4
Source File: HyperPipes.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
    * Updates the bounds arrays with a single instance. Missing values
    * are ignored (i.e. they don't change the bounds for that attribute)
    *
    * @param instance the instance
    * @throws Exception if any missing values are encountered
    */
   public void addInstance(Instance instance) throws Exception {

     for (int j = 0; j < instance.numAttributes(); j++) {
if ((j != m_ClassIndex) && (!instance.isMissing(j))) {

  double current = instance.value(j);

  if (m_NumericBounds[j] != null) { // i.e. a numeric attribute
    if (current < m_NumericBounds[j][0])
      m_NumericBounds[j][0] = current;
    if (current > m_NumericBounds[j][1])
      m_NumericBounds[j][1] = current;

  } else { // i.e. a nominal attribute
    m_NominalBounds[j][(int) current] = true;
  }
}
     }
   }
 
Example 5
Source File: PaceRegression.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Calculate the dependent value for a given instance for a
  * given regression model.
  *
  * @param transformedInstance the input instance
  * @param coefficients an array of coefficients for the regression
  * model
  * @return the regression value for the instance.
  * @throws Exception if the class attribute of the input instance
  * is not assigned
  */
 private double regressionPrediction(Instance transformedInstance,
			      double [] coefficients) 
   throws Exception {

   int column = 0;
   double result = coefficients[column];
   for (int j = 0; j < transformedInstance.numAttributes(); j++) {
     if (m_ClassIndex != j) {
column++;
result += coefficients[column] * transformedInstance.value(j);
     }
   }
   
   return result;
 }
 
Example 6
Source File: IB1.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Updates the minimum and maximum values for all the attributes
  * based on a new instance.
  *
  * @param instance the new instance
  */
 private void updateMinMax(Instance instance) {
   
   for (int j = 0;j < m_Train.numAttributes(); j++) {
     if ((m_Train.attribute(j).isNumeric()) && (!instance.isMissing(j))) {
if (Double.isNaN(m_MinArray[j])) {
  m_MinArray[j] = instance.value(j);
  m_MaxArray[j] = instance.value(j);
} else {
  if (instance.value(j) < m_MinArray[j]) {
    m_MinArray[j] = instance.value(j);
  } else {
    if (instance.value(j) > m_MaxArray[j]) {
      m_MaxArray[j] = instance.value(j);
    }
  }
}
     }
   }
 }
 
Example 7
Source File: ConsistencySubsetEval.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
    * Constructor for a hashKey
    *
    * @param t an instance from which to generate a key
    * @param numAtts the number of attributes
    * @throws Exception if something goes wrong
    */
   public hashKey(Instance t, int numAtts) throws Exception {

     int i;
     int cindex = t.classIndex();

     key = -999;
     attributes = new double [numAtts];
     missing = new boolean [numAtts];
     for (i=0;i<numAtts;i++) {
if (i == cindex) {
  missing[i] = true;
} else {
  if ((missing[i] = t.isMissing(i)) == false) {
    attributes[i] = t.value(i);
  }
}
     }
   }
 
Example 8
Source File: CheckSource.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * compares two Instance
  * 
  * @param inst1	the first Instance object to compare
  * @param inst2	the second Instance object to compare
  * @return		true if both are the same
  */
 protected boolean compare(Instance inst1, Instance inst2) {
   boolean	result;
   int		i;
   
   // check dimension
   result = (inst1.numAttributes() == inst2.numAttributes());
   
   // check content
   if (result) {
     for (i = 0; i < inst1.numAttributes(); i++) {
if (Double.isNaN(inst1.value(i)) && (Double.isNaN(inst2.value(i))))
  continue;

if (inst1.value(i) != inst2.value(i)) {
  result = false;
  System.out.println(
      "Values at position " + (i+1) + " differ (Filter/Source code): " 
      + inst1.value(i) + " != " + inst2.value(i));
  break;
}
     }
   }
   
   return result;
 }
 
Example 9
Source File: COMT2.java    From bestconf with Apache License 2.0 5 votes vote down vote up
private static double computeOmegaDelta(M5P model, M5P modelPi, Instances omega) throws Exception{
	double retval = 0., y;
	Enumeration<Instance> enu = omega.enumerateInstances();
	int idxClass = omega.classIndex();
	Instance ins;
	while(enu.hasMoreElements()){
		ins = enu.nextElement();
		y = ins.value(idxClass);
		retval += Math.pow(y-model.classifyInstance(ins), 2)-Math.pow(y-modelPi.classifyInstance(ins), 2);
	}
	return retval;
}
 
Example 10
Source File: LbKim.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
public static double distance(final Instance query, final Instance reference) {
    double maxQ = query.value(0), maxR = reference.value(0);
    double minQ = query.value(0), minR = reference.value(0);

    final double diffFirsts = maxQ - maxR;
    final double diffLasts = query.value(query.numAttributes() - 2) - reference.value(reference.numAttributes() - 2);
    double minDist = diffFirsts * diffFirsts + diffLasts * diffLasts;

    boolean minFirstLastQ = true, minFirstLastR = true;
    boolean maxFirstLastQ = true, maxFirstLastR = true;
    for (int i = 1; i < query.numAttributes() - 1; i++) {
        if (query.value(i) > maxQ) {
            maxQ = query.value(i);
            maxFirstLastQ = false;
        } else if (query.value(i) < minQ) {
            minQ = query.value(i);
            minFirstLastQ = false;
        }

        if (reference.value(i) > maxR) {
            maxR = reference.value(i);
            maxFirstLastR = false;
        } else if (reference.value(i) < minR) {
            minR = reference.value(i);
            minFirstLastR = false;
        }
    }

    if (!(minFirstLastQ && minFirstLastR)) {
        final double diffMin = minQ - minR;
        minDist += diffMin * diffMin;
    }
    if (!(maxFirstLastQ && maxFirstLastR)) {
        final double diffMax = maxQ - maxR;
        minDist += diffMax * diffMax;
    }

    return minDist;
}
 
Example 11
Source File: LabeledItemSet.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Updates counter of item set with respect to given transaction.
 * 
 * @param instanceNoClass instances without the class attribute
 * @param instanceClass the values of the class attribute sorted according to
 *          instances
 */
public final void upDateCounterTreatZeroAsMissing(Instance instanceNoClass,
    Instance instanceClass) {
  if (containedByTreatZeroAsMissing(instanceNoClass)) {
    m_counter++;
    if (this.m_classLabel == instanceClass.value(0))
      m_ruleSupCounter++;
  }
}
 
Example 12
Source File: BasicDTW.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
* Calculates the distance between two instances.
* 
* @param first 	the first instance
* @param second 	the second instance
* @return 		the distance between the two given instances
*/
 @Override
 public double distance(Instance first, Instance second, double cutOffValue){

     //remove class index from first instance if there iscutOffValue one
     
     int firtClassIndex = first.classIndex();
     double[] arr1;
     if(firtClassIndex > 0){
         arr1 = new double[first.numAttributes()-1];
         for(int i = 0,j = 0; i < first.numAttributes(); i++){
             if(i != firtClassIndex){
                 arr1[j]= first.value(i);
                 j++;
             }
         }
     }else{
         arr1 = first.toDoubleArray();
     }
     
     //remove class index from second instance if there is one
     int secondClassIndex = second.classIndex();
     double[] arr2;
     if(secondClassIndex > 0){
         arr2 = new double[second.numAttributes()-1];
         for(int i = 0,j = 0; i < second.numAttributes(); i++){
             if(i != secondClassIndex){
                 arr2[j]= second.value(i);
                 j++;
             }
         }
     }else{
         arr2 = second.toDoubleArray();
     }
     
     return distance(arr1,arr2,cutOffValue);
 }
 
Example 13
Source File: ResidualSplit.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
public final int whichSubset(Instance instance) 
 throws Exception {

   if (instance.isMissing(m_attIndex))
     return -1;
   else{
     if (instance.attribute(m_attIndex).isNominal())
return (int)instance.value(m_attIndex);
     else
if (Utils.smOrEq(instance.value(m_attIndex),m_splitPoint))
  return 0;
else
  return 1;
   }
 }
 
Example 14
Source File: FPGrowth.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Inserts a single instance into the FPTree.
 * 
 * @param current the instance to insert
 * @param singletons the singleton item sets
 * @param tree the tree to insert into
 * @param minSupport the minimum support threshold
 */
private void insertInstance(Instance current, ArrayList<BinaryItem> singletons, 
    FPTreeRoot tree, int minSupport) {
  ArrayList<BinaryItem> transaction = new ArrayList<BinaryItem>();
  if (current instanceof SparseInstance) {
    for (int j = 0; j < current.numValues(); j++) {
      int attIndex = current.index(j);
      if (singletons.get(attIndex).getFrequency() >= minSupport) {
        transaction.add(singletons.get(attIndex));
      }
    }
    Collections.sort(transaction);
    tree.addItemSet(transaction, 1);
  } else {
    for (int j = 0; j < current.numAttributes(); j++) {
      if (!current.isMissing(j)) {
        if (current.attribute(j).numValues() == 1 
            || current.value(j) == m_positiveIndex - 1) {
          if (singletons.get(j).getFrequency() >= minSupport) {
            transaction.add(singletons.get(j));
          }
        }
      }
    }
    Collections.sort(transaction);
    tree.addItemSet(transaction, 1);
  }
}
 
Example 15
Source File: RDG1.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates a new rule for the decision list
 * and classifies the new example.
 *
 * @param random random number generator
 * @param example the instance to classify
 * @return a list of tests
 * @throws Exception if dataset format not defined
 */
private FastVector generateTestList(Random random, Instance example) 
 throws Exception {

  Instances format = getDatasetFormat();
  if (format == null) 
    throw new Exception("Dataset format not defined.");

  int numTests = getNumAttributes() - getNumIrrelevant();
  FastVector TestList = new FastVector(numTests);
  boolean[] irrelevant = getAttList_Irr();

  for (int i = 0; i < getNumAttributes(); i++) {
    if (!irrelevant[i]) {
      Test newTest = null;
      Attribute att = example.attribute(i);
      if (att.isNumeric()) {
        double newSplit = random.nextDouble();
        boolean newNot = newSplit < example.value(i);
        newTest = new Test(i, newSplit, format, newNot);
      } else {
        newTest = new Test(i, example.value(i), format, false);
      }
    TestList.addElement (newTest);     
    }
  }
  
  return TestList;
}
 
Example 16
Source File: UCRSuitePrunedDTW.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void buildClassifier(Instances data) throws Exception {
   	// Initialise training dataset
	Attribute classAttribute = data.classAttribute();
	
	classedData = new HashMap<>();
	classedDataIndices = new HashMap<>();
	for (int c = 0; c < data.numClasses(); c++) {
		classedData.put(data.classAttribute().value(c), new ArrayList<SymbolicSequence>());
		classedDataIndices.put(data.classAttribute().value(c), new ArrayList<Integer>());
	}

	train = new SymbolicSequence[data.numInstances()];
	classMap = new String[train.length];
	maxLength = 0;
	for (int i = 0; i < train.length; i++) {
		Instance sample = data.instance(i);
		MonoDoubleItemSet[] sequence = new MonoDoubleItemSet[sample.numAttributes() - 1];
		maxLength = Math.max(maxLength, sequence.length);
		int shift = (sample.classIndex() == 0) ? 1 : 0;
		for (int t = 0; t < sequence.length; t++) {
			sequence[t] = new MonoDoubleItemSet(sample.value(t + shift));
		}
		train[i] = new SymbolicSequence(sequence);
		String clas = sample.stringValue(classAttribute);
		classMap[i] = clas;
		classedData.get(clas).add(train[i]);
		classedDataIndices.get(clas).add(i);
	}
			
	warpingMatrix = new double[maxLength][maxLength];
	U = new double[maxLength];
	L = new double[maxLength];
	U1 = new double[maxLength];
	L1 = new double[maxLength];
	
	maxWindow = Math.round(1 * maxLength);
	searchResults = new String[maxWindow+1];
	nns = new int[maxWindow+1][train.length];
	dist = new double[train.length][train.length];

	cache = new SequenceStatsCache(train, maxWindow);
	
	lazyUCR = new LazyAssessNNEarlyAbandon[train.length][train.length];
	
	for (int i = 0; i < train.length; i++) {
		for (int j  = 0; j < train.length; j++) {
			lazyUCR[i][j] = new LazyAssessNNEarlyAbandon(cache);
		}
	}
	
	// Start searching for the best window
	searchBestWarpingWindow();

	// Saving best windows found
	System.out.println("Windows found=" + bestWarpingWindow + " Best Acc=" + (1-bestScore));
}
 
Example 17
Source File: REPTree.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
    * Inserts an instance from the hold-out set into the tree.
    * 
    * @param inst the instance to insert
    * @param weight the weight of the instance
    * @param parent the parent of the node
    * @throws Exception if insertion fails
    */
   protected void insertHoldOutInstance(Instance inst, double weight, 
				 Tree parent) throws Exception {
     
     // Insert instance into hold-out class distribution
     if (inst.classAttribute().isNominal()) {

// Nominal case
m_HoldOutDist[(int)inst.classValue()] += weight;
int predictedClass = 0;
if (m_ClassProbs == null) {
  predictedClass = Utils.maxIndex(parent.m_ClassProbs);
} else {
  predictedClass = Utils.maxIndex(m_ClassProbs);
}
if (predictedClass != (int)inst.classValue()) {
  m_HoldOutError += weight;
}
     } else {

// Numeric case
m_HoldOutDist[0] += weight;
       m_HoldOutDist[1] += weight * inst.classValue();
double diff = 0;
if (m_ClassProbs == null) {
  diff = parent.m_ClassProbs[0] - inst.classValue();
} else {
  diff =  m_ClassProbs[0] - inst.classValue();
}
m_HoldOutError += diff * diff * weight;
     }	
     
     // The process is recursive
     if (m_Attribute != -1) {

// If node is not a leaf
if (inst.isMissing(m_Attribute)) {
  
  // Distribute instance
  for (int i = 0; i < m_Successors.length; i++) {
    if (m_Prop[i] > 0) {
      m_Successors[i].insertHoldOutInstance(inst, weight * 
					    m_Prop[i], this);
    }
  }
} else {
  
  if (m_Info.attribute(m_Attribute).isNominal()) {
    
    // Treat nominal attributes
    m_Successors[(int)inst.value(m_Attribute)].
      insertHoldOutInstance(inst, weight, this);
  } else {
    
    // Treat numeric attributes
    if (inst.value(m_Attribute) < m_SplitPoint) {
      m_Successors[0].insertHoldOutInstance(inst, weight, this);
    } else {
      m_Successors[1].insertHoldOutInstance(inst, weight, this);
    }
  }
}
     }
   }
 
Example 18
Source File: LbEnhanced.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
public static double distance(final Instance a, final Instance b,
                              final double[] U, final double[] L,
                              final int w, final int v, final double cutOffValue) {
    final int n = a.numAttributes() - 1;
    final int m = b.numAttributes() - 1;
    final int l = n - 1;
    final int nBands = Math.min(l / 2, v);
    final int lastIndex = l - nBands;
    final double d00 = a.value(0) - b.value(0);
    final double dnm = a.value(n - 1) - b.value(m - 1);

    int i, j, rightEnd, rightStart;
    double minL, minR, tmp, aVal;

    double res = d00 * d00 + dnm * dnm;

    for (i = 1; i < nBands; i++) {
        rightEnd = l - i;
        minL = a.value(i) - b.value(i);
        minL *= minL;
        minR = a.value(rightEnd) - b.value(rightEnd);
        minR *= minR;
        for (j = Math.max(0, i - w); j < i; j++) {
            rightStart = l - j;
            tmp = a.value(i) - b.value(j);
            minL = Math.min(minL, tmp * tmp);
            tmp = a.value(j) - b.value(i);
            minL = Math.min(minL, tmp * tmp);

            tmp = a.value(rightEnd) - b.value(rightStart);
            minR = Math.min(minR, tmp * tmp);
            tmp = a.value(rightStart) - b.value(rightEnd);
            minR = Math.min(minR, tmp * tmp);
        }
        res += minL + minR;
    }
    if (res >= cutOffValue)
        return Double.POSITIVE_INFINITY;

    for (i = nBands; i <= lastIndex; i++) {
        aVal = a.value(i);
        if (aVal > U[i]) {
            tmp = aVal - U[i];
            res += tmp * tmp;
        } else if (aVal < L[i]) {
            tmp = L[i] - aVal;
            res += tmp * tmp;
        }
    }

    return res;
}
 
Example 19
Source File: AddNoise.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
  * method to set a new value
  *
  * @param r random function
  * @param numOfValues 
  * @param instance
  * @param useMissing
  */
 private void changeValueRandomly(Random r, int numOfValues,
                                  int indexOfAtt, 
                                  Instance instance, 
                                  boolean useMissing) {
   int currValue;

   // get current value 
   // if value is missing set current value to number of values
   // whiche is the highest possible value plus one 
   if (instance.isMissing(indexOfAtt)) {
     currValue = numOfValues;
   } else {
     currValue = (int) instance.value(indexOfAtt);
   }

   // with only two possible values it is easier
   if ((numOfValues == 2) && (!instance.isMissing(indexOfAtt))) {
instance.setValue(indexOfAtt, (double) ((currValue+1)% 2));
   } else {
     // get randomly a new value not equal to the current value
     // if missing values are used as values they must be treated
     // in a special way
     while (true) {
  int newValue;
       if (useMissing) {
         newValue = (int) (r.nextDouble() * (double) (numOfValues + 1));
       } else {
         newValue = (int) (r.nextDouble() * (double) numOfValues);
       }
       // have we found a new value?
       if (newValue != currValue) { 
         // the value 1 above the highest possible value (=numOfValues)
         // is used as missing value
         if (newValue == numOfValues) { instance.setMissing(indexOfAtt); }
         else { instance.setValue(indexOfAtt, (double) newValue); }
         break;
       }
     }
   }
 }
 
Example 20
Source File: ItemSet.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks if an instance contains an item set.
 * 
 * @param instance the instance to be tested
 * @return true if the given instance contains this item set
 */
public boolean containedByTreatZeroAsMissing(Instance instance) {

  if (instance instanceof weka.core.SparseInstance) {
    int numInstVals = instance.numValues();
    int numItemSetVals = m_items.length;

    for (int p1 = 0, p2 = 0; p1 < numInstVals || p2 < numItemSetVals;) {
      int instIndex = Integer.MAX_VALUE;
      if (p1 < numInstVals) {
        instIndex = instance.index(p1);
      }
      int itemIndex = p2;

      if (m_items[itemIndex] > -1) {
        if (itemIndex != instIndex) {
          return false;
        } else {
          if (instance.isMissingSparse(p1)) {
            return false;
          }
          if (m_items[itemIndex] != (int) instance.valueSparse(p1)) {
            return false;
          }
        }

        p1++;
        p2++;
      } else {
        if (itemIndex < instIndex) {
          p2++;
        } else if (itemIndex == instIndex) {
          p2++;
          p1++;
        }
      }
    }
  } else {
    for (int i = 0; i < instance.numAttributes(); i++)
      if (m_items[i] > -1) {
        if (instance.isMissing(i) || (int) instance.value(i) == 0)
          return false;
        if (m_items[i] != (int) instance.value(i))
          return false;
      }
  }

  return true;
}