KNN
简介
KNN的全称是K Nearest Neighbors。K个最近邻居,K的取值肯定是至关重要的。 KNN的原理就是当预测一个新的值x的时候,根据它距离最近的K个点是什么类别来判断x属于哪个类别。
举个例子:
如果K=3,绿色圆将被分类为红色三角形。
如果K=5,绿色圆被分类为蓝色四方形类。
距离计算方程:
特点
KNN是一种非参的,惰性的算法模型。
非参 :这个模型不会对数据做出任何的假设,也就是说KNN建立的模型结构是根据数据来决定的。
惰性:不需要对数据进行大量训练就可以得到一个算法模型,它没有明确的训练数据的过程,或者说这个过程很快。
K值选择
一般采用交叉验证(将样本数据按照一定比例,拆分出训练用的数据和验证用的数据,比如6:4拆分出部分训练数据和验证数据),从选取一个较小的K值开始,不断增加K的值,然后计算验证集合的方差,最终找到一个比较合适的K值。
实验
要求
csv格式的数据是这样的,还有一个一模一样的txt类型数据。
实现
伪代码
1 读取数据
2 选择获得K的方式
2.1 手动输入
2.2 计算出比较好的
3. KNN算法
3.1计算测试数据与各个训练数据之间的距离;
3.2按照距离的递增关系进行排序;
3.3选取距离最小的K个点;
3.4确定前K个点所在类别的出现频率;
3.5返回前K个点中出现频率最高的类别作为测试数据的预测分类。
Java代码
package AIProjectSix;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
class Flower {
private Double calysLength; //花萼
private Double calysWidth;
private Double petalLength; //花瓣
private Double petalWidth; //1代表Setosa,2代表Versicolour,3代表Virginica
private int type;
@Override
public String toString() {
return "Flower [calyxLength=" + calysLength + ", calysWidth=" + calysWidth + ", petalLength=" + petalLength
+ ", petalWidth=" + petalWidth + ", type=" + type + "]";
}
public Flower(Double calyxLength, Double calysWidth, Double petalLength, Double petalWidth, int type) {
super();
this.calysLength = calyxLength;
this.calysWidth = calysWidth;
this.petalLength = petalLength;
this.petalWidth = petalWidth;
this.type = type;
}
public Double getCalyxLength() {
return calysLength;
}
public void setCalyxLength(Double calyxLength) {
this.calysLength = calyxLength;
}
public Double getCalysWidth() {
return calysWidth;
}
public void setCalysWidth(Double calysWidth)