本文整理汇总了Java中weka.core.Instance类的典型用法代码示例。如果您正苦于以下问题:Java Instance类的具体用法?Java Instance怎么用?Java Instance使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Instance类属于weka.core包,在下文中一共展示了Instance类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import weka.core.Instance; //导入依赖的package包/类
public static void main(String[] args) {
try {
BookDecisionTree decisionTree = new BookDecisionTree("books.arff");
J48 tree = decisionTree.performTraining();
System.out.println(tree.toString());
Instance testInstance = decisionTree.
getTestInstance("Leather", "yes", "historical");
int result = (int) tree.classifyInstance(testInstance);
String results = decisionTree.trainingData.attribute(3).value(result);
System.out.println(
"Test with: " + testInstance + " Result: " + results);
testInstance = decisionTree.
getTestInstance("Paperback", "no", "historical");
result = (int) tree.classifyInstance(testInstance);
results = decisionTree.trainingData.attribute(3).value(result);
System.out.println(
"Test with: " + testInstance + " Result: " + results);
} catch (Exception ex) {
ex.printStackTrace();
}
}
开发者ID:PacktPublishing,项目名称:Machine-Learning-End-to-Endguide-for-Java-developers,代码行数:24,代码来源:BookDecisionTree.java
示例2: instancesToDMatrix
import weka.core.Instance; //导入依赖的package包/类
public static DMatrix instancesToDMatrix(Instances instances) throws XGBoostError {
long[] rowHeaders = new long[instances.size()+1];
rowHeaders[0]=0;
List<Float> dataList = new ArrayList<>();
List<Integer> colList = new ArrayList<>();
float[] labels = new float[instances.size()];
for(int i=0; i<instances.size(); i++) {
Instance instance = instances.get(i);
rowHeaders[i] = dataList.size();
processInstance(instance, dataList, colList);
labels[i] = (float) instance.classValue();
}
rowHeaders[rowHeaders.length - 1] = dataList.size();
int colNum = instances.numAttributes()-1;
DMatrix dMatrix = createDMatrix(rowHeaders, dataList, colList, colNum);
dMatrix.setLabel(labels);
return dMatrix;
}
示例3: instanceToDenseDMatrix
import weka.core.Instance; //导入依赖的package包/类
public static DMatrix instanceToDenseDMatrix(Instance instance) throws XGBoostError {
Attribute classAttribute = instance.classAttribute();
int classAttrIndex = classAttribute.index();
int colNum = instance.numAttributes()-1;
int rowNum = 1;
float[] data = new float[colNum*rowNum];
Enumeration<Attribute> attributeEnumeration = instance.enumerateAttributes();
int dataIndex = 0;
while (attributeEnumeration.hasMoreElements()) {
Attribute attribute = attributeEnumeration.nextElement();
int attrIndex = attribute.index();
if(attrIndex == classAttrIndex){
continue;
}
data[dataIndex]= (float) instance.value(attribute);
dataIndex++;
}
return new DMatrix(data, rowNum, colNum);
}
示例4: predictExamples
import weka.core.Instance; //导入依赖的package包/类
@TimeThis(task="prediction")
protected void predictExamples(ProcessingContext<Corpus> ctx, Classifier classifier, IdentifiedInstances<Element> devSet, Corpus corpus) throws Exception {
ElementClassifierResolvedObjects resObj = getResolvedObjects();
RelationDefinition relationDefinition = resObj.getRelationDefinition();
Evaluator examples = resObj.getExamples();
String predictedClassFeatureKey = getPredictedClassFeatureKey();
TargetStream evaluationFile = getEvaluationFile();
boolean withId = evaluationFile != null;
String[] classes = getClasses(devSet);
getLogger(ctx).info("predicting class for each example");
EvaluationContext evalCtx = new EvaluationContext(getLogger(ctx));
for (Element example : Iterators.loop(getExamples(corpus, examples, evalCtx))) {
Instance inst = relationDefinition.addExample(devSet, evalCtx, example, withId, withId);
double prediction = classifier.classifyInstance(inst);
example.addFeature(predictedClassFeatureKey, classes[(int) prediction]);
if (!withId)
devSet.delete();
}
}
示例5: fetchNext
import weka.core.Instance; //导入依赖的package包/类
@Override
protected Tuple fetchNext() throws DbException, TransactionAbortedException {
// Block, adding all of the child tuples to the buffer.
while (child.hasNext()){
buffer.add(child.next());
}
// Do the impute, if we have not already.
if (imputedInstances == null){
doImpute();
}
// We've imputed values, so we can actually return them now.
if (nextTupleIndex < buffer.size()){
Tuple original = buffer.get(nextTupleIndex);
Instance inst = imputedInstances.get(nextTupleIndex);
Tuple imputed = new Tuple(original);
mergeInstanceIntoTuple(inst, imputed);
nextTupleIndex++;
return imputed;
} else {
return null;
}
}
示例6: Main
import weka.core.Instance; //导入依赖的package包/类
public Main() {
try {
BufferedReader datafile;
datafile = readDataFile("camping.txt");
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
Instances trainingData = new Instances(data, 0, 14);
Instances testingData = new Instances(data, 14, 5);
Evaluation evaluation = new Evaluation(trainingData);
SMO smo = new SMO();
smo.buildClassifier(data);
evaluation.evaluateModel(smo, testingData);
System.out.println(evaluation.toSummaryString());
// Test instance
Instance instance = new DenseInstance(3);
instance.setValue(data.attribute("age"), 78);
instance.setValue(data.attribute("income"), 125700);
instance.setValue(data.attribute("camps"), 1);
instance.setDataset(data);
System.out.println("The instance: " + instance);
System.out.println(smo.classifyInstance(instance));
} catch (Exception ex) {
ex.printStackTrace();
}
}
开发者ID:PacktPublishing,项目名称:Machine-Learning-End-to-Endguide-for-Java-developers,代码行数:30,代码来源:Main-SVG.java
示例7: isClassTheMajortiy
import weka.core.Instance; //导入依赖的package包/类
private boolean isClassTheMajortiy(ArrayList<Instance> instances, double classification){
List<Instance> instancesList = new ArrayList<>(instances);
TreeMap<Double, Double> classificationProbability = new TreeMap<>();
Attribute classAttribute = instances.get(0).classAttribute();
for (double i = 0; i < classAttribute.numValues(); i++) {
int matchedClassCount = 0;
for (Instance instance : instancesList) {
if(instance.classValue() == i){
matchedClassCount++;
}
}
classificationProbability.put(((double) matchedClassCount / (double) instancesList.size()), i);
}
return (classificationProbability.lastEntry().getValue() == classification);
}
示例8: createInstance
import weka.core.Instance; //导入依赖的package包/类
public Instance createInstance(List<String> featureNames, I key) {
double[] vals = new double[featureNames.size()];
for (int i = 0; i < featureNames.size(); i++) {
Feature<Object> f = this.featureValues.get(key).get(featureNames.get(i));
if (f != null)
vals[i] = f.getDoubleValue();
else {
Class<Object> type = features.get(featureNames.get(i));
if (type.equals(Double.class) || type.equals(Float.class) || type.equals(Integer.class))
vals[i] = Double.NaN;
if (type.equals(Boolean.class) || type.equals(String.class))
vals[i] = 0;
}
}
return new DenseInstance(1.0, vals);
}
示例9: testTransactionLookup
import weka.core.Instance; //导入依赖的package包/类
/**
* testTransactionLookup
*/
@Test
public void testTransactionLookup() throws Exception {
int txn_id_idx = FeatureExtractor.TXNID_ATTRIBUTE_IDX;
assertEquals(workload.getTransactionCount(), data.numInstances());
List<TransactionTrace> txns = new ArrayList<TransactionTrace>(workload.getTransactions());
// System.err.println(StringUtil.join("\n", txns));
// System.err.println();
for (int i = 0, cnt = data.numInstances(); i < cnt; i++) {
Instance inst = data.instance(i);
assertNotNull(inst);
String value = inst.stringValue(txn_id_idx);
// System.err.println("VALUE: " + value);
Long txn_id = Long.valueOf(value);
assertNotNull(txn_id);
TransactionTrace txn_trace = workload.getTransaction(txn_id);
TransactionTrace expected = txns.get(i);
// System.err.println("EXPECTED: " + expected.getTransactionId());
// System.err.println("FOUND: " + txn_id);
assertNotNull(String.format("[%05d] Failed to txn #%d", i, txn_id), txn_trace);
assertEquals(expected.getTransactionId(), txn_trace.getTransactionId());
} // FOR
}
示例10: testCreateMarkovAttributeSetFilter
import weka.core.Instance; //导入依赖的package包/类
/**
* testCreateMarkovAttributeSetFilter
*/
@Test
public void testCreateMarkovAttributeSetFilter() throws Exception {
// Test that we can create a filter from an MarkovAttributeSet
MarkovAttributeSet aset = new MarkovAttributeSet(data, FeatureUtil.getFeatureKeyPrefix(ParamArrayLengthFeature.class));
assertEquals(CatalogUtil.getArrayProcParameters(catalog_proc).size(), aset.size());
Filter filter = aset.createFilter(data);
Instances newData = Filter.useFilter(data, filter);
for (int i = 0, cnt = newData.numInstances(); i < cnt; i++) {
Instance processed = newData.instance(i);
// System.err.println(processed);
assertEquals(aset.size(), processed.numAttributes());
} // WHILE
assertEquals(data.numInstances(), newData.numInstances());
// System.err.println("MarkovAttributeSet: " + aset);
}
示例11: instanceToTuple
import weka.core.Instance; //导入依赖的package包/类
/**
* Create a new Tuple by extracting the values from the Instance inst and using the TupleDesc td
* @param inst Instance
* @param td TupleDesc
* @return new Tuple
*/
public static Tuple instanceToTuple(Instance inst, TupleDesc td){
Tuple t = new Tuple(td);
for (int i=0; i<td.numFields(); i++){
double value = inst.value(i);
Type type = td.getFieldType(i);
Field field = null;
if (type.equals(Type.INT_TYPE)){
field = new IntField((int) value);
} else if (type.equals(Type.DOUBLE_TYPE)){
field = new DoubleField(value);
} else if (type.equals(Type.STRING_TYPE)){
throw new UnsupportedOperationException();
// field = new StringField(value);
}
t.setField(i, field);
}
return t;
}
示例12: classifySentence
import weka.core.Instance; //导入依赖的package包/类
public SentenceType classifySentence(Sentence sentence) {
SpeechActsClassifier.Features features = speechActsClassifier.classifyFeatures(sentence);
Instance inst = new DenseInstance(6);
inst.setDataset(dataSet);
inst.setValue(0, features.getSentenceLength());
inst.setValue(1, features.getNumberOfNouns());
inst.setValue(2, (features.isEndingInNounOrAdjective() ? 1 : 0));
inst.setValue(3, (features.isBeginningInVerb() ? 1 : 0));
inst.setValue(4, features.getCountOfWhMarkers());
inst.setValue(5, Utils.missingValue());
try {
return SentenceType.valueOf(classifier.classifyInstance(inst));
} catch (Exception e) {
throw new RuntimeException("Can't classify");
}
}
示例13: classifyQuestion
import weka.core.Instance; //导入依赖的package包/类
public QuestionType classifyQuestion(Sentence sentence) {
if (!sentence.isQuestion()) {
return QuestionType.NA;
}
QuestionTypeClassifier.Features features = questionTypeClassifier.classifyFeatures(sentence);
Instance inst = new DenseInstance(5);
inst.setDataset(dataSet);
inst.setValue(0, features.getWhWord());
inst.setValue(1, features.getWhWordPos());
inst.setValue(2, features.getPosOfNext());
inst.setValue(3, features.getRootPos());
inst.setValue(4, Utils.missingValue());
try {
int ndx = (int) classifier.classifyInstance(inst);
return QuestionType.valueOf(ndx);
} catch (Exception e) {
throw new RuntimeException("Not classified");
}
}
示例14: getTopNegativeWekaFeaturesInReport
import weka.core.Instance; //导入依赖的package包/类
protected List<FeatureWeight> getTopNegativeWekaFeaturesInReport(
Instance reportInstance, HashMap<String, Integer> featureIndexMap,
String[][] featureWeightTable, int topKwords) throws Exception {
List<FeatureWeight> topNegativeFeatureList = new ArrayList<>();
int iFeature = 0;
double weight;
FeatureWeight featureWeight;
while(topNegativeFeatureList.size() < topKwords &&
iFeature < featureIndexMap.size()) {
weight = Double.parseDouble(featureWeightTable[iFeature][1]);
if(weight < 0 &&
reportInstance.value(featureIndexMap.get(featureWeightTable[iFeature][0]) + 1) == 1) { // reportID is the first att in reportInstance
featureWeight = new FeatureWeight();
featureWeight.setTerm(featureWeightTable[iFeature][0]);
featureWeight.setWeight(weight);
topNegativeFeatureList.add(featureWeight);
}
iFeature++;
}
return topNegativeFeatureList;
}
示例15: getTopPositiveWekaFeaturesInReport
import weka.core.Instance; //导入依赖的package包/类
protected List<FeatureWeight> getTopPositiveWekaFeaturesInReport(Instance reportInstance,
HashMap<String, Integer> featureIndexMap, String[][] featureWeightTable, int topKwords) throws Exception {
List<FeatureWeight> topPositiveFeatureList = new ArrayList<>();
int iFeature = 0;
double weight;
FeatureWeight featureWeight;
while(topPositiveFeatureList.size() < topKwords &&
iFeature < featureIndexMap.size()) {
weight = Double.parseDouble(featureWeightTable[iFeature][1]);
if(weight > 0 &&
reportInstance.value(featureIndexMap.get(featureWeightTable[iFeature][0]) + 1) == 1) { // reportID is the first att in reportInstance
featureWeight = new FeatureWeight();
featureWeight.setTerm(featureWeightTable[iFeature][0]);
featureWeight.setWeight(weight);
topPositiveFeatureList.add(featureWeight);
}
iFeature++;
}
return topPositiveFeatureList;
}