d(x,y)闵式距离
模型参数的分类
优缺点
代码
# 人工智能数据源下载地址:https://video.mugglecode.com/data_ai.zip,下载压缩包后解压即可(数据源与上节课相同)
# -*- coding: utf-8 -*-
"""
任务:鸢尾花识别
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import ai_utils
DATA_FILE = './data_ai/Iris.csv'
SPECIES_LABEL_DICT = {
'Iris-setosa': 0, # 山鸢尾
'Iris-versicolor': 1, # 变色鸢尾
'Iris-virginica': 2 # 维吉尼亚鸢尾
}
# 使用的特征列
FEAT_COLS = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']
def investigate_knn(iris_data, sel_cols, k_val):
"""
不同的K值对模型的影响
"""
X = iris_data[sel_cols].values
y = iris_data['Label'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=10)
knn_model = KNeighborsClassifier(n_neighbors=k_val) #特殊指定k值
knn_model.fit(X_train, y_train)
accuracy = knn_model.score(X_test, y_test)
print('k={},accuracy={:.2f}%'.format(k_val, accuracy * 100))
#绘图的样式、:ai_utils.plot_knn_boundary(模型、x,y,图题目,保存路径)
ai_utils.plot_knn_boundary(knn_model, X_test, y_test,
'Sepal Length vs Sepal Width, k={}'.format(k_val),
save_fig='sepal_k={}.png'.format(k_val))
def main():
"""
主函数
"""
# 读取数据集
iris_data = pd.read_csv(DATA_FILE, index_col='Id')
iris_data['Label'] = iris_data['Species'].map(SPECIES_LABEL_DICT)
k_vals = [3, 5, 10]
sel_cols = ['SepalLengthCm', 'SepalWidthCm']
for k_val in k_vals:
investigate_knn(iris_data, sel_cols, k_val)
if __name__ == '__main__':
main()
运行结果
k=3,accuracy=66.00%
k=5,accuracy=68.00%
k=10,accuracy=78.00%
k=3
k=5
k=7
练习:kNN算法的超参数对水果识别器的影响
题目描述:使用不同的k值,观察对水果识别器的影响。
题目要求:
使用scikit-learn的kNN进行识别
使用k=1, 3, 5, 7观察对结果的影响
数据文件:
数据源下载地址:https://video.mugglecode.com/fruit_data.csv(数据源与上节课相同)
fruit_data.csv,包含了60个水果的的数据样本。
共5列数据
fruit_name:水果类别
mass: 水果质量
width: 水果的宽度
height: 水果的高度
color_score: 水果的颜色数值,范围0-1。
0.85 - 1.00:红色
0.75 - 0.85: 橙色
0.65 - 0.75: 黄色
-
0.45 - 0.65: 绿色
image
参考代码
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
#特征文字
feat_cols =['mass','width','height','color_score']
#读取数据
data = pd.read_csv('/Users/miraco/PycharmProjects/ai/data_ai/fruit_data.csv')
#预处理
fruit2num = {'apple' : 0 ,
'mandarin' : 2 ,
'orange' : 3 ,
'lemon' : 1
}
data['label'] = data['fruit_name'].map(fruit2num)
#取出X和y
X = data[feat_cols].values
y = data['label'].values
#划分数据
X_train_set, X_test_set ,y_train_set, y_test_set = train_test_split(X,y, random_state = 20, test_size= 1/3)
print('原始数据集共{}个样本,其中训练集样本数为{},测试集样本数为{}'.format(
X.shape[0], X_train_set.shape[0], X_test_set.shape[0]))
#训练
def investigate_k(k_val):
knn_model = KNeighborsClassifier(n_neighbors=k_val)
knn_model.fit(X_train_set, y_train_set)
#准确率检测
accur = knn_model.score(X_test_set,y_test_set)
print(f'当k={k_val}时,预测的正确率为{accur*100}%')
#
# #试试看
#
# num2fruit = dict(zip(fruit2num.values(),fruit2num.keys()))
#
# for idx in range(X_test_set.shape[0]):
# test_feat = [X_test_set[idx]]
# y_pridict = num2fruit.get(int(knn_model.predict(test_feat)))
# y_real = num2fruit.get(y_test_set[idx])
# YorN = '对' if y_pridict == y_real else '错'
# print(f'第{idx+1}个测试水果的结果是{y_pridict},本来应该是{y_real},所以测{YorN}了')
for k in [1,3,5,7]:
investigate_k(k)
运行结果:
原始数据集共59个样本,其中训练集样本数为39,测试集样本数为20
当k=1时,预测的正确率为70.0%
当k=3时,预测的正确率为85.0%
当k=5时,预测的正确率为85.0%
当k=7时,预测的正确率为75.0%