KNN算法--投票猜党派
KNN分类方法可以理解为投票法。把训练数据集当做选民,K值当做这些选民所拥有的选票。现在从这些这些选民中推选出来的K位投票人,推选的标准 是和候选党派(假设这个党派名称对选民是保密的,实际中可以理解为测试数据)的政策主张(数据特征)相近程度。而这些投票人自己本身又有自己所属的党派,他们当然把选票投给自己的党派。得票最多的党派获胜,这时候我们就有较大的把握认为得票多的党派就是候选人的党派名称。
一个手势识别的KNN应用实例
/**
* @param trainingData2
* @param vec2
* @return the distance of two vectors
*/
public double EulerDistance(Double[] trainingData2,double[] vec2){
double tdis = 0.0;
double ans = 0.0;
double dis = 0.0;
for(int i = 0;i<vecLen;i++){
dis = (trainingData2[i] - vec2[i]);
tdis += dis * dis;
}
ans = Math.sqrt(tdis);
return ans;
}
/**
* the Entrance method of this class,from one to six marks the name
* of all the gestures,and this method returns the name of gesture
* that most matching.
* Using KNN algorithm
* @return name of gesture
*/
class Node implements Comparable<Node>{
public double dis;
public int gid;
public Node(int _gid,double _dis) {
this.gid = _gid;
this.dis = _dis;
}
@Override
public int compareTo(Node o) {
if(this.dis > o.dis) return 1;
else if(this.dis < o.dis) return -1;
else return 0;
}
}
public int GestureResult(double[] inData,int k){
ArrayList<Node> nodes = new ArrayList<>();
int[] vote = {0,0,0,0,0,0};
for(int i = 0;i<6;i++){
for(int j = 0;j<60;j++){
nodes.add(new Node(i,EulerDistance(trainingData[i][j], inData)));
}
}
Collections.sort(nodes);
for(int i = 0;i<k;i++){
vote[nodes.get(i).gid]++;
}
int ans_index = 0;
int most = -1;
for(int i = 0;i<6;i++){
if(vote[i] > most){
ans_index = i;
most = vote[i];
}
}
return GestrueName[ans_index];
}
网友评论