weka詳解

本篇文章針對weka API的幾個簡單使用介紹,weka官網文檔介紹非常詳細,可參考。

1.?weka官網:https://www.cs.waikato.ac.nz/~ml/weka/

2. weka官方文檔:https://waikato.github.io/weka-wiki/

3. weka API文檔:https://weka.sourceforge.io/doc.stable-3-8/

4. 推薦值得學習的blog:https://www.cnblogs.com/zlslch/category/999872.html

此博客是介紹weka比較系統(tǒng)和詳細的博客冤灾,有些不明白的地方可以查看官網。

備注:weka官方文檔上有相應例子辕近,有些例子對應版本比較舊,可對應更新為自己使用的版本

建議看下官網的有關weka視頻的介紹:https://youtu.be/TF1yh5PKaqI

一匿垄、Java調用Weka API創(chuàng)建Arff文件

Arff(attribute relation file format 關系屬性格式)文件是一種由獨立移宅、無序實例組成的數(shù)據集文件归粉,是一種 ASCII 文本文件。在 Arff 文件中漏峰,%開始表示注釋糠悼;@relation 表示數(shù)據之間的關系;@attribute 表示字段名稱和字段類型浅乔;@data 表示具體的數(shù)據倔喂,同時數(shù)據的順序要和@attribute 中的屬性保持一致靖苇。文件內容中悼枢,最開始的部分顯示文件注釋,之后顯示關系的名字和屬性的具體定義,在屬性下是具體的數(shù)據集合。

1. 總共就這么四步,關鍵代碼:

1)一開始需要實例化一個Vector來保存數(shù)據屬性:

FastVector atts =newFastVector();// 保存屬性

2)同時需要有保存單條數(shù)據

double[]vals;// arff保存單條數(shù)據

3)判斷數(shù)據格式之后新建數(shù)據屬性:

atts.addElement(newAttribute(numName));

4)之后填充數(shù)據:

vals[j] =instances.attribute(j).addStringValue("XXXXX");

2.?完整代碼:

/** * 創(chuàng)建合法格式的Arff文件 * * @param data 該參數(shù)為封裝好的Data參數(shù),數(shù)據類型為 * Map<String, List<Object>> * @return * @throws Exception */

? ? public String createArffFile(Data data, int userID) throws Exception {

? ? ? ? FastVector atts = new FastVector();// 保存屬性

? ? ? ? double[] vals;// arff保存單條數(shù)據

? ? ? ? // 創(chuàng)建List作為數(shù)據類型flag

? ? ? ? List<Object> indexList = new LinkedList<Object>();

? ? ? ? // 獲取data數(shù)據

? ? ? ? wekaData = XMLParser.praseXML(data.getData_Content());

? ? ? ? // 獲取data中的第0行為title,第一行為判斷數(shù)據類型

? ? ? ? List<Object> titleList = wekaData.get("0");

? ? ? ? List<Object> firstList = wekaData.get("1");

? ? ? ? // 遍歷title中的數(shù)據類型,為arff文件創(chuàng)建attribute

? ? ? ? for (int i = 0; i < firstList.size(); i++) {

? ? ? ? ? ? Object obj = firstList.get(i);

? ? ? ? ? ? String objStr = obj.toString();

? ? ? ? ? ? if (isNumeric(objStr)) {

? ? ? ? ? ? ? ? indexList.add("Numeric");

? ? ? ? ? ? ? ? String numName = String.valueOf(titleList.get(i));

? ? ? ? ? ? ? ? atts.addElement(new Attribute(numName));

? ? ? ? ? ? } else if (isValidDate(objStr)) {

? ? ? ? ? ? ? ? indexList.add("Date");

? ? ? ? ? ? ? ? atts.addElement(new Attribute((String) titleList.get(i), "yyyy-MM-dd"));

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? indexList.add("String");

? ? ? ? ? ? ? ? atts.addElement(new Attribute((String) titleList.get(i), (FastVector) null));

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? // 必須放在創(chuàng)建attribute之后 否則會報異常

? ? ? ? Instances instances = new Instances(data.getData_Name(), atts, 0); // 創(chuàng)建一個weka data實例

? ? ? ? System.out.println(indexList);

? ? ? ? // 填充數(shù)據

? ? ? ? for (int i = 1; i < wekaData.size(); i++) {

? ? ? ? ? ? vals = new double[instances.numAttributes()];

? ? ? ? ? ? String index = String.valueOf(i);

? ? ? ? ? ? int length = wekaData.get(index).size();

? ? ? ? ? ? System.out.println(length);

? ? ? ? ? ? // 遍歷填充

? ? ? ? ? ? for (int j = 0; j < length; j++) {

? ? ? ? ? ? ? ? if (indexList.get(j).equals("String")) {

? ? ? ? ? ? ? ? ? ? System.out.println("string");

? ? ? ? ? ? ? ? ? ? vals[j] = instances.attribute(j).addStringValue((String) wekaData.get(index).get(j));

? ? ? ? ? ? ? ? } else if (indexList.get(j).equals("Numeric")) {

? ? ? ? ? ? ? ? ? ? System.out.println("number");

? ? ? ? ? ? ? ? ? ? System.out.println((String) wekaData.get(index).get(j));

? ? ? ? ? ? ? ? ? ? double num = Double.valueOf((String) wekaData.get(index).get(j));

? ? ? ? ? ? ? ? ? ? vals[j] = num;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? instances.add(new Instance(1.0, vals));

? ? ? ? ? ? // end

? ? ? ? }

? ? ? ? System.out.println(instances.toString());

? ? ? ? // IP時間戳工具

? ? ? ? IPTimeStamp ipTimeStamp = new IPTimeStamp();

? ? ? ? // 保存文件加時間戳重命名获印,防止不同文件重名覆蓋

? ? ? ? String fileName = ipTimeStamp.getIPTimeRand() + "_" + userID + "_" + data.getData_Name();

? ? ? ? String path = configProperty.getArffPath() + fileName + ".arff";

? ? ? ? File outFile = new File(path);

? ? ? ? FileUtils.writeStringToFile(outFile, instances.toString(), false);

? ? ? ? System.out.println("ArffPath" + configProperty.getArffPath());

? ? ? ? return path;

? ? }

構建好的格式舉例:K-means聚類樣本.arff

@relation K-means聚類樣本

@attribute X numeric

@attribute Y numeric

@data

0,0

1,0

二鳍征、Weka API使用訓練好的已知模型進行實時預測

1、自己根據屬性構建instance實例。

2、調用之前已經訓練的模型,調用時需要將模型強制轉變?yōu)槟P蜋C器學習類型,如NaiveBayes的模型需要這樣操作。

Classifier m_Classifier =?(NaiveBayes)SerializationHelper.read(new FileInputStream("model/bayes.model"));

以下是本文構建的Weka實時預測功能:

本實例中instance具有四個屬性衷佃,第一個為double屬性惯悠,第二個是double屬性克婶,第三個是Nominal類型,第四個是Class類型(預測值)。

注:本文中使用的模型可以使用Weka圖形界面操作生成鸠补。

代碼思路:

首先萝风,構建一個instances結構,構建instances具有什么樣的屬性紫岩;其次,指定instances的類別索引睬塌,即指定哪個屬性代表的是類別泉蝌。之后,構建instance實例揩晴,將instances的結構框架指定為instance的數(shù)據集勋陪,給instance賦值,此處傳值時不需要傳入Class值硫兰,因為這是我們要預測的诅愚;最后,使用已知模型的classifyInstance方法對instance進行預測劫映,再根據預測出的索引得到預測類別的值违孝。

以下是編寫的Weka實時預測代碼:

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import weka.classifiers.Classifier;

import weka.classifiers.bayes.NaiveBayes;

import weka.core.Attribute;

import weka.core.FastVector;

import weka.core.Instance;

import weka.core.Instances;

import weka.core.SerializationHelper;

public class WekaTestInstance

{

? ? Instances m_Data = null;

? ? Classifier m_Classifier = null;

? ? public WekaTestInstance() throws FileNotFoundException, Exception

? ? {

? ? ? ? m_Classifier = (NaiveBayes)SerializationHelper.read(new FileInputStream("model/bayes.model"));?


? ? ? ? String nameOfDataset = "messDataset";

? ? ? ? FastVector attributes = new FastVector();

? ? ? ? attributes.addElement(new Attribute("aa"));

? ? ? ? attributes.addElement(new Attribute("bb"));


? ? ? ? FastVector fvNominalVal = new FastVector(3);

? ? ? ? fvNominalVal.addElement("blue");

? ? ? ? fvNominalVal.addElement("gray");

? ? ? ? fvNominalVal.addElement("black");? ? ? ? ? ? ?

? ? ? ? attributes.addElement(new Attribute("Nominal", fvNominalVal));


? ? ? ? FastVector classValues = new FastVector(2);

? ? ? ? classValues.addElement("pos");

? ? ? ? classValues.addElement("neg");

? ? ? ? attributes.addElement(new Attribute("Class", classValues));

? ? ? ? m_Data = new Instances(nameOfDataset, attributes, 10);

? ? ? ? m_Data.setClassIndex(m_Data.numAttributes()-1);

? ? }

? ? public void classifyMessage(double aa,double bb,String nominal) throws Exception

? ? {

? ? ? ? Instances testset = m_Data.stringFreeStructure();

? ? ? ? Instance instance = makeInstance(aa,bb,nominal,testset);

? ? ? ? System.out.println(m_Data.numAttributes());

? ? ? ? System.out.println(instance);

? ? ? ? double predicted = m_Classifier.classifyInstance(instance);

? ? ? ? System.out.println("predicted:"+predicted);

? ? ? ? System.out.println("Message classified as : " +

? ? ? ? ? ? ? ? m_Data.classAttribute().value((int)predicted));

? ? }

? ? private Instance makeInstance(double aa,double bb,String nominal,Instances data)

? ? {

? ? ? ? Instance instance = new Instance(4);

? ? ? ? instance.setDataset(data);

? ? ? ? Attribute aaAtt = data.attribute("aa");

? ? ? ? Attribute bbAtt = data.attribute("bb");

? ? ? ? Attribute nominalAtt = data.attribute("Nominal");


? ? ? ? instance.setValue(aaAtt, aa);

? ? ? ? instance.setValue(bbAtt, bb);

? ? ? ? instance.setValue(nominalAtt, nominal);


//? ? ? instance.setValue((Attribute)instance.attribute(0), aa);

//? ? ? instance.setValue((Attribute)instance.attribute(1), bb);

//? ? ? instance.setValue((Attribute)instance.attribute(2),nominal);? ? ? ?

? ? ? ? return instance;

? ? }

? ? public static void main(String[] args) throws Exception

? ? {

? ? ? ? WekaTestInstance wTestInstance = new WekaTestInstance();

? ? ? ? wTestInstance.classifyMessage(5.6,9.9,"gray");

? ? }

}

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市泳赋,隨后出現(xiàn)的幾起案子雌桑,更是在濱河造成了極大的恐慌,老刑警劉巖祖今,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件校坑,死亡現(xiàn)場離奇詭異,居然都是意外死亡千诬,警方通過查閱死者的電腦和手機耍目,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來徐绑,“玉大人邪驮,你說我怎么就攤上這事”萌” “怎么了耕捞?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長烫幕。 經常有香客問我俺抽,道長,這世上最難降的妖魔是什么较曼? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任磷斧,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘弛饭。我一直安慰自己冕末,他們只是感情好,可當我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布侣颂。 她就那樣靜靜地躺著档桃,像睡著了一般。 火紅的嫁衣襯著肌膚如雪憔晒。 梳的紋絲不亂的頭發(fā)上藻肄,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天,我揣著相機與錄音拒担,去河邊找鬼嘹屯。 笑死,一個胖子當著我的面吹牛从撼,可吹牛的內容都是我干的州弟。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼低零,長吁一口氣:“原來是場噩夢啊……” “哼婆翔!你這毒婦竟也來了?” 一聲冷哼從身側響起毁兆,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤浙滤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后气堕,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纺腊,經...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年茎芭,在試婚紗的時候發(fā)現(xiàn)自己被綠了揖膜。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡梅桩,死狀恐怖壹粟,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情宿百,我是刑警寧澤趁仙,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站垦页,受9級特大地震影響雀费,放射性物質發(fā)生泄漏。R本人自食惡果不足惜痊焊,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一盏袄、第九天 我趴在偏房一處隱蔽的房頂上張望忿峻。 院中可真熱鬧,春花似錦辕羽、人聲如沸逛尚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽绰寞。三九已至,卻和暖如春酌毡,著一層夾襖步出監(jiān)牢的瞬間克握,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工枷踏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人掰曾。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓旭蠕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親旷坦。 傳聞我的和親對象是個殘疾皇子掏熬,可洞房花燭夜當晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內容