Java Code Examples for weka.core.Instances#firstInstance()

The following examples show how to use weka.core.Instances#firstInstance() . 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: WDTW1NN.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
//        for(int i = 0; i < 10; i++){
//            runComparison();
//        }

        Instances train = DatasetLoading.loadDataNullable("C:/users/sjx07ngu/dropbox/tsc problems/SonyAiboRobotSurface1/SonyAiboRobotSurface1_TRAIN");

        Instance one, two;
        one = train.firstInstance();
        two = train.lastInstance();
        WeightedDTW wdtw;
        WDTW1NN wnn = new WDTW1NN();
        double g;
        for (int paramId = 0; paramId < 100; paramId++) {
            g = (double) paramId / 100;
            wdtw = new WeightedDTW(g);

            wnn.setParamsFromParamId(train, paramId);
            System.out.print(wdtw.distance(one, two) + "\t");
            System.out.println(wnn.distance(one, two, Double.MAX_VALUE));

        }


    }
 
Example 2
Source File: SimpleMI.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Computes the distribution for a given exemplar
 *
 * @param newBag the exemplar for which distribution is computed
 * @return the distribution
 * @throws Exception if the distribution can't be computed successfully
 */
public double[] distributionForInstance(Instance newBag)
  throws Exception {

  double [] distribution = new double[2];
  Instances test = new Instances (newBag.dataset(), 0);	
  test.add(newBag);	

  test = transform(test);
  test.deleteAttributeAt(0);
  Instance newInst=test.firstInstance();

  distribution = m_Classifier.distributionForInstance(newInst);

  return distribution;	   
}
 
Example 3
Source File: BestConf.java    From bestconf with Apache License 2.0 6 votes vote down vote up
public static void getBestPerfFrom(String path){
	try {
		BestConf bestconf = new BestConf();
		Instances trainingSet = DataIOFile.loadDataFromArffFile(path);
		Instance best = trainingSet.firstInstance();
		//set the best configuration to the cluster
		Map<Attribute,Double> attsmap = new HashMap<Attribute,Double>();
		for(int i=0;i<best.numAttributes()-1;i++){
			attsmap.put(best.attribute(i), best.value(i));
		}

		double bestPerf = bestconf.setOptimal(attsmap, "getBestPerfFrom");
		System.out.println("=========================================");
		System.err.println("The actual performance for the best point is : "+bestPerf);
		System.out.println("=========================================");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: NN_DTW_A.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
Pair<List<Double>, List<Double>> findScores(Instances data){
    List<Double> S_dSuccess = new ArrayList<>();
    List<Double> S_iSuccess = new ArrayList<>();
    
    for(int i=0; i<data.numInstances(); i++){
        try {
            //LOOCV search for distances.
            Instances cv_train = data.trainCV(data.numInstances(), i);
            Instances cv_test = data.testCV(data.numInstances(), i);
            Instance test = cv_test.firstInstance();
            
            Pair<Instance, Double> pair_D = findMinDistance(cv_train, test, D);
            Pair<Instance, Double> pair_I = findMinDistance(cv_train, test, I);
            
            //we know we only have one instance.
            double pred_d = pair_D.var1.classValue();
            double pred_i = pair_I.var1.classValue();
            double dist_d = pair_D.var2;
            double dist_i = pair_I.var2;
            double S = dist_d / (dist_i+0.000000001);
            
            //if d is correct and i is incorrect.
            if(test.classValue() == pred_d && test.classValue() != pred_i)
                S_dSuccess.add(S);
            //if d is incorrect and i is correct.
            if(test.classValue() != pred_d && test.classValue() == pred_i)
                S_iSuccess.add(S);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        
    }
   
    return new Pair(S_dSuccess, S_iSuccess);
}
 
Example 5
Source File: RDG1.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Resets the class values of all instances using voting.
 * For each instance the class value that satisfies the most rules
 * is choosen as new class value.
 *
 * @param dataset the dataset to work on
 * @return the changed instances
 * @throws Exception if something goes wrong
 */
private Instances voteDataset(Instances dataset) throws Exception {
  for (int i = 0; i < dataset.numInstances(); i++) {
    Instance inst = dataset.firstInstance();
    inst = votedReclassifyExample(inst); 
    dataset.add(inst);
    dataset.delete(0);
  }  

  return dataset;
}
 
Example 6
Source File: WekaUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Instance useFilterOnSingleInstance(final Instance instance, final Filter filter) throws Exception {
	Instances data = new Instances(instance.dataset());
	data.clear();
	data.add(instance);
	Instances filteredInstances = Filter.useFilter(data, filter);
	return filteredInstances.firstInstance();
}
 
Example 7
Source File: UnsupervisedShapelets.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
private void extractUShapelets(Instances data){
    int[] shapeletLengths = {25, 50};

    if (data.numAttributes() < 50){
        shapeletLengths = new int[]{data.numAttributes()/2};
    }

    shapelets = new ArrayList();
    numInstances = data.size();
    Instance inst = data.firstInstance();
    boolean finished = false;

    while (!finished){
        ArrayList<UShapelet> shapeletCandidates = new ArrayList();

        //Finds all candidate shapelets on the selected instance
        for (int i = 0; i < shapeletLengths.length; i++){
            for (int n = 0; n < inst.numAttributes() - shapeletLengths[i]; n++){
                UShapelet candidate = new UShapelet(n, shapeletLengths[i], inst);
                candidate.computeGap(data);
                shapeletCandidates.add(candidate);
            }
        }

        double maxGap = -1;
        int maxGapIndex = -1;

        //Finds the shapelet with the highest gap value
        for (int i = 0; i < shapeletCandidates.size(); i++){
            if (shapeletCandidates.get(i).gap > maxGap){
                maxGap = shapeletCandidates.get(i).gap;
                maxGapIndex = i;
            }
        }

        //Adds the shapelet with the best gap value to the pool of shapelets
        UShapelet best = shapeletCandidates.get(maxGapIndex);
        shapelets.add(best);

        double[] distances = best.computeDistances(data);
        ArrayList<Double> lesserDists = new ArrayList();
        double maxDist = -1;
        int maxDistIndex = -1;

        //Finds the instance with the max dist to the shapelet and all with a dist lower than the distance used
        //to generate the gap value.
        for (int i = 0; i < distances.length; i++){
            if (distances[i] < best.dt){
                lesserDists.add(distances[i]);
            }
            else if (distances[i] > maxDist){
                maxDist = distances[i];
                maxDistIndex = i;
            }
        }

        //Use max dist instance to generate new shapelet and remove low distance instances
        if (lesserDists.size() == 1){
            finished = true;
        }
        else{
            inst = data.get(maxDistIndex);

            double mean = mean(lesserDists);
            double cutoff = mean + standardDeviation(lesserDists, mean);

            Instances newData = new Instances(data, 0);

            for (int i = 0; i < data.numInstances(); i++){
                if (distances[i] >= cutoff){
                    newData.add(data.get(i));
                }
            }

            data = newData;

            if (data.size() == 1){
                finished = true;
            }
        }
    }
}
 
Example 8
Source File: GridModelDataPredictVS.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
public void dataAvailable(String inputStreamName, StreamElement data) { 

//mapping the input stream to an instance and setting its dataset
String[] dfn = data.getFieldNames().clone();
Byte[] dft = data.getFieldTypes().clone();
Serializable[] da = data.getData().clone();
data = new StreamElement(dfn, dft, da, data.getTimeStamp());
Instance i = instanceFromStream(data);
if (att.size() == 0){
	att = attFromStream(data);
}
dataset = new Instances("input",att,0);
dataset.setClassIndex(classIndex);
if(i != null){
	dataset.add(i);
	i = dataset.firstInstance();
	
	boolean success = true;
	
	//extracting latitude/longitude
	Double center_lat = i.value(1);
	Double center_long = i.value(2);
	
	//filling the grid with predictions/extrapolations
	Double[][] rawData = new Double[gridSize][gridSize];
	for (int j=0;j<gridSize;j++){
		for(int k=0;k<gridSize;k++){
			i.setValue(1, center_lat - (cellSize*gridSize/2) + cellSize * j);
			i.setValue(2, center_long - (cellSize*gridSize/2) + cellSize * k);
			rawData[j][k] = ms.predict(i);
			success = success && (rawData[j][k] != null);
		}
	}

	//preparing the output
	
	Serializable[] stream = new Serializable[7];
       try {

           ByteArrayOutputStream bos = new ByteArrayOutputStream();
           ObjectOutputStream oos = new ObjectOutputStream(bos);
           oos.writeObject(rawData);
           oos.flush();
           oos.close();
           bos.close();

           stream[0] = new Integer(gridSize);
           stream[1] = new Integer(gridSize);
           stream[2] = new Double(center_lat - (cellSize*gridSize/2));
           stream[3] = new Double(center_long - (cellSize*gridSize/2));
           stream[4] = new Double(cellSize);
           stream[5] = new Double(0);
           stream[6] = bos.toByteArray();

       } catch (IOException e) {
           logger.warn(e.getMessage(), e);
           success = false;
       }
       
       if(success){
       	StreamElement se = new StreamElement(getOutputFormat(), stream, data.getTimeStamp());
       	dataProduced(se);
       }else{
		logger.warn("Prediction error. Something get wrong with the prediction.");
	}

}else{
	logger.warn("Predicting instance has wrong attibutes, please check the model and the inputs.");
}
  }
 
Example 9
Source File: SAX.java    From tsml with GNU General Public License v3.0 1 votes vote down vote up
/**
 * Will perform a SAX transformation on a single data series passed as a double[], input format
 * must already be known. 
 * 
 * Generally to be used 
 * in the SAX_1NN classifier (essentially a wrapper classifier that just feeds SAX-filtered
 * data to a 1NN classifier) to filter individual instances during testing
 * 
 * Instance objects need the header info as well as the basic data
 * 
 * @param alphabetSize size of SAX alphabet
 * @param numIntervals size of resulting word
 * @throws Exception 
 */
public Instance convertInstance(Instance inst, int alphabetSize, int numIntervals) throws Exception {

    Instances newInsts = new Instances(inputFormat, 1);
    newInsts.add(inst);
    
    newInsts = process(newInsts);
    
    return newInsts.firstInstance();
}