[WEKA] WEKA Clustering

File csv = new File("C:\\Users\\pmk\\Desktop\\Book1.csv");


import java.io.BufferedReader;

import java.io.FileReader;


import weka.classifiers.Classifier;

import weka.classifiers.bayes.net.search.fixed.NaiveBayes;

import weka.core.Instances;


public class MyNB {

void NaiveBayes_ArffArff() throws Exception {

// 모델 빌드에 사용할 학습 데이터 로드

BufferedReader reader;

reader = new BufferedReader(new FileReader("C://"));

Instances train = new Instances(reader);

reader.close();


// 각 개체의 레이블을 설정

train.setClassIndex(train.numAttributes()-1);

// 모델 빌드

Classifier cModel = (Classifier)new NaiveBayes();

cModel.buildClassifier(train);

// 테스트용 데이터 로드

reader = new BufferedReader(new FileReader("c://")));

Instances test = new Instances(reader);

reader.close();

// 개체의 레이블 설정

int point = test.numAttributes() - 1;

test.setClassIndex(point);

// 개체 분류 테스트

double pred = cModel.classifyInstance(test.instance(0));

System.out.println("Classify " + pred);

}


}



Use Weka in your java code


자주 사용하는 요소

Instances - 데이터 객체

Filter - 데이터 전처리과정을 위한 필터

Classifier/Cluster - 전처리된 데이터를 분류/클러스터링

Evaluating - 분류/클러스터링이 얼마나 잘 되었는지 평가

Attribute selection - 데이터집합에서 필요없는 속성들을 제거하는 속성선택


ARFF File

 파일 쉽게 하는 법

 -> 엑셀



 import weka.core.Instances;

 import java.io.BufferedReader;

 import java.io.FileReader;

 ...

 BufferedReader reader = new BufferedReader(

                              new FileReader("/some/where/data.arff"));

 Instances data = new Instances(reader);

 reader.close();


 // Class 속성을 설정

 data.setClassIndex(data.numAttributes() - 1);


기본적으로 ARFF 파일에서는 마지막의 속성이 타겟(클래스) 속성이기 때문에 numAttributes - 1로 둔다.

(인덱스는 0부터 시작하나보다)

인스턴스 객체(data)를 만들어야 weka 함수의 파라미터로 넘길 수 있다니 꼭 Instances 클래스를 사용하여 객체로 만들어두자


DataSource 클래스 - ARFF, CSV (Weka에서는 컨버터 패키지를 통해서 모든 파일 포맷을 import할 수 있다!)


생성자


 import weka.core.converters.ConverterUtils.DataSource;

 ...

 DataSource source = new DataSource("/some/where/data.arff");

 Instances data = source.getDataSet();

 // 데이터 포맷이 이정보를 제공하지 않으면 클래스 속성 설정

 // 예를 들어, XRFF 포맷은 클래스 속성 정보를 저장한다.

 if (data.classIndex() == -1)

   data.setClassIndex(data.numAttributes() - 1);



데이터베이스도 쉽게 사용할 수 있다.

먼저 DatabaseUtils.props 파일이 데이터베이스와 connection할 수 있도록 수정한다. 

파일 내용

 jdbcDriver=org.gjt.mm.mysql.Driver

 jdbcURL=jdbc:mysql://localhost:3306/some_database


그러고나서 자바 코드에서 DB에서 데이터를 로드할 수 있게 한다.


 import weka.core.Instances;

 import weka.experiment.InstanceQuery;

 ...

 InstanceQuery query = new InstanceQuery();

 query.setUsername("nobody");

 query.setPassword("");

 query.setQuery("select * from whatsoever");

 // 데이터집합이 sparse하다면 선언

 // query.setSparseData(true);

 Instances data = query.retrieveInstances();


- JDBC 드라이버를 위해 Classpath 추가해줄 것

그러나 지금은 DB를 연동하지 않을 것이므로 pass!



Option handling

분류, 클러스터, 필터와 같은 scheme에서 옵션 설정을 바꾸기 위해 아래와 같은 메소드를 제공한다.


void setOption(String[] options)

String[] getOptions()


>>>

String[] options = new String[2];

options[0] = "-R";

options[1] = "1";


혹은 한줄로 나타낼 수 있다.

String[] options = weka.core.Utils.splitOptions("-R 1");


OptionsToCode.java 자동으로 명령라인을 코드로 변환하기 위해 사용한다. 특히 명령라인이 옵션을 가진 네스팅 클래스들을 포함하고 있을 때 유용하다.


OptionTree.java는 네스팅 옵션스트링을 한 눈에 볼 수 있게 한다. 네스팅으로 인한 에러를 잡는 데 도움이 될 것이다.


필터

필터는 감독형/비감독형, attribute-/instance-based 두가지 유형이 있다.


대부분 필터는 OptionHandler 인터페이스를 구현하고 그말인즉슨 set메소드를 통해 설정하기 보다는 String 배열을 통해 옵션을 설정할 수 있다는 말이다.

예를 들어, 첫번째 옵션을 지우고 싶다하면, 

weka.filters.unsupervised.attribute.Remove

를 옵션 -R 1과 함께 사용하면 된다. 



 import weka.core.Instances;

 import weka.filters.Filter;

 import weka.filters.unsupervised.attribute.Remove;

 ...

 String[] options = new String[2];

 options[0] = "-R";                                    // 범위

 options[1] = "1";                                     // 첫번째 속성

 Remove remove = new Remove();                         // new 필터 인스턴스 

 remove.setOptions(options);                           // 앞에서 준 옵션 설정

 remove.setInputFormat(data);                          // data에 filter설정

 Instances newData = Filter.useFilter(data, remove);   // 필터 적용


이때 remove.setOptions(options)를 한 후에 remove.setInputFormat(data)를 해야한다!!!!



클러스터링

클러스터링은 분류와 비슷하다

> weka.clusterers


building a cluster


Batch


import weka.clusterers.EM;

 ...

 String[] options = new String[2];

 options[0] = "-I";                 // max. iterations

 options[1] = "100"; // 최대 100번 반복

 EM clusterer = new EM();   // new 클러스터 인스턴스

 clusterer.setOptions(options);     // 옵션 설정

 clusterer.buildClusterer(data);    // bulid the clusterer


weka.clusterers.UpdateableClusterer 인터페이스는 점진적으로 train시킬 수 있다. 한꺼번에 동시에 메모리에 올릴 필요가 없으므로 메모리를 낭비하지 않는다.

- 데이터집합 스트럭쳐와 함께 buildClusterer(Instances) 호출

- 결과적으로, 차례대로 updateClusterer(Instance)메소드 호출

- 모든 인스턴스 오브젝트가 추가 연산을 수행하기 위한 클러스터를 수행한 후에 updateFinish()를 호출한다.



반응형
그리드형

댓글

❤️김세인트가 사랑으로 키웁니다❤️