こちらのページを参考にローカルに保存してあるcifar-10の画像でcnnを実行してみたのですが、エラーが出てしまいました。
python
1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3import keras 4from keras.utils import np_utils 5from keras.layers.convolutional import Conv2D, MaxPooling2D 6from keras.models import Sequential 7from keras.layers.core import Dense, Dropout, Activation, Flatten 8from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img 9import numpy as np 10import pandas as pd 11from sklearn.model_selection import train_test_split 12import matplotlib.pyplot as plt 13 14temp_img = load_img('./test/test1.jpg', target_size=(64,64)) 15temp_img_array = img_to_array(temp_img) 16 17X = [] 18Y = [] 19 20# 対象airplaneの画像 21for picture in list_pictures('/Users/name/Desktop/cif-train/airplane'): 22 img = img_to_array(load_img(picture, target_size=(64,64))) 23 X.append(img) 24 25 Y.append(0) 26 27# 対象automobileの画像 28for picture in list_pictures('/Users/name/Desktop/cif-train/automobile'): 29 img = img_to_array(load_img(picture, target_size=(64,64))) 30 X.append(img) 31 32 Y.append(1) 33 34# 対象birdの画像 35for picture in list_pictures('/Users/name/Desktop/cif-train/bird'): 36 img = img_to_array(load_img(picture, target_size=(64,64))) 37 X.append(img) 38 39 Y.append(2) 40 41# 対象catの画像 42for picture in list_pictures('/Users/name/Desktop/cif-train/cat'): 43 img = img_to_array(load_img(picture, target_size=(64,64))) 44 X.append(img) 45 46 Y.append(3) 47 48# 対象deerの画像 49for picture in list_pictures('/Users/name/Desktop/cif-train/deer'): 50 img = img_to_array(load_img(picture, target_size=(64,64))) 51 X.append(img) 52 53 Y.append(4) 54 55# 対象dogの画像 56for picture in list_pictures('/Users/name/Desktop/cif-train/dog'): 57 img = img_to_array(load_img(picture, target_size=(64,64))) 58 X.append(img) 59 60 Y.append(5) 61 62# 対象frogの画像 63for picture in list_pictures('/Users/name/Desktop/cif-train/frog'): 64 img = img_to_array(load_img(picture, target_size=(64,64))) 65 X.append(img) 66 67 Y.append(6) 68 69# 対象horseの画像 70for picture in list_pictures('/Users/name/Desktop/cif-train/horse'): 71 img = img_to_array(load_img(picture, target_size=(64,64))) 72 X.append(img) 73 74 Y.append(7) 75 76# 対象shipの画像 77for picture in list_pictures('/Users/name/Desktop/cif-train/ship'): 78 img = img_to_array(load_img(picture, target_size=(64,64))) 79 X.append(img) 80 81 Y.append(8) 82 83# 対象truckの画像 84for picture in list_pictures('/Users/name/Desktop/cif-train/truck'): 85 img = img_to_array(load_img(picture, target_size=(64,64))) 86 X.append(img) 87 88 Y.append(9) 89 90# arrayに変換 91X = np.asarray(X) 92Y = np.asarray(Y) 93 94# 画素値を0から1の範囲に変換 95X = X.astype('float32') 96X = X / 255.0 97 98# クラスの形式を変換 99Y = np_utils.to_categorical(Y, 9) 100 101# 学習用データとテストデータ 102X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=111) 103#2割がtest 104 105# CNNを構築 106model = Sequential() 107 108model.add(Conv2D(32, (3, 3), padding='same', 109 input_shape=X_train.shape[1:])) 110model.add(Activation('relu')) 111model.add(Conv2D(32, (3, 3))) 112model.add(Activation('relu')) 113model.add(MaxPooling2D(pool_size=(2, 2))) 114model.add(Dropout(0.25)) 115 116model.add(Conv2D(64, (3, 3), padding='same')) 117model.add(Activation('relu')) 118model.add(Conv2D(64, (3, 3))) 119model.add(Activation('relu')) 120model.add(MaxPooling2D(pool_size=(2, 2))) 121model.add(Dropout(0.25)) 122 123model.add(Flatten()) 124model.add(Dense(512)) 125model.add(Activation('relu')) 126model.add(Dropout(0.5)) 127model.add(Dense(2)) # クラスは2個 128model.add(Activation('softmax')) 129 130# コンパイル 131model.compile(loss='categorical_crossentropy', 132 optimizer='SGD',#参考書はadam 133 metrics=['accuracy']) 134 135# 実行。出力はなしで設定(verbose=0)。 136history = model.fit(X_train, y_train, batch_size=5, epochs=200, 137 validation_data = (X_test, y_test), verbose = 0) 138 139#参考書はbatch=32,epoch=1,verbose=1 140 141plt.plot(history.history['acc']) 142plt.plot(history.history['val_acc']) 143plt.title('model accuracy') 144plt.xlabel('epoch') 145plt.ylabel('accuracy') 146plt.legend(['acc', 'val_acc'], loc='lower right') 147plt.show() 148 149# テストデータに適用 150predict_classes = model.predict_classes(X_test) 151 152# マージ。yのデータは元に戻す 153mg_df = pd.DataFrame({'predict': predict_classes, 'class': np.argmax(y_test, axis=1)}) 154 155# confusion matrix 156pd.crosstab(mg_df['class'], mg_df['predict']) 157 158
エラーは以下の通りです
python
1ValueError Traceback (most recent call last) 2<ipython-input-26-524378df711d> in <module> 3 105 4 106 model.add(Conv2D(32, (3, 3), padding='same', 5--> 107 input_shape=X_train.shape[1:])) 6 108 model.add(Activation('relu')) 7 109 model.add(Conv2D(32, (3, 3))) 8 9~/anaconda3/lib/python3.6/site-packages/keras/models.py in add(self, layer) 10 465 # and create the node connecting the current layer 11 466 # to the input layer we just created. 12--> 467 layer(x) 13 468 14 469 if len(layer._inbound_nodes[-1].output_tensors) != 1: 15 16~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs) 17 571 # Raise exceptions in case the input is not compatible 18 572 # with the input_spec specified in the layer constructor. 19--> 573 self.assert_input_compatibility(inputs) 20 574 21 575 # Collect input shapes to build layer. 22 23~/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py in assert_input_compatibility(self, inputs) 24 470 self.name + ': expected ndim=' + 25 471 str(spec.ndim) + ', found ndim=' + 26--> 472 str(K.ndim(x))) 27 473 if spec.max_ndim is not None: 28 474 ndim = K.ndim(x) 29 30ValueError: Input 0 is incompatible with layer conv2d_17: expected ndim=4, found ndim=1
エラーをどのように訂正していいのか不明な点と
temp_img = load_img('./test/test1.jpg', target_size=(64,64))
temp_img_array = img_to_array(temp_img)
この2行はtest1.jpgをロードしてarrayに変換しているということはわかるのですが、意図がわかりません。
ディレクトリごと変換するために使用するということでしょうか?
その下の# 対象airplaneの画像というところで変換されると思うのですが。。。
教えていただきたいです。宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。