是在循环0-9的数字一直循环500次所得到的数据,然后以手写照片的形式存在
import numpy as np
import matplotlib.pyplot as plt
# 记载数据
data = np.load('./digit.npy')
data
# 构建基础的目标值
y = list(np.arange(0,10))*500
# 对生成的目标值进行排序,与图片的目标值进行对应
y.sort()
# 为了在拆分数据的时候可以正常拆分
y = np.array(y)
X = data.reshape(5000,-1)
X.shape # 784:是图片的像素值 ,也就是图像的特征
from sklearn.model_selection import train_test_split
X_tarin,X_test,y_train,y_test = train_test_split(X,y,# x,y的数据
test_size=0.05 # 验证集的占总数据的比重
,random_state=1024 # 随机数的种子)
display(X_tarin.shape,X_test.shape,y_train.shape,y_test.shape)
from sklearn.neighbors import KNeighborsClassifier
# 创建模型
model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_tarin,y_train)
# 数据分数
model.score(X_test,y_test)
%%time
from sklearn.model_selection import GridSearchCV
prams = dict(n_neighbors = [5,7,9,12,15,17,21,23,30],
weights=['uniform','distance'],
p=[1,2])
estimator = KNeighborsClassifier()
gCV = GridSearchCV(estimator,prams,cv=5,scoring='accuracy')
gCV.fit(X_tarin,y_train)
%%time:获取当前程序的运行时间
gCV.best_params_
gCV.best_score_
gCV.best_estimator_
best_model = gCV.best_estimator_
y_predict = gCV.predict(X_test)
print('测试值:',y_predict)
print('真实值:',y_test)
best_model.score(X_test,y_test)
plt.figure(figsize=(5*2,10*3))
for i in range(50):
plt.subplot(10,5,i+1)
plt.imshow(X_test[i].reshape(28,28))
true = y_test[i]
predict = y_predict[i]
plt.title(f'true:{true}\n'+f'predict:{predict}')