K-NN算法的核心在于距离的求解
注意事项:
1. K值的选取
当K值较小时,容易受到个别值的影响
当K值较大时,容易受到样本均衡性的影响,主要取奇数作为K值
2. 只能用在比较小的数据量,大概在1000~10000之间
代码如下:
# 1. 数据集的获取
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
data = load_iris()
x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.3, random_state=60)
# 2. 特征工程(特征标准化)
from sklearn.preprocessing import StandardScaler
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# 3. 评估器实例化
from sklearn.neighbors import KNeighborsClassifier
estimator = KNeighborsClassifier(n_neighbors=3)
estimator.fit(x_train, y_train)
# 4. 模型评估
# 方法1:预测值和评估值之间的直接比较
print('预测值和实际值的比较\n',estimator.predict(x_test) == y_test)
# 方法2:打分score
estimator.score(x_test, y_test)
# 这里我们可以看一下K的取值对score的影响
accuray_list = []
for i in range(1, 20):
estimator = KNeighborsClassifier(n_neighbors=i)
estimator.fit(x_train, y_train)
accuracy = estimator.score(x_test, y_test)
accuray_list.append(accuracy)
accuray_list
import matplotlib.pyplot as plt
plt.bar([str(i) for i in range(1, 20)],accuray_list)
plt.ylim(0.8, 1)
plt.show()
结果如下:
预测值和实际值的比较 [ True True True True True True True True True False True True True True True True True True True True True True False True True True True True False True True True True True True True True True True True True True False True True]0.9111111111111111[0.8666666666666667, 0.8888888888888888, 0.9111111111111111, 0.9111111111111111, 0.9555555555555556, 0.9111111111111111, 0.9111111111111111, 0.9333333333333333, 0.9333333333333333, 0.9333333333333333, 0.9111111111111111, 0.9111111111111111, 0.9111111111111111, 0.9333333333333333, 0.9111111111111111, 0.9111111111111111, 0.9111111111111111, 0.9111111111111111, 0.8888888888888888]
我们可以发现,当K取5时可以得到一个比较好的结果
学习地址: