tensorflowをいきなり使うのは難しかったので、scikit-learnを使い数字認識を作ろうと思いました。
手順としては
1.pythonファイルを実行するとペイントソフトが起動する
2.数字を描画する
3.画像として保存
4.数字を学習したAIがその画像を認識する
5.結果を出力
今回の参考サイトは
ペイントソフトを作って、ついでに手書き数字認識もする
基本的にサイトに書かれていることしかしていないので、以下のエラーが一体何なのかわからず困っています。
K近傍法とやらのエラーっぽい感じなのはわかるのですが・・・。
インデント修正、<の変換、色指定(COLOR_WHITE)のエラーはどうにか調べて修正し、現在描画して画像を保存するところまではできています。
今回分からないエラーは
Image has saved correctly. C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\utils\deprecation.py:144: FutureWarning: The sklearn.neighbors.classification module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API. warnings.warn(message, FutureWarning) C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\utils\deprecation.py:144: FutureWarning: The sklearn.neighbors.kd_tree module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API. warnings.warn(message, FutureWarning) C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\utils\deprecation.py:144: FutureWarning: The sklearn.neighbors.dist_metrics module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API. warnings.warn(message, FutureWarning) C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\base.py:318: UserWarning: Trying to unpickle estimator KNeighborsClassifier from version 0.21.3 when using version 0.22.1. This might lead to breaking code or invalid results. Use at your own risk. UserWarning) Traceback (most recent call last): File "paint.py", line 87, in <module> App() File "paint.py", line 31, in __init__ pyxel.run(self.update, self.draw) File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\pyxel\app.py", line 255, in run main_loop() File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\pyxel\app.py", line 247, in main_loop self._update_frame() File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\pyxel\app.py", line 438, in _update_frame self._update() File "paint.py", line 57, in update self.pred_digit = model.load_predict() File "C:\Users\ユーザー名\Desktop\AI\pyxelDigitRecognition\model.py", line 43, in load_predict pred = loaded_model.predict(img)[0] # np.array to int File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\neighbors\_classification.py", line 173, in predict neigh_dist, neigh_ind = self.kneighbors(X) File "C:\Users\ユーザー名\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\neighbors\_base.py", line 580, in kneighbors n_samples_fit = self.n_samples_fit_ AttributeError: 'KNeighborsClassifier' object has no attribute 'n_samples_fit_'
コード
paint.py
1# 3rd party 2import numpy as np 3from PIL import Image 4import pyxel 5 6# my library 7import model 8 9# constants 10WINDOW_SIZE = 64 11 12 13# ===== main ===== 14class App: 15 16 # 0: white, -1: black 17 windowData = [[0]*WINDOW_SIZE for _ in range(WINDOW_SIZE)] 18 pred_digit = None 19 20 def __init__(self): 21 pyxel.init(WINDOW_SIZE, WINDOW_SIZE) 22 pyxel.mouse(visible=True) 23 pyxel.run(self.update, self.draw) 24 25 26 def update(self): 27 if pyxel.btn(pyxel.KEY_DELETE): 28 self.pred_digit = None 29 # Change each pixel's color to white 30 for y in range(pyxel.height): 31 for x in range(pyxel.width): 32 self.windowData[y][x] = 0 33 34 if pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON, hold=2, period=1): 35 # Draw a line 36 # This change pixel's colors like a star(*) 37 # (the center is (mouse_x,mouse_y)) 38 x, y = pyxel.mouse_x, pyxel.mouse_y 39 dx = [-3,-2,-1, 0, 0, 0,0,0,0,0,1,2,3,-1,-1,1,1,-2,-2,2,2] 40 dy = [ 0, 0, 0,-3,-2,-1,0,1,2,3,0,0,0,-1,1,-1,1,2,-2,2,-2] 41 for i in range(len(dx)): 42 nx, ny = x+dx[i], y+dy[i] 43 if 0 <= nx < pyxel.width and 0 <= ny < pyxel.height: 44 self.windowData[ny][nx] = -1 45 46 if pyxel.btn(pyxel.KEY_S): 47 # save image and recognize the digit 48 self._saveImage() 49 self.pred_digit = model.load_predict() 50 51 52 def draw(self): 53 pyxel.cls(7) 54 # show window 55 for y in range(pyxel.height): 56 for x in range(pyxel.width): 57 if self.windowData[y][x]==-1: 58 pyxel.pix(x, y, 0) 59 60 pyxel.text(0, 0, 'PREDICT: {}'.format(self.pred_digit), 8) 61 62 63 def _saveImage(self): 64 """ save 64x64 window's image into 8x8 picture 65 The file name is 'screen_shot.png' 66 """ 67 img = Image.new('RGB', (pyxel.width, pyxel.height)) 68 for y in range(pyxel.height): 69 for x in range(pyxel.width): 70 if self.windowData[y][x]==0: 71 img.putpixel((x,y), (255,255,255)) 72 else: 73 img.putpixel((x,y), (0,0,0)) 74 img = img.resize((8, 8), Image.BICUBIC) 75 img.save("images/screen_shot.png") 76 print("Image has saved correctly.") 77 78 79App() 80
model.py
1import numpy as np 2import pickle 3from PIL import Image 4from sklearn.datasets import load_digits 5from sklearn.model_selection import train_test_split 6from sklearn.neighbors import KNeighborsClassifier 7 8 9def train(): 10 """Train k-nearest neighbors model with Digits dataset 11 """ 12 digits = load_digits() 13 X = digits.data 14 y = digits.target 15 16 # print(X.shape) # (1797, 64) 17 # print(y.shape) # (1797,) 18 19 X_train,X_test,y_train,y_test = train_test_split(X, y) 20 21 knn = KNeighborsClassifier() 22 knn.fit(X_train, y_train) 23 # print(knn.score(X_test, y_test)) # 0.98 lol 24 25 # save model 26 with open('knn_digit.pkl', 'wb') as f: 27 pickle.dump(knn, f) 28 29 30def load_predict() -> int: 31 """load a trained model and predict 32 """ 33 34 with open('knn_digit.pkl', 'rb') as f: 35 loaded_model = pickle.load(f) 36 37 # Open image and extract features 38 img = Image.open("images/screen_shot.png") 39 img = img.convert('L') # convert (r,g,b) to gray scale (0-255) 40 img = (255 - np.array(img))//16 + 1 # convert to 0-15 41 img = img.reshape(1, 64) 42 43 pred = loaded_model.predict(img)[0] # np.array to int 44 # print("PREDICT: ", pred) 45 return pred 46
ライブラリなど
windows10
python3.6
pyxel
scikit-learn 0.22
回答1件
あなたの回答
tips
プレビュー