转自 Koala++'s blog
寻找K个邻居,这里先给出一个例子,大部分是王义写的,进行了一点点改动:
publicstatic Instances getKNeighbour( Instances sourceIns, Instance target,
int kNN,int numLabels)
{
Instances neighbours = null;
try{
EuclideanDistance dfunc = new EuclideanDistance();
int predictors = sourceIns.numAttributes() - numLabels;
dfunc.setAttributeIndices("first-" + predictors);
LinearNNSearch lnn = new LinearNNSearch();
lnn.setDistanceFunction(dfunc);
lnn.setInstances( sourceIns );
lnn.addInstanceInfo(target);
neighbours = lnn.kNearestNeighbours(target, kNN);
}catch(Exception e){
System.out.println("Util.getKNeighbour(LinearNNSearch m_NNSearch,
Instance mean, int m_kNN) is wrong!");
}
return neighbours;
}
参数分别是sourceIns表示你在哪个数据集中找邻居,target就是找邻居的样本,kNN是指多少邻居。最后一个参数是我自己在多标签中用的。如果你不需要对特征进行选择,只是想除去类别,那么用下面的代码就可以了:
sourceIns.setClassIndex( sourceIns.numAttributes() -1 );
lnn.setInstances( sourceIns);
EuclideanDistance表示是我用的是欧几里德距离,下面的predictors表示最后一个index,也就是说算距离我只算0-predictors这么多特征,如果你不明白为什么要这样,因为你不懂多标签。下面是设置你考虑哪些特征,这里的”first-“+predictors就表示只考虑0-predictors。LinearNNSearcher是寻找邻居的类,用setDistanceFunction进行距离计算设置,再对数据源和样本信息设置用setInstances和addInstanceInfo,最后设置目标样本和找多少邻居。
这里的setAttributeIndices对我很重要,所以我看了一下:
publicvoid setAttributeIndices(String value) {
m_AttributeIndices.setRanges(value);
invalidate();
}
m_AttributeIndices是一个Range对象。下面是一个Range的例子:
publicstatic Instances getInstances( String filename )
{
try{
FileReader frData = new FileReader( filename );
Instances trainData =new Instances(frData);
return trainData;
}catch( FileNotFoundException e )
{
e.printStackTrace();
}
catch( IOException e )
{
e.printStackTrace();
}
returnnull;
}
publicstaticvoid outputRange( Instances ins )
{
Range range = new Range();
range.setRanges("first-2, 4, 10, last");
range.setUpper(ins.numAttributes() - 1);
boolean[] activeIndices =newboolean[ins.numAttributes()];
for (int i = 0; i < activeIndices.length; i++)
{
activeIndices[i] = range.isInRange(i);
System.out.print( activeIndices[i] +" " );
}
}
publicstaticvoid main(String[] args)throws Exception
{
Instances ins = getInstances("D:/DOWNLOAD/data/soybean.arff" );
outputRange( ins );
}
设置Range我用的是”first-2,4,10,last”,first表示第0个下标,last表示最后一个下标,整个的意思就是选择从第0个到第2个,和第4个,第10个,最后一个特征。setUpper表示最大下标是多少,注意setUpper函数:
publicvoid setUpper(int newUpper) {
if (newUpper >= 0) {
m_Upper = newUpper;
setFlags();
}
}
这里setFlags函数是得到哪一些特征被选中,最后在我的例子中,我用isRange来判断是否第i个特征被选中了。
其它的函数特别简单,也没什么好讲的。