weka and java eclipse example : A Simple Machine Learning Example in Java

A Simple Machine Learning Example in Java

This is a "Hello World" example of machine learning in Java. It simply give you a taste of machine learning in Java.

Environment

 

Java 1.6+ and Eclipse

Step 1: Download Weka libraryDownload page: http://www.cs.waikato.ac.nz/ml/weka/snapshots/weka_snapshots.html

Download stable.XX.zip, unzip the file, add weka.jar to your library path of Java project in Eclipse.

Step 2: Prepare Data

Create a txt file "weather.txt" by following the following format:

@relation weather

@attribute outlook {sunny, overcast, rainy}
@attribute temperature numeric
@attribute humidity numeric
@attribute windy {TRUE, FALSE}
@attribute play {yes, no}

@data
sunny,85,85,FALSE,no
sunny,80,90,TRUE,no
overcast,83,86,FALSE,yes
rainy,70,96,FALSE,yes
rainy,68,80,FALSE,yes
rainy,65,70,TRUE,no
overcast,64,65,TRUE,yes
sunny,72,95,FALSE,no
sunny,69,70,FALSE,yes
rainy,75,80,FALSE,yes
sunny,75,70,TRUE,yes
overcast,72,90,TRUE,yes
overcast,81,75,FALSE,yes
rainy,71,91,TRUE,no

This dataset is from weka download package. It is located at "/data/weather.numeric.arff". The file extension name is "arff", but we can simply use "txt".

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Step 3: Training and Testing by Using Weka

This code example use a set of classifiers provided by Weka. It trains model on the given dataset and test by using 10-split cross validation. I will explain each classifier later as it is a more complicated topic.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.rules.DecisionTable;
import weka.classifiers.rules.PART;
import weka.classifiers.trees.DecisionStump;
import weka.classifiers.trees.J48;
import weka.core.FastVector;
import weka.core.Instances;
 
public class WekaTest {
	public static BufferedReader readDataFile(String filename) {
		BufferedReader inputReader = null;
 
		try {
			inputReader = new BufferedReader(new FileReader(filename));
		} catch (FileNotFoundException ex) {
			System.err.println("File not found: " + filename);
		}
 
		return inputReader;
	}
 
	public static Evaluation classify(Classifier model,
			Instances trainingSet, Instances testingSet) throws Exception {
		Evaluation evaluation = new Evaluation(trainingSet);
 
		model.buildClassifier(trainingSet);
		evaluation.evaluateModel(model, testingSet);
 
		return evaluation;
	}
 
	public static double calculateAccuracy(FastVector predictions) {
		double correct = 0;
 
		for (int i = 0; i < predictions.size(); i++) {
			NominalPrediction np = (NominalPrediction) predictions.elementAt(i);
			if (np.predicted() == np.actual()) {
				correct++;
			}
		}
 
		return 100 * correct / predictions.size();
	}
 
	public static Instances[][] crossValidationSplit(Instances data, int numberOfFolds) {
		Instances[][] split = new Instances[2][numberOfFolds];
 
		for (int i = 0; i < numberOfFolds; i++) {
			split[0][i] = data.trainCV(numberOfFolds, i);
			split[1][i] = data.testCV(numberOfFolds, i);
		}
 
		return split;
	}
 
	public static void main(String[] args) throws Exception {
		BufferedReader datafile = readDataFile("weather.txt");
 
		Instances data = new Instances(datafile);
		data.setClassIndex(data.numAttributes() - 1);
 
		// Do 10-split cross validation
		Instances[][] split = crossValidationSplit(data, 10);
 
		// Separate split into training and testing arrays
		Instances[] trainingSplits = split[0];
		Instances[] testingSplits = split[1];
 
		// Use a set of classifiers
		Classifier[] models = { 
				new J48(), // a decision tree
				new PART(), 
				new DecisionTable(),//decision table majority classifier
				new DecisionStump() //one-level decision tree
		};
 
		// Run for each model
		for (int j = 0; j < models.length; j++) {
 
			// Collect every group of predictions for current model in a FastVector
			FastVector predictions = new FastVector();
 
			// For each training-testing split pair, train and test the classifier
			for (int i = 0; i < trainingSplits.length; i++) {
				Evaluation validation = classify(models[j], trainingSplits[i], testingSplits[i]);
 
				predictions.appendElements(validation.predictions());
 
				// Uncomment to see the summary for each training-testing pair.
				//System.out.println(models[j].toString());
			}
 
			// Calculate overall accuracy of current classifier on all splits
			double accuracy = calculateAccuracy(predictions);
 
			// Print current classifier's name and accuracy in a complicated,
			// but nice-looking way.
			System.out.println("Accuracy of " + models[j].getClass().getSimpleName() + ": "
					+ String.format("%.2f%%", accuracy)
					+ "\n---------------------------------");
		}
 
	}
}

The package view of your project should look like the following:

java-machine-learning-example

References:
1. http://www.cs.umb.edu/~ding/history/480_697_spring_2013/homework/WekaJavaAPITutorial.pdf
2. http://www.cs.ru.nl/P.Lucas/teaching/DM/weka.pdf

[출처] https://www.programcreek.com/2013/01/a-simple-machine-learning-example-in-java/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
62 [maven 설정] Jackson Databind » 2.6.7.1 졸리운_곰 2020.10.05 187
61 [maven 설정] MongoDB Java Driver » 3.12.6 졸리운_곰 2020.10.05 175
60 Maven 에 직접 jar 라이브러리 추가하기!!! ( 외부 repository 사용이 안될때) + scope 정리 졸리운_곰 2020.10.05 169
59 추상(abstract) 클래스가 필요한 기본적인 이유 졸리운_곰 2019.10.30 247
58 Java and JMX - Building Manageable Systems secret 졸리운_곰 2019.05.26 0
57 [GC] 강제로 GC시키기Java 메모리 full 발생시 강제로 GC 시키기 졸리운_곰 2019.01.22 377
56 Java Map 반복(Iteration)시키는 3가지 방법 졸리운_곰 2019.01.01 347
55 UML: 클래스 다이어그램과 소스코드 매핑 file 졸리운_곰 2018.04.30 381
54 lombok에 대해서 알아보자 file 졸리운_곰 2018.04.24 292
53 lombok을 잘 써보자! (2) 졸리운_곰 2018.04.24 318
52 lombok을 잘 써보자! (1) 졸리운_곰 2018.04.24 366
51 [Java] Quartz (쿼츠)를 사용하여 자바 스케줄링(scheduling) 하기 졸리운_곰 2018.02.12 509
50 [subclipse] svn에서 무시할 파일 설정하기 svn:ignore property 설정 file 졸리운_곰 2017.09.24 286
49 자바에서 C# 호출하기 file 졸리운_곰 2017.04.26 475
48 Comparison between C# and Java - DiVA.pdf file 졸리운_곰 2017.04.25 1017
47 Java Annotation: 인터페이스 강요로부터 자유를… file 졸리운_곰 2017.03.20 302
46 Java Naming conventions 자바 명명 규칙 졸리운_곰 2017.03.04 272
45 Timer 클래스를 이용한 작업 스케쥴링 졸리운_곰 2016.11.14 290
44 자바 8 살펴보기 file 졸리운_곰 2016.05.23 432
43 Java 8 개선 사항 관련 글 모음 졸리운_곰 2016.05.23 409
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED