类weka.core.DenseInstance源码实例Demo

下面列出了怎么用weka.core.DenseInstance的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: AILibs   文件: WekaUtil.java
public static Instance getRefactoredInstance(final Instance instance, final List<String> classes) {

		/* modify instance */
		Instances dataset = WekaUtil.getEmptySetOfInstancesWithRefactoredClass(instance.dataset(), classes);
		int numAttributes = instance.numAttributes();
		int classIndex = instance.classIndex();
		Instance iNew = new DenseInstance(numAttributes);
		for (int i = 0; i < numAttributes; i++) {
			Attribute a = instance.attribute(i);
			if (i != classIndex) {
				iNew.setValue(a, instance.value(a));
			} else {
				iNew.setValue(a, 0.0); // the value does not matter since this should only be used for TESTING
			}
		}
		dataset.add(iNew);
		iNew.setDataset(dataset);
		return iNew;
	}
 
源代码2 项目: tsml   文件: BOSSC45.java
@Override
public double classifyInstance(Instance instance) throws Exception {
    Bag testBag = BOSSTransform(instance);

    //convert bag to instance
    double[] init = new double[bagInsts.numAttributes()];
    init[init.length-1] = testBag.getClassVal();

    //TEMPORARILY create it on the end of the train insts to easily copy over the attribute data.
    bagInsts.add(new DenseInstance(1, init));
    for (Entry<BitWordInt,Integer> entry : testBag.entrySet()) {
        Attribute att = bagInsts.attribute(entry.getKey().toString());
        if (att != null)
            bagInsts.get(bagInsts.size()-1).setValue(att, entry.getValue());
    }

    Instance testInst = bagInsts.remove(bagInsts.size()-1);

    return tree.classifyInstance(testInst);
}
 
源代码3 项目: tsml   文件: BOSSC45.java
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    Bag testBag = BOSSTransform(instance);

    //convert bag to instance
    double[] init = new double[bagInsts.numAttributes()];
    init[init.length-1] = testBag.getClassVal();

    //TEMPORARILY create it on the end of the train isnts to easily copy over the attribute data.
    bagInsts.add(new DenseInstance(1, init));
    for (Entry<BitWordInt,Integer> entry : testBag.entrySet()) {
        Attribute att = bagInsts.attribute(entry.getKey().toString());
        if (att != null)
            bagInsts.get(bagInsts.numInstances()-1).setValue(att, entry.getValue());
    }
    Instance testInst = bagInsts.remove(bagInsts.size()-1);

    return tree.distributionForInstance(testInst);
}
 
源代码4 项目: tsml   文件: BoTSWEnsemble.java
public BoTSW_Bag buildTestBag(Instance instnc) throws Exception {
    double[][] features = extractFeatures(toArrayNoClass(instnc));

    //cluster/form histograms
    Instances testFeatures = new Instances(clusterData, features.length);
    double[] hist = new double[params.k];
    for (int i = 0; i < features.length; ++i) {
        testFeatures.add(new DenseInstance(1, features[i]));
        int cluster = kmeans.clusterInstance(testFeatures.get(i));
        ++hist[cluster];
    }

    hist = normaliseHistogramSSR(hist);
    hist = normaliseHistograml2(hist);

    return new BoTSW_Bag(hist, instnc.classValue());
}
 
@Override
public int classNum(int x, int y, final Raster raster) throws Exception {
   if (model==null) throw new IllegalStateException("Model is null. Please call initialize() before to set a mask model.");
   if (tissueFeatures==null) throw new IllegalStateException("tissueFeatures is null. Please call initialize() before to set a mask model.");
   int w = model.getFeatureDescription().getWindowSize();
   int xr = x;
   int yr = y;
   if (xr<raster.getMinX()+w) xr = raster.getMinX()+w;
   if (yr<raster.getMinY()+w) yr = raster.getMinY()+w;
   if (xr>raster.getMinX()+raster.getWidth()-1-w) xr = raster.getMinX()+raster.getWidth()-1-w;
   if (yr>raster.getMinY()+raster.getHeight()-1-w) yr = raster.getMinY()+raster.getHeight()-1-w;
   double[] features = tissueFeatures.buildFeatures(raster, xr, yr, Double.NaN);
   Instance instance = new DenseInstance(1d,features);
   instance.setDataset(model.getStructure());
   int clazz = (int) model.getClassifier().classifyInstance(instance);
   return clazz;
}
 
源代码6 项目: tsml   文件: RankOrder.java
public Instances process(Instances inst) throws Exception {
//Set input instance format		  
		 
		  Instances result = new Instances(determineOutputFormat(inst), 0);
		  rankOrder(inst);
//Stuff into new set of instances
		  for(int i=0;i<inst.numInstances();i++) {
//Create a deep copy, think this is necessary to maintain meta data?
			  Instance in=new DenseInstance(inst.instance(i)); 
//Reset to the ranks
			  for(int j=0;j<numAtts;j++)
				  in.setValue(j, ranks[i][j]);
			  result.add(in);
		  }
		  if(normalise){
			  NormalizeAttribute na=new NormalizeAttribute(result);
			  result=na.process(result);
		  }
		  return result;

	  }
 
public SentimentClass.ThreeWayClazz classify(String sentence) throws Exception {
    double[] instanceValue = new double[dataRaw.numAttributes()];
    instanceValue[0] = dataRaw.attribute(0).addStringValue(sentence);

    Instance toClassify = new DenseInstance(1.0, instanceValue);
    dataRaw.setClassIndex(1);
    toClassify.setDataset(dataRaw);

    double prediction = this.classifier.classifyInstance(toClassify);

    double distribution[] = this.classifier.distributionForInstance(toClassify);

    if (distribution[0] != distribution[1])
        return SentimentClass.ThreeWayClazz.values()[(int)prediction];
    else
        return SentimentClass.ThreeWayClazz.NEUTRAL;
}
 
源代码8 项目: AILibs   文件: WekaInstancesUtil.java
public static Instances datasetToWekaInstances(final ILabeledDataset<? extends ILabeledInstance> dataset) throws UnsupportedAttributeTypeException {
	Instances wekaInstances = createDatasetFromSchema(dataset.getInstanceSchema());
	int expectedAttributes = dataset.getInstanceSchema().getNumAttributes();
	for (ILabeledInstance inst : dataset) {
		if (inst.getNumAttributes() != expectedAttributes) {
			throw new IllegalStateException("Dataset scheme defines a number of " + expectedAttributes + " attributes, but instance has " + inst.getNumAttributes() + ". Attributes in scheme: " + dataset.getInstanceSchema().getAttributeList().stream().map(a -> "\n\t" + a.getName() + " (" + a.toString() + ")").collect(Collectors.joining()) + ". Attributes in instance: " + Arrays.stream(inst.getAttributes()).map(a -> "\n\t" + a.toString()).collect(Collectors.joining()));
		}
		double[] point = inst.getPoint();
		double[] pointWithLabel = Arrays.copyOf(point, point.length + 1);
		DenseInstance iNew = new DenseInstance(1, pointWithLabel);
		iNew.setDataset(wekaInstances);
		if (dataset.getLabelAttribute() instanceof ICategoricalAttribute) {
			iNew.setClassValue(((ICategoricalAttribute) dataset.getLabelAttribute()).getLabelOfCategory((int)inst.getLabel()));
		} else {
			iNew.setClassValue(Double.parseDouble(inst.getLabel().toString()));
		}
		wekaInstances.add(iNew); // this MUST come here AFTER having set the class value; otherwise, the class is not registered correctly in the Instances object!!
	}
	return wekaInstances;
}
 
源代码9 项目: AILibs   文件: WekaTimeseriesUtil.java
/**
 * Converts a double[][] matrix (number of instances x number of attributes) to
 * Weka instances without any class attribute.
 *
 * @param matrix
 *            The double[][] matrix storing all the attribute values of the
 *            instances
 * @return Returns the Weka Instances object consisting of all instances and the
 *         attribute values
 */
public static Instances matrixToWekaInstances(final double[][] matrix) {
	final ArrayList<Attribute> attributes = new ArrayList<>();
	for (int i = 0; i < matrix[0].length; i++) {
		final Attribute newAtt = new Attribute("val" + i);
		attributes.add(newAtt);
	}
	Instances wekaInstances = new Instances(I_NAME, attributes, matrix.length);
	for (int i = 0; i < matrix[0].length; i++) {
		final Instance inst = new DenseInstance(1, matrix[i]);
		inst.setDataset(wekaInstances);
		wekaInstances.add(inst);
	}

	return wekaInstances;
}
 
源代码10 项目: tsml   文件: AttributeFilterBridge.java
public Instance filterInstance(Instance ins){
	int nosDeleted=0;
	int nosKept=0;
	int dataPos=0;
	Instance newIns=new DenseInstance(ins);
		//Advance to the next to keep
	while(dataPos<newIns.numAttributes()-1 && nosKept<attsToKeep.length){
		while(dataPos!=attsToKeep[nosKept]-nosDeleted && dataPos<newIns.numAttributes()-1){
			newIns.deleteAttributeAt(dataPos);
			nosDeleted++;
		}
		nosKept++;
		dataPos++;
	}
	while(dataPos<newIns.numAttributes()-1)
		newIns.deleteAttributeAt(dataPos);
	return newIns;
	
}
 
源代码11 项目: tsml   文件: MINND.java
/**
 * Scale the given exemplar so that the returned exemplar
 * has the value of 0 to 1 for each dimension
 * 
 * @param before the given exemplar
 * @return the resultant exemplar after scaling
 * @throws Exception if given exampler cannot be scaled properly
 */
private Instance scale(Instance before) throws Exception{

  Instances afterInsts = before.relationalValue(1).stringFreeStructure();
  Instance after = new DenseInstance(before.numAttributes());
  after.setDataset(m_Attributes);

  for(int i=0; i < before.relationalValue(1).numInstances(); i++){
    Instance datum = before.relationalValue(1).instance(i);
    Instance inst = (Instance)datum.copy();

    for(int j=0; j < m_Dimension; j++){
      if(before.relationalValue(1).attribute(j).isNumeric())
        inst.setValue(j, (datum.value(j) - m_MinArray[j])/(m_MaxArray[j] - m_MinArray[j]));	
    }
    afterInsts.add(inst);
  }

  int attValue = after.attribute(1).addRelation(afterInsts);
  after.setValue(0, before.value( 0));
  after.setValue(1, attValue);	
  after.setValue(2, before.value( 2));

  return after;
}
 
源代码12 项目: AILibs   文件: DataSetUtilsTest.java
public void cifar10InstancesAttributesTest() {
    ArrayList<Attribute> atts = new ArrayList<>();
    for (int i = 0; i < 32 * 32 * 3 + 1; i++) {
        atts.add(new Attribute("blub" + i));
    }
    Instances instances = new Instances("test", atts, 1);
    DenseInstance inst = new DenseInstance(atts.size());
    for (int i = 0; i < inst.numAttributes(); i++) {
        inst.setValue(i, 1d);
    }
    inst.setDataset(instances);
    instances.add(inst);

    INDArray result = DataSetUtils.cifar10InstanceToMatrix(inst);
    Assert.assertArrayEquals(new long[]{32, 32, 3}, result.shape());
}
 
源代码13 项目: tsml   文件: MergeInfrequentNominalValues.java
/**
 * Processes the given data.
 *
 * @param instances   the data to process
 * @return            the modified data
 * @throws Exception  in case the processing goes wrong
 */
public Instances process(Instances instances) throws Exception {

  // Generate the output and return it
  Instances result = new Instances(getOutputFormat(), instances.numInstances());
  for (int i = 0; i < instances.numInstances(); i++) {
    Instance inst = instances.instance(i);
    double[] newData = new double[instances.numAttributes()];
    for (int j = 0; j < instances.numAttributes(); j++) {
      if (m_AttToBeModified[j] && !inst.isMissing(j)) {
        newData[j] = m_NewValues[j][(int)inst.value(j)];
      } else {
        newData[j] = inst.value(j);
      }
    }
    DenseInstance instNew = new DenseInstance(1.0, newData);
    instNew.setDataset(result);
    
    // copy possible strings, relational values...
    copyValues(instNew, false, inst.dataset(), getOutputFormat());

    // Add instance to output
    result.add(instNew);
  }
  return result;
}
 
源代码14 项目: tsml   文件: StackingOnDists.java
@Override
protected Instance buildInst(double[][] dists, Double classVal) {
    double[] instData = new double[numOutputAtts];
    
    int i = 0;
    for (int m = 0; m < dists.length; m++) 
        for (int c = 0; c < numClasses; c++) 
            instData[i++] = dists[m][c];
    
    assert(i == numOutputAtts-1);
    
    if (classVal != null)
        instData[i] = classVal; 
    //else irrelevent 
    
    instsHeader.add(new DenseInstance(1.0, instData));
    return instsHeader.remove(0);
}
 
源代码15 项目: tsml   文件: InstanceTools.java
public static Instance shiftSeries(Instance inst, int shift){
    Instance newInst = new DenseInstance(inst);

    if (shift < 0){
        shift = Math.abs(shift);

        for (int i = 0; i < inst.numAttributes()-shift-1; i++){
            newInst.setValue(i, inst.value(i+shift));
        }

        for (int i = inst.numAttributes()-shift-1; i < inst.numAttributes()-1; i++){
            newInst.setValue(i, 0);
        }
    }
    else if (shift > 0){
        for (int i = 0; i < shift; i++){
            newInst.setValue(i, 0);
        }

        for (int i = shift; i < inst.numAttributes()-1; i++){
            newInst.setValue(i, inst.value(i-shift));
        }
    }

    return newInst;
}
 
源代码16 项目: tsml   文件: InstanceTools.java
public static Instance randomlyAlterSeries(Instance inst, Random rand){
    Instance newInst = new DenseInstance(inst);

    if (rand.nextBoolean()){
        newInst = reverseSeries(newInst);
    }

    int shift = rand.nextInt(240)-120;
    newInst = shiftSeries(newInst, shift);

    if (rand.nextBoolean()){
        newInst = randomlyAddToSeriesValues(newInst, rand, 0, 5, Integer.MAX_VALUE);
    }
    else{
        newInst = randomlySubtractFromSeriesValues(newInst, rand, 0, 5, 0);
    }

    return newInst;
}
 
源代码17 项目: chuidiang-ejemplos   文件: DecisionTree.java
public static void main(String[] args) throws Exception {
    Classifier j48 = new J48();
    Instances trainingData = GenerateTestVessels.getData();
    j48.buildClassifier(trainingData);
    System.out.println(j48);



    double[] vesselUnderTest = GenerateTestVessels.getBarco(5);

    DenseInstance inst = new DenseInstance(1.0,vesselUnderTest);
    inst.setDataset(trainingData);
    inst.setClassMissing();
    System.out.println(inst);

    double result = j48.classifyInstance(inst);
    System.out.println(GenerateTestVessels.types[(int)result]);

    SerializationHelper.write(new FileOutputStream("tmp"), j48);
    J48 j48Read = (J48)SerializationHelper.read(new FileInputStream("tmp"));
}
 
源代码18 项目: AILibs   文件: DataSetUtils.java
public static Instance matrixToInstance(final INDArray instance, final Instances refInstances) {
	if (instance == null || refInstances == null) {
		throw new IllegalArgumentException("Parameter 'instance' and 'refInstances' must not be null!");
	}

	// Create attributes
	final ArrayList<Attribute> attributes = new ArrayList<>();
	for (int i = 0; i < instance.length(); i++) {
		final Attribute newAtt = new Attribute("val" + i);
		attributes.add(newAtt);
	}

	final List<String> classValues = IntStream.range(0, refInstances.classAttribute().numValues()).asDoubleStream().mapToObj(String::valueOf).collect(Collectors.toList());
	final Attribute classAtt = new Attribute(CLASS_ATT_NAME, classValues);
	attributes.add(classAtt);

	final Instances result = new Instances(INSTANCES_DS_NAME, attributes, refInstances.size());
	result.setClassIndex(result.numAttributes() - 1);

	// Initialize instance
	final Instance inst = new DenseInstance(1, ArrayUtils.addAll(Nd4j.toFlattened(instance).toDoubleVector(), 0));
	inst.setDataset(result);

	return inst;
}
 
源代码19 项目: NeurophFramework   文件: WekaNeurophSample.java
/**
 * Test NeurophWekaClassifier
 *
 * @param wekaDataset Instances Weka data set
 */
private static void testNeurophWekaClassifier(Instances wekaDataset) {
    try {
        MultiLayerPerceptron neuralNet = new MultiLayerPerceptron(4, 16, 3);

        // set labels manualy
        neuralNet.getOutputNeurons().get(0).setLabel("Setosa");
        neuralNet.getOutputNeurons().get(1).setLabel("Versicolor");
        neuralNet.getOutputNeurons().get(2).setLabel("Virginica");

        // initialize NeurophWekaClassifier
        WekaNeurophClassifier neurophWekaClassifier = new WekaNeurophClassifier(neuralNet);
        // set class index on data set
        wekaDataset.setClassIndex(4);
        
        // process data set
        neurophWekaClassifier.buildClassifier(wekaDataset);

        // test item
        //double[] item = {5.1, 3.5, 1.4, 0.2, 0.0}; // normalized item is below
        double[] item = {0.22222222222222213, 0.6249999999999999, 0.06779661016949151, 0.04166666666666667, 0};

        // create weka instance for test item
        Instance instance = new DenseInstance(1, item);

        // test classification
        System.out.println("NeurophWekaClassifier - classifyInstance for {5.1, 3.5, 1.4, 0.2}");
        System.out.println("Class idx: "+neurophWekaClassifier.classifyInstance(instance));
        System.out.println("NeurophWekaClassifier - distributionForInstance for {5.1, 3.5, 1.4, 0.2}");
        double dist[] = neurophWekaClassifier.distributionForInstance(instance);            
        for (int i=0; i<dist.length; i++ ) {
            System.out.println("Class "+i+": "+dist[i]);
        }

    } catch (Exception ex) {
        Logger.getLogger(WekaNeurophSample.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
源代码20 项目: NLIWOD   文件: EntityTypeTest.java
@Test
public void dateTest2() {
	EntityDate dateana = new EntityDate();
	ArrayList<Attribute> fvWekaAttributes = new ArrayList<Attribute>();
	fvWekaAttributes.add(dateana.getAttribute());
	new Instances("Test", fvWekaAttributes, 1);
	Instance testinstance = new DenseInstance(fvWekaAttributes.size());
	testinstance.setValue(dateana.getAttribute(), (String) dateana.analyze("Who fucked up?"));
	assertTrue(testinstance.stringValue(dateana.getAttribute()).equals("NoDate"));
}
 
源代码21 项目: NLIWOD   文件: EntityTypeTest.java
@Test
public void dateTest1() {
	EntityDate dateana = new EntityDate();
	ArrayList<Attribute> fvWekaAttributes = new ArrayList<Attribute>();
	fvWekaAttributes.add(dateana.getAttribute());
	new Instances("Test", fvWekaAttributes, 1);
	Instance testinstance = new DenseInstance(fvWekaAttributes.size());
	testinstance.setValue(dateana.getAttribute(), (String) dateana.analyze("The olympic games in 1992 were the best."));
	assertTrue(testinstance.stringValue(dateana.getAttribute()).equals("Date"));
}
 
源代码22 项目: tsml   文件: TSBF.java
Instances formatIntervalInstances(Instances data){

        //3 stats for whole subseries, start and end point, 3 stats per interval
        int numFeatures=(3+2+3*numIntervals); 
        //Set up instances size and format. 
        FastVector atts=new FastVector();
        String name;
        for(int j=0;j<numFeatures;j++){
                name = "F"+j;
                atts.addElement(new Attribute(name));
        }
        //Get the class values as a fast vector			
        Attribute target =data.attribute(data.classIndex());
       FastVector vals=new FastVector(target.numValues());
        for(int j=0;j<target.numValues();j++)
                vals.addElement(target.value(j));
        atts.addElement(new Attribute(data.attribute(data.classIndex()).name(),vals));
//create blank instances with the correct class value                
        Instances result = new Instances("SubsequenceIntervals",atts,data.numInstances());
        result.setClassIndex(result.numAttributes()-1);
        for(int i=0;i<data.numInstances();i++){
            double cval=data.instance(i).classValue();
            for(int j=0;j<numSubSeries;j++){
                DenseInstance in=new DenseInstance(result.numAttributes());
                in.setValue(result.numAttributes()-1,cval);
                result.add(in);
            }
        }
        return result;
    }
 
源代码23 项目: tsml   文件: TSBF.java
Instances formatProbabilityInstances(double[][] probs,Instances data){
        int numClasses=data.numClasses();
        int numFeatures=(numClasses-1)*numSubSeries;
        //Set up instances size and format. 
        FastVector atts=new FastVector();
        String name;
        for(int j=0;j<numFeatures;j++){
                name = "ProbFeature"+j;
                atts.addElement(new Attribute(name));
        }
        //Get the class values as a fast vector			
        Attribute target =data.attribute(data.classIndex());
       FastVector vals=new FastVector(target.numValues());
        for(int j=0;j<target.numValues();j++)
                vals.addElement(target.value(j));
        atts.addElement(new Attribute(data.attribute(data.classIndex()).name(),vals));
//create blank instances with the correct class value                
        Instances result = new Instances("SubsequenceIntervals",atts,data.numInstances());
        result.setClassIndex(result.numAttributes()-1);
        for(int i=0;i<data.numInstances();i++){
            double cval=data.instance(i).classValue();
            DenseInstance in=new DenseInstance(result.numAttributes());
            in.setValue(result.numAttributes()-1,cval);
            int pos=0;
            for(int j=0;j<numSubSeries;j++){
                for(int k=0;k<numClasses-1;k++)
                    in.setValue(pos++, probs[j+numSubSeries*i][k]);
            }           
            result.add(in);
        }
        return result;
    }
 
源代码24 项目: tsml   文件: TSBF.java
Instances formatFrequencyBinInstances(int[][][] counts,double[][] classProbs,Instances data){
        int numClasses=data.numClasses();
        int numFeatures=numBins*(numClasses-1)+numClasses;
        //Set up instances size and format. 
        FastVector atts=new FastVector();
        String name;
        for(int j=0;j<numFeatures;j++){
                name = "FreqBinFeature"+j;
                atts.addElement(new Attribute(name));
        }
                
        //Get the class values as a fast vector			
        Attribute target =data.attribute(data.classIndex());
       FastVector vals=new FastVector(target.numValues());
        for(int j=0;j<target.numValues();j++)
                vals.addElement(target.value(j));
        atts.addElement(new Attribute(data.attribute(data.classIndex()).name(),vals));
//create blank instances with the correct class value                
        Instances result = new Instances("HistogramCounts",atts,data.numInstances());
        result.setClassIndex(result.numAttributes()-1);
        for(int i=0;i<data.numInstances();i++){
            double cval=data.instance(i).classValue();
            DenseInstance in=new DenseInstance(result.numAttributes());
            in.setValue(result.numAttributes()-1,cval);
            int pos=0;
//Set values here            
            for(int j=0;j<numClasses-1;j++){
                for(int k=0;k<numBins;k++)
                    in.setValue(pos++,counts[i][j][k]);
            }           
//            
           for(int j=0;j<numClasses;j++)
               in.setValue(pos++,classProbs[i][j]);
             
            result.add(in);
        }
        return result;
    }
 
源代码25 项目: NLIWOD   文件: EntityTypeTest.java
@Test
public void percentTest1() {
	EntityPercent percana = new EntityPercent();
	ArrayList<Attribute> fvWekaAttributes = new ArrayList<Attribute>();
	fvWekaAttributes.add(percana.getAttribute());
	new Instances("Test", fvWekaAttributes, 1);
	Instance testinstance = new DenseInstance(fvWekaAttributes.size());
	testinstance.setValue(percana.getAttribute(), (String) percana.analyze("5% of 100 equal 5."));
	assertTrue(testinstance.stringValue(percana.getAttribute()).equals("Percent"));
}
 
源代码26 项目: tsml   文件: BoTSWEnsemble.java
public double[] distributionForInstanceSVM(Instance instnc) throws Exception {
    BoTSW_Bag testBag = buildTestBag(instnc);

    //classify
    Instances testBagData = new Instances(bagData, 1);
    double[] inst = new double[params.k+1];
    for (int j = 0; j < params.k; ++j)
        inst[j] = testBag.hist[j];
    inst[inst.length-1] = testBag.classValue;
    testBagData.add(new DenseInstance(1, inst));

    return svm.distributionForInstance(testBagData.get(0));
}
 
@Test
public void testClassIndexAtPosZero() throws Exception {
  data = DatasetLoader.loadAnger();

  RnnOutputLayer out = new RnnOutputLayer();
  out.setLossFn(new LossMSE());
  out.setActivationFunction(new ActivationIdentity());
  clf.setLayers(out);

  // Create reversed attribute list
  ArrayList<Attribute> attsReversed = new ArrayList<>();
  for (int i = data.numAttributes() - 1; i >= 0; i--) {
    attsReversed.add(data.attribute(i));
  }

  // Create copy with class at pos 0 and text at pos 1
  Instances copy = new Instances("reversed", attsReversed, data.numInstances());
  data.forEach(
      d -> {
        Instance inst = new DenseInstance(2);
        inst.setDataset(copy);
        inst.setValue(0, d.classValue());
        inst.setValue(1, d.stringValue(0));
        copy.add(inst);
      });

  copy.setClassIndex(0);

  TestUtil.holdout(clf, copy);
}
 
源代码28 项目: AILibs   文件: MekaInstancesUtil.java
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 MekaInstance) {
		return ((MekaInstance) 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!");
	}
	return iNew;
}
 
源代码29 项目: meka   文件: MatrixUtils.java
/**
 * Helper method that transforms a Matrix object to an Instances object.
 *
 * @param mat The Matrix to transform.
 * @param patternInst the Instances template to use
 * @return  The resulting Instances object.
 */
public static Instances matrixToInstances(Matrix mat, Instances patternInst){
	Instances result = new Instances(patternInst);
	for (int i = 0; i < mat.getRowDimension(); i++) {
		double[] row =  mat.getArray()[i];
		DenseInstance denseInst = new DenseInstance(1.0, row);
		result.add(denseInst);
	}

	return result;
}
 
源代码30 项目: NLIWOD   文件: QuestionWordTest.java
@Test
public void questionWordTest() {
	QuestionWord questionWord = new QuestionWord();
	ArrayList<Attribute> fvWekaAttributes = new ArrayList<Attribute>();
	fvWekaAttributes.add(questionWord.getAttribute());
	new Instances("Test", fvWekaAttributes, 1 );
	Instance test = new DenseInstance(fvWekaAttributes.size());
	test.setValue(questionWord.getAttribute(), (String) questionWord.analyze("How high is the lighthouse in Colombo?"));	
	assertTrue(test.stringValue(questionWord.getAttribute()).equals("How"));
	
	test.setValue(questionWord.getAttribute(), (String) questionWord.analyze("List all the musicals with music by Elton John."));	
	assertTrue(test.stringValue(questionWord.getAttribute()).equals(Commands));	
}