Weka is a very useful machine learning library, which is not described in detail here.
To get to the point, to use Weka in a program way, here are the steps:
First, create a new Java project in eclipse:
1. Create the project: Click File->new->java Project in the menu, and any name in project name in the pop-up dialog box is assumed to be wekatest. Click the Finish button (at the bottom of the dialog box).
2. Establish package: In Package Explorer to find just the new project, on its right button->new->package. Enter a name in the Name text box, which is assumed to be test. Click the Finish button.
3. Set up the program file: in the newly-created package above right->new->class, select the public static void main (string[] args) Multiple-selection box, click Finish.
Second, add Weka references to the project:
1. Package Explorer in the project name on the right, select the pop-up menu, the last item properties-> on the left select the Java build path-> the library page on the right-hand side-> click Add External jars...- > Browse to the directory of Weka, add Weka.jar, and click OK.
2. In Package Explorer, double-click the test file and add a four-sentence code below the package wekatest sentence:
import java.io.File;
import weka.classifiers.Classifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import Weka.core.converters.ArffLoader;
Add the Weka call code to the program:
Add the following code to the main function (under//TODO auto-generated method Stub):
Classifier M_classifier = new J48 ();
File Inputfile = new file ("D://program Files//weka-3-6//data//cpu.with.vendor.arff");//Training Corpus
Arffloader ATF = new arffloader ();
Atf.setfile (Inputfile);
Instances Instancestrain = Atf.getdataset (); Read into the training files
Inputfile = new file ("D://program Files//weka-3-6//data//cpu.with.vendor.arff")//Test Corpus
Atf.setfile (Inputfile);
Instances instancestest = Atf.getdataset (); Read into test files
Instancestest.setclassindex (0); Set the line number of the Category property (first act No. 0), instancestest.numattributes () to get the total number of attributes
double sum = instancestest.numinstances (),//number of test corpus instances
right = 0.0f;
Instancestrain.setclassindex (0);
M_classifier.buildclassifier (Instancestrain); Training
for (int i = 0;i<sum;i++)//test classification results
{
if (M_classifier.classifyinstance (Instancestest.instance (i)) ==instancestest.instance (i). ClassValue ())// If the predicted value is equal to the answer value (the category column in the test corpus provides the correct answer, the result makes sense)
{
right++;//correct value plus 1
}
}
SYSTEM.OUT.PRINTLN ("J48 classification precision:" + (right/sum));
Four, run a try.