本文整理汇总了Java中weka.classifiers.functions.LibSVM类的典型用法代码示例。如果您正苦于以下问题:Java LibSVM类的具体用法?Java LibSVM怎么用?Java LibSVM使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LibSVM类属于weka.classifiers.functions包,在下文中一共展示了LibSVM类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: predictDataDistribution
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
protected double[][] predictDataDistribution(Instances unlabeled) throws Exception {
// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);
// distribution for instance
double[][] dist = new double[unlabeled.numInstances()][unlabeled.numClasses()];
// label instances
for (int i = 0; i < unlabeled.numInstances(); i++) {
// System.out.println("debug: "+this.getClass().getName()+": classifier: "+m_Classifier.toString());
LibSVM libsvm = (LibSVM) m_Classifier;
libsvm.setProbabilityEstimates(true);
double[] instanceDist = libsvm.distributionForInstance(unlabeled.instance(i));
dist[i] = instanceDist;
}
return dist;
}
示例2: afterPropertiesSet
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
/**
* Loads the training data as configured in {@link #dataConfig} and trains a
* 3-gram SVM classifier.
*/
@Override
public void afterPropertiesSet() throws Exception {
this.trainingData = svmTrainer.train();
StringToWordVector stwvFilter = createFilter(this.trainingData);
// Instances filterdInstances = Filter.useFilter(data, stwv);
LibSVM svm = new LibSVM();
svm.setKernelType(new SelectedTag(0, LibSVM.TAGS_KERNELTYPE));
svm.setSVMType(new SelectedTag(0, LibSVM.TAGS_SVMTYPE));
svm.setProbabilityEstimates(true);
// svm.buildClassifier(filterdInstances);
FilteredClassifier filteredClassifier = new FilteredClassifier();
filteredClassifier.setFilter(stwvFilter);
filteredClassifier.setClassifier(svm);
filteredClassifier.buildClassifier(this.trainingData);
this.classifier = filteredClassifier;
// predict("nice cool amazing awesome beautiful");
// predict("this movie is simply awesome");
// predict("its very bad");
// predict("Not that great");
}
示例3: generateAndWriteFullModel
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
/**
* Generate the model with all data and write it with the appropriate filters.
*
* @param instances as returned from {@link WekaUtils#createInstances(String)}
* @throws Exception
*/
private void generateAndWriteFullModel(Instances instances) throws Exception {
StringToWordVector stringToWordVector = getStringToWordVectorFilter(instances);
Instances stringsReplacedData = Filter.useFilter(instances, stringToWordVector);
Instances resampled = dumbResample(stringsReplacedData);
Remove removeFilter = getRemoveFilter(stringsReplacedData);
LibSVM svmForOut = new LibSVM();
svmForOut.setCost(config.getSvmCost().get(0));
svmForOut.setGamma(config.getSvmGamma().get(0));
FilteredClassifier filteredClassifierForOut = new FilteredClassifier();
filteredClassifierForOut.setClassifier(svmForOut);
filteredClassifierForOut.setFilter(removeFilter);
filteredClassifierForOut.buildClassifier(resampled);
weka.core.SerializationHelper.write(config.getOutputDir() + "/svm_model_c_" + config.getSvmCost().get(0) + "_gamma_" + config.getSvmGamma().get(0) + ".model", filteredClassifierForOut);
weka.core.SerializationHelper.write(config.getOutputDir() + "/string_filter_c_" + config.getSvmCost().get(0) + "_gamma_" + config.getSvmGamma().get(0) + ".model", stringToWordVector);
}
示例4: train
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
/**
* This function only train the model with the trainSet as it is.
* In other words, no feature removal will done here.
*
* @param trainSet
* @throws Exception
*/
public void train(Instances trainSet) throws Exception {
trainSet.setClassIndex(trainSet.numAttributes() - 1);
// set classifier: use linear SVM only
String[] options = weka.core.Utils.splitOptions("-K 0");
String classifierName = "weka.classifiers.functions.LibSVM";
this.m_Classifier = Classifier.forName(classifierName, options);
// get probability instead of explicit prediction
LibSVM libsvm = (LibSVM) this.m_Classifier;
libsvm.setProbabilityEstimates(true);
// build model
this.m_Classifier.buildClassifier(trainSet);
}
示例5: getFeatureWeight
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
/**
* Get feature weights. Each weight corresponds to a feature name with the
* same index
*
* @return a double array
*/
public double[] getFeatureWeight(int nFeatures) {
LibSVM libsvm = (LibSVM) m_Classifier;
double[] weights = null;
try {
weights = libsvm.getFeatureWeights(nFeatures);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
return weights;
}
示例6: getLabelList
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
public String[] getLabelList() {
LibSVM libsvm = (LibSVM) m_Classifier;
int[] intLabelList = libsvm.getLabelList();
String[] labelList = new String[intLabelList.length];
for(int i = 0; i < labelList.length; i++) {
labelList[i] = Integer.toString(intLabelList[i]);
}
return labelList;
}
示例7: trainModel
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
protected void trainModel(Instances trainData) throws Exception {
// set class attribute
trainData.setClassIndex(trainData.numAttributes() - 1);
// set classifier: use linear SVM only
String[] options = weka.core.Utils.splitOptions("-K 0");
String classifierName = "weka.classifiers.functions.LibSVM";
this.m_Classifier = Classifier.forName(classifierName, options);
// get probability instead of explicit prediction
LibSVM libsvm = (LibSVM) this.m_Classifier;
libsvm.setProbabilityEstimates(true);
// build model
this.m_Classifier.buildClassifier(trainData);
}
示例8: trainLibSvm
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
public static void trainLibSvm(final Instances trainingSet) throws Exception {
// Create a classifier
final LibSVM tree = new LibSVM();
tree.buildClassifier(trainingSet);
// Test the model
final Evaluation eval = new Evaluation(trainingSet);
eval.crossValidateModel(tree, trainingSet, 10, new Random(1));
//eval.evaluateModel(tree, trainingSet);
// Print the result à la Weka explorer:
logger.info(eval.toSummaryString());
}
示例9: main
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: WekaSpeechActClassifier <train_set_input_file> <test_set_input_file>");
System.exit(0);
}
String arffFileTrain = args[0];
String arffFileTest = args[1];
LibSVM wekaClassifier = new LibSVM();
wekaClassifier.setOptions(new String[] {"-B", "-H"});
Instances preparedData = (Instances) SerializationHelper.read(arffFileTrain);
Instances preparedTest = (Instances) SerializationHelper.read(arffFileTest);
System.out.println("Reading train set and test set done!");
System.out.print("\nTraining...");
wekaClassifier.buildClassifier(preparedData);
System.out.println("\nTraining...done!");
Evaluation evalTrain = new Evaluation(preparedData);
evalTrain.evaluateModel(wekaClassifier, preparedData);
DecimalFormat formatter = new DecimalFormat("#0.0");
System.out.println("\nEvaluating on trainSet...");
System.out.println(evalTrain.toSummaryString());
System.out.println("\nResult on trainSet...");
System.out.println("Precision:" + formatter.format(100*evalTrain.precision(0)) + "%" +
" - Recal: " + formatter.format(100*evalTrain.recall(0)) + "%" +
" - F1: " + formatter.format(evalTrain.fMeasure(0)) + "%");
Evaluation eval = new Evaluation(preparedTest);
eval.evaluateModel(wekaClassifier, preparedTest);
System.out.println("\nEvaluating on testSet...");
System.out.println(eval.toSummaryString());
System.out.println("\nResult on testSet...");
System.out.println("Precision:" + formatter.format(100*eval.precision(0)) + "%" +
" - Recal: " + formatter.format(100*eval.recall(0)) + "%" +
" - F1: " + formatter.format(100*eval.fMeasure(0)) + "%");
System.out.println("True positive rate: " + formatter.format(100*eval.truePositiveRate(0)) + "%" +
" - True negative rate: " + formatter.format(100*eval.trueNegativeRate(0)) + "%");
System.out.println("Accuracy: " + formatter.format(100*((eval.truePositiveRate(0) + eval.trueNegativeRate(0)) / 2)) + "%");
System.out.println("\nDone!");
}
示例10: setupLearner
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
/**
* Setup the classifier parameters'.
*/
private void setupLearner() {
logger.info("Applying default configuration to {}", this.classifier.getClass().getSimpleName());
if (this.classifier instanceof J48) {
J48 j48 = (J48) this.classifier;
j48.setCollapseTree(false);
j48.setBinarySplits(false);
j48.setUnpruned(false);
j48.setReducedErrorPruning(false);
j48.setConfidenceFactor(0.25f);
j48.setUseLaplace(true);
j48.setNumFolds(5);
j48.setSubtreeRaising(false);
} else if (this.classifier instanceof LibSVM) {
LibSVM libSVM = (LibSVM) this.classifier;
libSVM.setCacheSize(512); // MB
libSVM.setNormalize(true);
libSVM.setShrinking(true);
libSVM.setKernelType(new SelectedTag(LibSVM.KERNELTYPE_POLYNOMIAL, LibSVM.TAGS_KERNELTYPE));
libSVM.setDegree(3);
libSVM.setSVMType(new SelectedTag(LibSVM.SVMTYPE_C_SVC, LibSVM.TAGS_SVMTYPE));
} else if (this.classifier instanceof NaiveBayes) {
NaiveBayes naiveBayes = (NaiveBayes) this.classifier;
// Configure NaiveBayes
naiveBayes.setUseKernelEstimator(false);
naiveBayes.setUseSupervisedDiscretization(false);
} else if (this.classifier instanceof RandomForest) {
RandomForest rndForest = (RandomForest) this.classifier;
// Configure RandomForest
rndForest.setNumExecutionSlots(5);
rndForest.setNumTrees(50);
rndForest.setMaxDepth(3);
} else if (this.classifier instanceof MultilayerPerceptron) {
MultilayerPerceptron perceptron = (MultilayerPerceptron) this.classifier;
// Configure perceptron
perceptron.setAutoBuild(true);
perceptron.setTrainingTime(250); // epochs
perceptron.setNominalToBinaryFilter(false);
perceptron.setNormalizeAttributes(true);
}
}
示例11: main
import weka.classifiers.functions.LibSVM; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException {
int cores = Runtime.getRuntime().availableProcessors()-1;
cores = 4;
ThreadPoolExecutor es = (ThreadPoolExecutor) Executors.newFixedThreadPool(cores);
String[] datasets = {
"datasets/segment.arff",
"datasets/hypothyroid.arff",
"datasets/spambase.arff",
"datasets/ecoli.arff",
};
List<Instances> instancess = new ArrayList<Instances>();
for (String dataset: datasets){
instancess.add(new Instances(new BufferedReader(new FileReader(dataset))));
}
//Another way of selecting a single dataset
//String dataset = datasets[(int) (Math.random()*datasets.length)];
for (int i : new int[]{1,2,3,4,5})
for(Instances instances : instancess){
Experiment exp = new Experiment(
"Test1",
instances.relationName(),
instances,
new LibSVM(),
es);
//exp.run();
es.execute(exp);
}
//wait forever
es.shutdown();
es.awaitTermination(9999, TimeUnit.DAYS);
System.out.println("#######Finished######");
}