这篇文章能够帮助你从数据到模型的整个过程实现 不过至于安装第三方库等基础问题,本文不涉及,因为确实不难,搜一搜一大把 本此实验运行环境为jupyter,当然通过pycharm也是可行的 手写数字共5000组数组 其中一共有0-9,10组数据,每一组中有500张对应的手写数字的图片 数据资料: 拿到数据后把数据解压到和代码同一级的目录当中 这部分重点是把图片数据转换为可以输入模型的二维数组型数据 用到的函数解答: plt.imshow()函数是matplotlib库中的一个函数,它用于显示图像。这个函数接受一个二维或三维的数组作为输入,表示图像的数据。然后,它将数组的值映射到颜色空间,以显示图像。在plt.imshow()函数中,cmap是一个参数,代表色彩映射(colormap)。在图像处理中,我们通常将图像表示为一个二维数组,数组的每个元素代表图像的一个像素。每个像素的值通常是一个介于0和255之间的整数,表示该像素的灰度级别。然而,我们通常不能直接看到这些数字,因为它们在视觉上可能没有明显的差别。相反,我们通常将每个像素的值映射到一个连续的色彩空间,这样我们就可以在屏幕上显示图像了。有许多不同的colormap可以选择,比如:‘gray’:灰度colormap、‘hot’:红色到白色的热图colormap、‘cool’:蓝色到绿色的colormap、‘Jet’:从蓝色到红色的colormap、‘hsv’:HSV色彩空间的colormap。  代码 
img =  plt. imread( './手写数字识别/0/0_1.bmp' ) 
display( img. shape)  
plt. imshow( img, cmap= 'gray' ) 
data =  [ ]  
target =  [ ]  for  i in  range ( 10 ) : for  j in  range ( 1 , 501 ) : img =  plt. imread( f'./手写数字识别/ { i} / { i} _ { j} .bmp' ) data. append( img) target. append( i) 
data =  np. array( data) . reshape( 5000 ,  - 1 ) 
target =  np. array( target) . reshape( 5000 ,  - 1 ) 
print ( 'data的形状:' , data. shape, 'target的形状:' , target. shape) 
from  sklearn. model_selection import  train_test_splitx_train,  x_test,  y_train,  y_test =  train_test_split( data, target, test_size= 0.2 )  
from  sklearn. neighbors import  KNeighborsClassifierknn =  KNeighborsClassifier( ) 
knn. fit( x_train, y_train) 
knn. score( x_test, y_test) 
choice =  np. random. randint( 1 , 1000 , 10 ) . tolist( ) 
plt. figure( figsize= ( 5 * 10 , 2 * 10 ) ) for  i in  range ( 10 ) : re =  plt. subplot( 2 , 5 , i+ 1 ) re. imshow( x_test[ choice[ i] ] . reshape( 28 , - 1 ) , cmap= 'gray' ) re. set_title( f'real: { y_test[ choice[ i] ] [ 0 ] } ,\npredict: { y_pred[ choice[ i] ] } ' , fontsize= 40 , color =  'k'  if  y_test[ choice[ i] ] [ 0 ]  ==  y_pred[ choice[ i] ]  else  'r' ) 
 
如果在划分了数据集之后,要显示test当中的一个图片,应该先把图片数据变回原来的维度,然后再显示 关于如何改变数组维度的问题