質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1576閲覧

IndexError: tuple index out of rangeとでる

yuyura

総合スコア4

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

2クリップ

投稿2020/01/29 05:38

前提・実現したいこと

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/ツールのバージョンなど)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

can110

2020/01/29 05:52 編集

make_listの戻り値を確認したとのことですが、具体的になにをどのように確認し(、なにをもって正しいと判断し)ましたか? あるいは、cnn関数の引数Xのshapeはどのようなもの(値)だと意図していますか?
yuyura

2020/01/29 07:19

読み込みたい画像データの認識が、されておらず、正しいという判断には至れていません。 読み込む画像データのサイズ指定だと認識しています。 引継ぎのデータのため、理解乏しく申し訳ないです。
fukatani

2020/01/30 13:34

make_listの返り値Xをprint(X)で出力してみてください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問