如何将新实例添加到我创建的现有Instances对象中?
以下是一个例子:
ArrayList<Attribute> atts = new ArrayList<Attribute>(2);
ArrayList<String> classVal = new ArrayList<String>();
classVal.add("A");
classVal.add("B");
atts.add(new Attribute("content",(ArrayList<String>)null));
atts.add(new Attribute("@@class@@",classVal));
Instances dataRaw = new Instances("TestInstances",atts,0);
我想为dataRaw添加一个新实例。据我所知,我必须使用dataRaw.add(Instance i)....如果Instance类是一个接口,我如何创建一个实例对象?
先谢谢
答案 0 :(得分:16)
让我们从一些亮点开始。
instanceValue1 [0] = dataRaw.attribute(0).addStringValue(“这是一个字符串!”);
dataRaw.add(new DenseInstance(1.0,instanceValue1));
以下是完整的运行示例:
import java.util.ArrayList;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
public class Program {
public static void main(String[] args) {
ArrayList<Attribute> atts = new ArrayList<Attribute>(2);
ArrayList<String> classVal = new ArrayList<String>();
classVal.add("A");
classVal.add("B");
atts.add(new Attribute("content",(ArrayList<String>)null));
atts.add(new Attribute("@@class@@",classVal));
Instances dataRaw = new Instances("TestInstances",atts,0);
System.out.println("Before adding any instance");
System.out.println("--------------------------");
System.out.println(dataRaw);
System.out.println("--------------------------");
double[] instanceValue1 = new double[dataRaw.numAttributes()];
instanceValue1[0] = dataRaw.attribute(0).addStringValue("This is a string!");
instanceValue1[1] = 0;
dataRaw.add(new DenseInstance(1.0, instanceValue1));
System.out.println("After adding a instance");
System.out.println("--------------------------");
System.out.println(dataRaw);
System.out.println("--------------------------");
double[] instanceValue2 = new double[dataRaw.numAttributes()];
instanceValue2[0] = dataRaw.attribute(0).addStringValue("This is second string!");
instanceValue2[1] = 1;
dataRaw.add(new DenseInstance(1.0, instanceValue2));
System.out.println("After adding second instance");
System.out.println("--------------------------");
System.out.println(dataRaw);
System.out.println("--------------------------");
}
}
其输出如下:
Before adding any instance
--------------------------
@relation TestInstances
@attribute content string
@attribute @@class@@ {A,B}
@data
--------------------------
After adding a instance
--------------------------
@relation TestInstances
@attribute content string
@attribute @@class@@ {A,B}
@data
'This is a string!',A
--------------------------
After adding second instance
--------------------------
@relation TestInstances
@attribute content string
@attribute @@class@@ {A,B}
@data
'This is a string!',A
'This is second string!',B
--------------------------