10,knn手寫數字識別

2022-05-01 15:00:12 字數 1898 閱讀 3490

# 導包

import numpy as np

import matplotlib.pyplot as plt

from sklearn.neighbors import kneighborsclassifier

# 獲取資料

feature =

target =

for i in range(10):

for j in range(1,501):

img_arr = plt.imread('f:/data/%d/%d_%d.bmp'%(i,i,j))

feature = np.array(feature)

target = np.array(target)

print(feature.shape,target.shape)

# 測試結果

index = np.random.randint(0,5000,size=1)[0]

print('該索引對應的目標值',target[index])

digit = feature[index]

plt.figure(figsize=(2,2))

plt.imshow(digit,cmap='gray')

# 打亂資料順序

np.random.seed(3) #按照同一標準打亂

np.random.shuffle(feature)

np.random.seed(3)

np.random.shuffle(target)

# 分別獲取訓練,測試資料

x_train = feature[:4950]

y_train = target[:4950]

x_test = feature[-50:]

y_test = target[-50:]

x_train.shape #(4950, 28, 28)

# 特徵資料必須保證是二維

x_train = x_train.reshape(4950,784)

#畫素點一共784個,倒著數為-1

x_test = x_test.reshape(50,-1)

# 建立knn物件

knn = kneighborsclassifier(n_neighbors=15)

knn.fit(x_train,y_train)

knn.score(x_train,y_train)

# 比對結果

y_ = knn.predict(x_test)

print('真實:',y_test)

print('**:',y_)

#模型儲存

from sklearn.externals import joblib

joblib.dump(knn,'./knn.m')

knn = joblib.load('./knn.m')

# 讓模型進行外部模型的識別操作

img_arr = plt.imread('f:/數字.jpg')

plt.imshow(img_arr)

five_img = img_arr[95:150,85:130]

plt.imshow(five_img)

five_img.shape

# 對目標**進行降維

five_img = five_img.mean(axis=2)

# 將**的畫素壓縮成和樣本同樣的畫素,即28*28

import scipy.ndimage as ndimage

five_img.shape

five = ndimage.zoom(five_img,zoom=(28/55,28/45))

five.shape

knn.predict(five.reshape(1,784))

最終獲得結果

KNN手寫數字識別

以歐幾里得距離度量樣本間的相似程度。對於乙個測試樣本首先計算該樣本與每個訓練樣本間的距離,然後按距離值對訓練樣本進行公升序排序,排序後前k個樣本進行投票,即哪個標籤出現的次數多,就將測試樣例劃為該類。程式使用資料 預先將資料處理為,標籤資訊轉化為txt文件。from numpy import imp...

kNN 手寫數字識別

識別手寫的數字0 9,影象為32畫素 32畫素的黑白影象 1.將影象轉換為向量 將32 32的二進位制影象矩陣轉換為1 1024的向量。將影象轉化為向量 defimgvector filename returnvect zeros 1,1024 fr open filename 讀取檔案的前32行 ...

KNN手寫數字識別

import numpy as np import matplotlib pyplot as plt from sklearn.neighbors import kneighborsclassifier 讀取樣本資料,目標 0,1,2,3,4,5,6,7,8,9 feature target for...