機械学習で画像分類を行なっています
python
1# coding:utf-8 2import keras 3from keras.utils import np_utils 4from keras.layers.convolutional import Conv2D, MaxPooling2D 5from keras.models import Sequential 6from keras.layers.core import Dense, Dropout, Activation, Flatten 7from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img 8import numpy as np 9import pandas as pd 10import matplotlib.pyplot as plt 11import seaborn as sns 12from sklearn.metrics import confusion_matrix 13from sklearn.neighbors import KNeighborsClassifier 14from sklearn.model_selection import train_test_split 15 16X = []#train 17Y = [] 18A = []#validation 19B = [] 20V = []#test 21W = [] 22 23ep = 10 24size = 10,10 25 26 27 28# aの画像 29for picture in list_pictures('dir/train/a'): 30 img = img_to_array(load_img(picture, target_size=(size))) 31 X.append(img) 32 Y.append(0) 33 34for picture in list_pictures('dir/vali/a'): 35 img = img_to_array(load_img(picture, target_size=(size))) 36 A.append(img) 37 B.append(0) 38 39for picture in list_pictures('dir/test/a'): 40 img = img_to_array(load_img(picture, target_size=(size))) 41 V.append(img) 42 W.append(0) 43 44# bの画像 45for picture in list_pictures('dir/train/b'): 46 img = img_to_array(load_img(picture, target_size=(size))) 47 X.append(img) 48 Y.append(1) 49 50for picture in list_pictures('dir/vali/b'): 51 img = img_to_array(load_img(picture, target_size=(size))) 52 A.append(img) 53 B.append(1) 54 55for picture in list_pictures('dir/test/b'): 56 img = img_to_array(load_img(picture, target_size=(size))) 57 V.append(img) 58 W.append(1) 59 60# cの画像 61for picture in list_pictures('dir/train/c'): 62 img = img_to_array(load_img(picture, target_size=(size))) 63 X.append(img) 64 Y.append(2) 65 66for picture in list_pictures('dir/vali/c'): 67 img = img_to_array(load_img(picture, target_size=(size))) 68 A.append(img) 69 B.append(2) 70 71for picture in list_pictures('dir/test/c'): 72 img = img_to_array(load_img(picture, target_size=(size))) 73 V.append(img) 74 W.append(2) 75 76X = np.asarray(X) 77Y = np.asarray(Y) 78A = np.asarray(A) 79B = np.asarray(B) 80V = np.asarray(V) 81W = np.asarray(W) 82 83# 画素値を0から1の範囲に変換 84X = X.astype('float32') 85X = X / 255.0 86A = A.astype('float32') 87A = A / 255.0 88V = V.astype('float32') 89V = V / 255.0 90 91# クラスの形式を変換 92Y = np_utils.to_categorical(Y, 3)#(ベクトル変換したいラベル、配列数) 93B = np_utils.to_categorical(B, 3) 94W = np_utils.to_categorical(W, 3) 95 96X_train, Y_train = (X, Y) 97A_vali, B_vali = (A, B) 98V_test, W_test = (V, W) 99 100# 【CNNを構築】 101model = Sequential() 102model.add(Conv2D(32, (3, 3), padding='same', 103 input_shape=X_train.shape[1:])) 104model.add(Activation('relu')) 105model.add(Conv2D(32, (3, 3))) 106model.add(Activation('relu')) 107model.add(MaxPooling2D(pool_size=(2, 2))) 108model.add(Dropout(0.4)) 109model.add(Conv2D(64, (3, 3), padding='same')) 110model.add(Activation('relu')) 111model.add(Conv2D(64, (3, 3))) 112model.add(Activation('relu')) 113model.add(MaxPooling2D(pool_size=(2, 2))) 114model.add(Dropout(0.4)) 115model.add(Flatten()) 116model.add(Dense(512)) 117model.add(Activation('relu')) 118model.add(Dropout(0.4)) 119model.add(Dense(3))#カテゴリー数 120model.add(Activation('softmax')) 121 122# 【コンパイル】 123model.compile(loss='categorical_crossentropy',#損失関数 124 optimizer='adam',#最適化、オブジェクト 125 metrics=['accuracy'])#評価関数、正解率 126 127#【学習実行】 128history = model.fit(X_train, Y_train, batch_size=2048, epochs=ep, 129 validation_data = (A_vali, B_vali), verbose = 1) 130 131score = model.evaluate(V_test, W_test, verbose = 1) 132print("test_acc", score[1], "test_loss", score[0]) 133
機械学習後に
python
1import cv2 2import numpy as np 3import os 4import glob 5%matplotlib inline 6 7size = 10,10,3 8# ラベル情報 9labels = ["a","b","c"] 10 11# モデルデータを読み込み 12model.load_weights('weight.h5') 13 14files = glob.glob("Desktop/test/a/*.png") 15for f in files: 16 im = cv2.imread(f, cv2.COLOR_BGR2RGB) 17 im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) 18 im = cv2.resize(im, (10,10)) 19 plt.imshow(im) 20 plt.show() 21 im = im.reshape(size).astype('float32') / 255 22 r = model.predict(np.array([im]), batch_size=32,verbose=1) 23 res = r[0] 24 for i, acc in enumerate(res): 25 print(labels[i], "=", int(acc * 100)) 26 if labels[0] == res.argmax(): 27 print("予測結果=", labels[res.argmax()]) 28 29 else: 30 print("予測結果=", labels[res.argmax()]) 31 if res.argmax() == 1: 32 print("bです") 33 img = cv2.imread('dir/b.png') 34 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 35 img = cv2.resize(img, (300,300)) 36 plt.imshow(img) 37 plt.show() 38 39 elif res.argmax() == 2: 40 print("cです") 41 img = cv2.imread('dir/c.png') 42 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 43 img = cv2.resize(img, (300,300)) 44 plt.imshow(img) 45 plt.show() 46
理想はこのような感じです
python
1#a画像の表示 #b画像の表示 21/1 [==============================] - 0s 978us/step 3a=1 4b=90 5c=10 6予測結果= b 7 8#上記を文章も含めてこのまま画像として保存したい
このようにtest画像を読み、どの画像をどのように間違っていたか評価しています。
a画像をbと間違っていた場合、bの画像を表示するようにしています。
誤判定していた場合に隣に画像を並べる場合に、隣同士で並べ、指定したフォルダに文章ごと保存したいですが、どのようにしたらいいでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。