在這一節我們看看屬性選擇。在資料挖掘的研究中,通常要通過距離來計算樣本之間的距離,而樣本距離是通過屬性值來計算的。我們知道對于不同的屬性,它們在樣本空間的權重是不一樣的,即它們與類别的關聯度是不同的,是以有必要篩選一些屬性或者對各個屬性賦一定的權重。這樣屬性選擇的方法就應運而生了。
在屬性選擇方面InfoGain和GainRatio的比較常見,也是最通俗易懂的方法。它們與Decision Tree的構造原理比較相似,哪個節點擁有的資訊量就為哪個節點賦較高的權重。其它的還有根據關聯度的辦法來進行屬性選擇(Correlation-based Feature Subset Selection for Machine Learning)。具體它的工作原理大家可以在網上看論文。
現在我将簡單的屬性選擇執行個體給大家展示一下:
package com.csdn;
import java.io.File;
import weka.attributeSelection.InfoGainAttributeEval;
import weka.attributeSelection.Ranker;
import weka.classifiers.Classifier;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
public class SimpleAttributeSelection {
public static void main(String[] args) {
// TODO Auto-generated method stub
Instances trainIns = null;
try{
File file= new File("C:\\Program Files\\Weka-3-6\\data\\segment-challenge.arff");
ArffLoader loader = new ArffLoader();
loader.setFile(file);
trainIns = loader.getDataSet();
//在使用樣本之前一定要首先設定instances的classIndex,否則在使用instances對象是會抛出異常
trainIns.setClassIndex(trainIns.numAttributes()-1);
Ranker rank = new Ranker();
InfoGainAttributeEval eval = new InfoGainAttributeEval();
eval.buildEvaluator(trainIns);
//System.out.println(rank.search(eval, trainIns));
int[] attrIndex = rank.search(eval, trainIns);
StringBuffer attrIndexInfo = new StringBuffer();
StringBuffer attrInfoGainInfo = new StringBuffer();
attrIndexInfo.append("Selected attributes:");
attrInfoGainInfo.append("Ranked attributes:\n");
for(int i = 0; i < attrIndex.length; i ++){
attrIndexInfo.append(attrIndex[i]);
attrIndexInfo.append(",");
attrInfoGainInfo.append(eval.evaluateAttribute(attrIndex[i]));
attrInfoGainInfo.append("\t");
attrInfoGainInfo.append((trainIns.attribute(attrIndex[i]).name()));
attrInfoGainInfo.append("\n");
}
System.out.println(attrIndexInfo.toString());
System.out.println(attrInfoGainInfo.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
在這個執行個體中,我用了InfoGain的屬性選擇類來進行特征選擇。InfoGainAttributeEval主要是計算出各個屬性的InfoGain資訊。同時在weka中為屬性選擇方法配備的有搜尋算法(seacher method),在這裡我們用最簡單的Ranker類。它對屬性進行了簡單的排序。在Weka中我們還可以對搜尋算法設定一些其它的屬性,例如設定搜尋的屬性集,門檻值等等,如果有需求大家可以進行詳細的設定。
在最後我們列印了一些結果資訊,列印了各個屬性的InfoGain的資訊。
本文來自CSDN部落格,轉載請标明出處:http://blog.csdn.net/anqiang1984/archive/2009/04/04/4048177.aspx