📜  如何使用 Weka Java API?

📅  最后修改于: 2022-05-13 01:55:47.310000             🧑  作者: Mango

如何使用 Weka Java API?

要使用 weka API,您需要根据您的操作系统安装 weka。下载存档并解压缩后,您将找到 weka.jar 文件。 JAR 文件包含所需的所有类文件,即 weka API。现在我们可以在 Weka Java API 文档中找到关于类和方法的所有信息。我们需要将此 jar 作为类路径添加到我们的程序中。

另外,让我们在进入实现部分之前讨论类路径。所以类路径是告诉 JDK 关于外部库(用户类文件)的东西。为了添加类路径,推荐的方法是使用 JDK 命令的-cp选项。如果您使用任何框架,则可以将类路径添加到相应的清单文件中。

例子:

Java
// Java Program to Illustrate Usage of Weka API
 
// Importing required classes
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.J48;
import weka.core.Instances;
 
// Main class
// BreastCancer
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Try block to check for exceptions
        try {
 
            // Create J48 classifier by
            // creating object of J48 class
            J48 j48Classifier = new J48();
 
            // Dataset path
            String breastCancerDataset
                = "/home/droid/Tools/weka-3-8-5/data/breast-cancer.arff";
 
            // Creating bufferedreader to read the dataset
            BufferedReader bufferedReader
                = new BufferedReader(
                    new FileReader(breastCancerDataset));
 
            // Create dataset instances
            Instances datasetInstances
                = new Instances(bufferedReader);
 
            // Set Target Class
            datasetInstances.setClassIndex(
                datasetInstances.numAttributes() - 1);
 
            // Evaluating by creating object of Evaluation
            // class
            Evaluation evaluation
                = new Evaluation(datasetInstances);
 
            // Cross Validate Model with 10 folds
            evaluation.crossValidateModel(
                j48Classifier, datasetInstances, 10,
                new Random(1));
 
            System.out.println(evaluation.toSummaryString(
                "\nResults", false));
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
 
            // Print message on the console
            System.out.println("Error Occurred!!!! \n"
                               + e.getMessage());
        }
    }
}


输出:



这将是生成的所需输出,如下所示: