代码:
# -*- coding: utf-8 -*-
"""
Created on Sat May 11 10:23:50 2024@author: admin
"""
# 调用库
import numpy as np
import matplotlib.pyplot as plt
# 调用人工智能模型库
from sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn import metrics
# 定义函数
X1, y1 = [], []
#输入数据
fr = open('F:/bigdata/knn.txt', mode='r', encoding='gbk')
for line in fr.readlines():lineArr = line.strip().split()X1.append([int(lineArr[0]),int(lineArr[1])])y1.append(int(lineArr[2]))
# 输出数据
X = np.array(X1)
y = np.array(y1)X_train,X_text,Y_train,Y_test =train_test_split(X,y,test_size=0.16)knn=KNeighborsClassifier(3)
knn.fit(X,y)plt.scatter(X_train[Y_train==1,0], X_train[Y_train==1,1], color='red', marker='o')
plt.scatter(X_train[Y_train==2,0], X_train[Y_train==2,1], color='green', marker='x')
plt.scatter(X_train[Y_train==3,0], X_train[Y_train==3,1], color='blue', marker='d')y_pred=knn.predict(X_text)print(knn.score(X_text, Y_test))
print(metrics.accuracy_score(y_true=Y_test,y_pred=y_pred))print(metrics.confusion_matrix(y_true=Y_test,y_pred=y_pred))from sklearn.metrics import classification_report
target_names=['label_1','label_2','label_3']
print(classification_report(Y_test, y_pred))
label = knn.predict([[7,27],[2,4]])
print(label)
结果如下:
knn.txt:
2 4 1
4 3 2
10 6 3
12 9 2
3 11 3
20 7 2
22 5 2
21 10 1
11 2 3
24 1 1