クジラ飛行机「ゼロからやさしくはじめるPython入門」第7章step04
y = f( p, x ) xは64次元(8x8)のベクトル,y は 0, 1, 2, 3, ・・・,9
教師付きデータを利用して,パラメータpを学習(調節)する。from sklearn.datasets import load_digits
digits = load_digits() # 手書き数字データセットをロードし,digitsとラベリング
#digits datasetのkeys
print( digits.keys() )
print(digits.DESCR) # データセット説明を印刷
%matplotlib inline
import matplotlib.pyplot as plt
# 手書き画像データを表示: 8px * 8px = 64px, 各pixelの明暗を0~16で表現
print( "number of data:", len(digits.data) )
n = 500
print("data number:n=", n)
print( digits.data[n] ) # 配列(サイズ64)64次元ベクトル
print( "target:", digits.target[n] ) # 正解
print( "images:", digits.images[n] ) # 2次元配列(8x8),要素の値:0..16の数値
plt.matshow(digits.images[n], cmap ="gray")
plt.show()
fig = plt.subplots(8, 10, figsize=(14, 14) ) # 8行,10列1400px*1400px
for i in range(80):
plt.subplot(8, 10, i+1).matshow(digits.images[i], cmap ="gray") # 8行10列のi+1番目
plt.xticks(color="None") # x軸の数字を非表示
plt.yticks(color="None")
plt.title( digits.target[i], y = -0.3 )
# データを学習用とテスト用に分割 --- (*1)
from sklearn.model_selection import train_test_split as split
x_train, x_test, y_train, y_test = split(digits.data, digits.target)
print( "len(x_train)=", len(x_train) )
# データを学習:アルゴリズム SVC Support Vector Classification.--- (*2)
from sklearn import svm
clf = svm.SVC(gamma = 'auto') # Support Vector Classificationオブジェクト生成, gamma = 'auto' 指定!
clf.fit(x_train, y_train ) # trainingデータで学習
# モデルを評価 --- (*3)
pred = clf.predict(x_test) # testデータで評価
print("pred=", pred)
# predの要素 と y_test(教師データ)の要素が一致する回数をカウントして,正当率を計算
result = list(pred == y_test).count(True) / len(y_test)
print("正当率=" + str(result))
# データを学習:LinearSVC
clf2 = svm.LinearSVC() # LinearSVCオブジェクト生成
clf2.fit(x_train, y_train) # trainingデータで学習
# モデルを評価
pred = clf2.predict(x_test)
result = list(pred == y_test).count(True) / len(y_test)
print("正解率=" + str(result))
isPredict = list(pred == y_test)
print('isPredict/n', isPredict)
predictFalseList = []
n = -1
for a in isPredict:
n += 1
if( a == False ):
#print(n)
predictFalseList += [n]
print('識別に失敗したデータのindex\n', predictFalseList)
fig = plt.subplots(3, 10, figsize=(14, 6) ) # 3行,10列1400px*1000px
n = 0
for i in predictFalseList:
n += 1
Nimg = x_test[i].reshape(8,8)
plt.subplot(3, 10, n).matshow( Nimg, cmap ="gray") # 5行10列のi+1番目
plt.xticks(color="None") # x軸の数字を非表示
plt.yticks(color="None")
plt.title( str( y_test[i] ) + ', ' + str( pred[i] ) , y = -0.3 ) # 図のタイトルに,教師データ(正解)と予測(回答)を表示
# 学習済みモデルを保存
from sklearn.externals import joblib
joblib.dump(clf2, "digits.pkl", compress=True)
# ファイルから学習済みモデルを読み込む
clf3 = joblib.load("digits.pkl")
# 読み込んだモデルの正解率を確かめる
pred = clf3.predict(x_test)
result = list(pred == y_test).count(True) / len(y_test)
print("正解率=" + str(result))
%matplotlib inline
from PIL import Image
from matplotlib import pylab as plt
# ファイル名を指定
png_file = "tegaki3.png"
# 画像ファイルを開く
img = Image.open(png_file)
plt.imshow(img)
# リサイズしてグレイスケールに
img.thumbnail((8, 8), Image.LANCZOS) # リサイズ, Image.LANCZOS:フィルター
img = img.convert("L") # 8bitグレイスケールに
plt.imshow(img, cmap="gray") # cmap="gray"指定!
# numpyの配列形式に変換
import numpy as np
print(img)
img_a = np.array(img, 'float') # 画像→配列 第2引数はデータ型指定
print(img_a)
img_a = 255 - img_a # ネガポジ反転
print(img_a)
img_a = img_a // 16 # 0-16の範囲に揃える
img_a = img_a.reshape(-1,) # 一次元に変換
print("---今回変換したデータ---")
print(img_a)
# 学習モデルを読み込んで判定
clf = joblib.load("digits.pkl")
result = clf.predict([img_a])
print(result) # 結果を表示
%matplotlib inline
from PIL import Image
from matplotlib import pylab as plt
import numpy as np
# 画像ファイルを指定して判定する(24bit PNG対応)
def predict_num(clf, png_file):
img = Image.open(png_file)
img.thumbnail((8, 8), Image.LANCZOS) # リサイズ
img = img.convert("L") # 8bitグレイスケール
img_a = np.array(img, 'f') # 画像→配列
img_a = 255 - img_a # ネガポジ反転
img_a = img_a // 16 # 0-16の範囲に揃える
img_a = img_a.reshape(-1,) # 一次元に変換
r = clf.predict([img_a])
return r[0]
# 学習モデルの読み込み
clf = joblib.load("digits.pkl")
# テスト画像で判定してみる
print(predict_num(clf, "tegaki5.png"))
print(predict_num(clf, "tegaki9.png"))
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(6, 5, sharex=True, sharey=True)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.1)
for i in range(30):
row = i // 5
col = i % 5
digits.images[i] = 15 - digits.images[i]
ax[row, col].imshow(digits.images[i], cmap="gray")
plt.show()
fig.savefig("digits30.png")