###問題点
kerasによる画像認識を拝見し,Inception v3のfine tuning(4クラス分類)をやりたいと思っています.
しかし,最終層の設定において出力を4つに設定し,モデルのサマリを見ても
dense_1 (Dense) (None, 4) 8196 global_average_pooling2d_1[0][0]
となっているにも関わらず,以下のエラーが出ます
ValueError: Error when checking target: expected dense_1 to have shape (None, 1) but got array with shape (32, 4)
何が原因かが未だ分からないので助言をお願いしたいと思います.
以下ソースコードです.
###該当のソースコード
Python
1import os 2from keras.applications.inception_v3 import InceptionV3 3from keras.applications.inception_v3 import preprocess_input 4from keras.models import Sequential, Model 5from keras.layers import Dense, Dropout, Activation, Flatten 6from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D, AveragePooling2D 7from keras.regularizers import l2 8from keras.utils import np_utils 9from keras.utils import plot_model 10from keras.preprocessing.image import ImageDataGenerator 11from keras.callbacks import ModelCheckpoint 12import matplotlib.pyplot as plt 13import keras.backend as K 14 15epoch = 2 16 17result_dir = 'D:/result' 18if not os.path.exists(result): 19 os.mkdir(result_dir) 20 21 22def plot_history(history): 23 # 精度の履歴をプロット 24 plt.plot(history.history['acc'], "o-", label="accuracy") 25 plt.plot(history.history['val_acc'], "o-", label="val_acc") 26 plt.title('model accuracy') 27 plt.xlabel('epoch') 28 plt.ylabel('accuracy') 29 plt.legend(loc="lower right") 30 plt.show() 31 32 # 損失の履歴をプロット 33 plt.plot(history.history['loss'], "o-", label="loss", ) 34 plt.plot(history.history['val_loss'], "o-", label="val_loss") 35 plt.title('model loss') 36 plt.xlabel('epoch') 37 plt.ylabel('loss') 38 plt.legend(loc='lower right') 39 plt.show() 40 41 42def save_history(history, result_file): 43 loss = history.history['loss'] 44 acc = history.history['acc'] 45 val_loss = history.history['val_loss'] 46 val_acc = history.history['val_acc'] 47 nb_epoch = len(acc) 48 49 with open(result_file, "w") as fp: 50 fp.write("epoch\tloss\tacc\tval_loss\tval_acc\n") 51 for i in range(nb_epoch): 52 fp.write("%d\t%f\t%f\t%f\t%f\n" % (i, loss[i], acc[i], val_loss[i], val_acc[i])) 53 54 55if __name__ == '__main__': 56 classes = ['m', 'n', 'o', 'k'] 57 58 batch_size = 32 59 nb_classes = len(classes) 60 img_rows, img_cols = 299, 299 61 62 samples_per_epoch = 600 63 nb_val_samples = 99 64 65 # CNNを構築 66 # Inception v3モデルの読み込み,最終層は読み込まない 67 base_model = InceptionV3(weights='imagenet', include_top=False) 68 # 最終層の設定 69 x = base_model.output 70 x = GlobalAveragePooling2D()(x) 71 predictions = Dense(nb_classes, kernel_initializer="glorot_uniform", activation="softmax", 72 kernel_regularizer=l2(.0005))(x) 73 74 # モデルのサマリを表示 75 model = Model(inputs=base_model.input, outputs=predictions) 76 plot_model(model, show_shapes=True, to_file=os.path.join(result_dir, 'model.png')) 77 model.summary() 78 79 # base_modelはweightsを更新しない 80 for layer in base_model.layers: 81 layer.trainable = False 82 83 model.compile(loss='categorical_crossentropy', 84 optimizer='adam', 85 metrics=['accuracy']) 86 87 # ディレクトリの画像を使ったジェネレータ 88 train_datagen = ImageDataGenerator( 89 rescale=1.0 // 255, 90 shear_range=0.2, 91 zoom_range=0.2, 92 horizontal_flip=True) 93 94 test_datagen = ImageDataGenerator(rescale=1.0 // 255) 95 96 train_generator = train_datagen.flow_from_directory( 97 directory='D:/s_dir/train_images', 98 target_size=(img_rows, img_cols), 99 color_mode='rgb', 100 classes=classes, 101 class_mode='categorical', 102 batch_size=batch_size, 103 shuffle=True) 104 105 # 確認 106 print(train_generator.class_indices) 107 108 test_generator = test_datagen.flow_from_directory( 109 directory='D:/s_dir/test_images', 110 target_size=(img_rows, img_cols), 111 color_mode='rgb', 112 classes=classes, 113 class_mode='categorical', 114 batch_size=batch_size, 115 shuffle=True) 116 117 checkpointer = ModelCheckpoint(filepath='D:/result/model.{epoch:02d}-{val_loss:.2f}.hdf5', verbose=1, 118 save_best_only=True) 119 120 history = model.fit_generator( 121 train_generator, 122 steps_per_epoch=samples_per_epoch, 123 epochs=epoch, 124 validation_data=test_generator, 125 validation_steps=nb_val_samples, 126 callbacks=[checkpointer]) 127 128 save_history(history, os.path.join(result, 'history.txt')) 129 130 # modelに学習させた時の変化の様子をplot 131 plot_history(history) 132 133 loss, acc = model.evaluate_generator(test_generator, steps=400) 134 print('Test loss:', loss) 135 print('Test acc:', acc) 136 137 K.clear_session() 138
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。