前提・実現したいこと
CNNを用いて、筆者識別を行いたい。
下記のソースコード実行時に、エラーが発生した。
実際に認識を行い、特徴抽出を行いたい。
発生している問題・エラーメッセージ
runfile('C:/Users/sugitalab/Desktop/S315401/char/cnn.py', wdir='C:/Users/sugitalab/Desktop/S315401/char') Traceback (most recent call last): File "<ipython-input-2-098afa90c49c>", line 1, in <module> runfile('C:/Users/sugitalab/Desktop/S315401/char/cnn.py', wdir='C:/Users/sugitalab/Desktop/S315401/char') File "C:\Users\sugitalab\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\sugitalab\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/sugitalab/Desktop/S315401/char/cnn.py", line 162, in <module> test(file_path="./test_char_su/*", day_name=day_name) File "C:/Users/sugitalab/Desktop/S315401/char/cnn.py", line 133, in test cnn(X, y, 0, file_path, day_name=day_name) File "C:/Users/sugitalab/Desktop/S315401/char/cnn.py", line 75, in cnn height, width = X.shape[1], X.shape[2] IndexError: tuple index out of range
該当のソースコード
from keras.models import Sequential from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPool2D from keras.optimizers import Adam from keras.layers.core import Dense, Activation, Dropout, Flatten from keras.layers.advanced_activations import LeakyReLU from keras.utils import plot_model from keras.callbacks import TensorBoard from keras.utils import np_utils import numpy as np from PIL import Image import cv2 import glob from sklearn.model_selection import train_test_split import tensorflow as tf from keras import backend as K from keras.preprocessing import image import matplotlib.pyplot as plt import os K.clear_session() #tf.reset_default_graph() import math from keras.models import load_model #from keras import get_activations from keras.models import Model from keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint from sklearn.preprocessing import MinMaxScaler import sys from sklearn.metrics import confusion_matrix, accuracy_score, classification_report np.set_printoptions(threshold=np.inf) fig, (axL, axR) = plt.subplots(ncols=2, figsize=(10,4)) def binary(file_path, save_path): # return img file_list = glob.glob(file_path) for i in range(len(file_list)): name=os.path.basename(file_list[i]) save_name=name[0] gray_img = cv2.imread(file_path[:-1]+name, cv2.IMREAD_GRAYSCALE) blur_img = cv2.GaussianBlur(gray_img, (5,5), 0) ret, bin_img = cv2.threshold(blur_img, 0, 255, cv2.THRESH_OTSU) cv2.imwrite(save_path+'{}_{}.jpg'.format(save_name,i), bin_img) def make_list(file_path, flag=None): X = [] y = [] file_list = glob.glob(file_path) for i in range(len(file_list)): file = file_list[i] file_name = os.path.basename(file)[0] img = cv2.imread(file, cv2.IMREAD_GRAYSCALE) ret, tmp_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) X.append(tmp_img) if file_name == 'a': y.append(0) elif file_name == 'b': y.append(1) X = np.array(X) y = np.array(y) return X, y def cnn(X, y, flag=None, file_path=None, day_name=None): # return value : <training:model>, <test:None> height, width = X.shape[1], X.shape[2] print(height, width) print("X.shape:", X.shape) print("X shape:", X[0].shape) X = X.astype('float')/255.0 if flag==0: print("X: ", X.shape) X_test = X.reshape(X.shape[0], height, width, 1) print("X: ", X_test.shape) y_test = np_utils.to_categorical(y, 2) print("X_test.shape :",X_test.shape) model = load_model("./model/model_{}.h5".format(day_name)) model.load_weights("./model_weight/weight_ep1000_es_{}.h5".format(day_name)) model.summary() score = model.evaluate(X_test, y_test) print("test loss: ", score[0], "acc: {:.4f}".format(score[1])) predict = model.predict(X_test) print(predict.shape) for i in range(predict.shape[0]): print("{} : <{}, {}> <{:4f}%, {:4f}%>".format(i, y_test[i][0], y_test[i][1], predict[i][0]*100, predict[i][1]*100)) ### metrics cnt_o, cnt_t = 0, 0 for i in range(len(y_test)): if y_test[i][0]==1: cnt_o+=1 elif y_test[i][1]==1: cnt_t+=1 print("cnt_o: {}, cnt_t: {}".format(cnt_o, cnt_t)) target_names = ['class0', 'class1'] print(confusion_matrix(y_test.argmax(axis=1), predict.argmax(axis=1))) print(accuracy_score(y_test.argmax(axis=1), predict.argmax(axis=1))) print(classification_report(y_test.argmax(axis=1), predict.argmax(axis=1))) print(y_test.argmax(axis=1)) print(predict.argmax(axis=1)) print('*'*20) print(predict.argmax(axis=1)) ### predict = list(predict) with open("./acc.csv", "w") as f: for i in range(40): f.write("{},{}\n".format(predict[i][0], predict[i][1])) return None def test(file_path=None, day_name=None): X, y = make_list(file_path) cnn(X, y, 0, file_path, day_name=day_name) # loss def plot_history_loss(fit): # Plot the loss in the history axL.plot(fit.history['loss'],label="トレーニングデータ") axL.plot(fit.history['val_loss'],label="検証用データ") axL.set_title('エポックごとの損失') axL.set_xlabel('エポック [回]') axL.set_ylabel('損失') axL.legend(loc='upper right') # acc def plot_history_acc(fit): # Plot the loss in the history axR.plot(fit.history['acc'],label="トレーニングデータ") axR.plot(fit.history['val_acc'],label="検証用データ") axR.set_title('エポックごとの正解率') axR.set_xlabel('エポック [回]') axR.set_ylabel('正解率') axR.legend(loc='lower right') if __name__ == "__main__": day_name="20190207_0" test(file_path="./test_char_su/*", day_name=day_name)
試したこと
動作箇所のコメント化
make_list関数の戻り値確認
補足情報(FW/ツールのバージョンなど)
あなたの回答
tips
プレビュー