下記のようなコードで画像分類器を作成したいと考えています。
しかし、エラーが発生してしまい実行できません。
コードは同じ本から採用しています。
解決方法がありましたら、教えていただけますでしょうか。
よろしくお願い致します。
model_and_weight.h5と1.jpgというファイルは、同階層に保存済みです。
python
1from PIL import Image 2import os, glob 3from PIL import ImageFile 4ImageFile.LOAD_TRUNCATED_IMAGES = True 5 6from keras.models import Sequential 7from keras.layers import Conv2D, MaxPooling2D 8from keras.layers import Activation, Dropout, Flatten, Dense 9from keras.optimizers import RMSprop 10from keras.utils import np_utils 11import keras 12import numpy as np 13 14import sys, os 15from keras.models import load_model 16 17imsize = (150, 150) 18 19keras_param = "model_and_weight.h5" 20testpic = "1.jpg" 21 22def load_image(path): 23 img = Image.open(path) 24 img = img.convert('RGB') 25 img = img.resize(imsize) 26 img = np.asarray(img) 27 img = img / 255.0 28 return img 29 30model = load_model(keras_param) 31img = load_image(testpic) 32prd = model.predict(np.array([img])) 33print(prd) 34prelabel = np.argmax(prd, axis=1) 35if prelabel == 0: 36 print(">>> 犬") 37elif prelabel == 1: 38 print(">>> 猫")
下記に記載したのがエラー内容
python
1WARNING:tensorflow:Model was constructed with shape (None, 4, 4, 512) for input KerasTensor(type_spec=TensorSpec(shape=(None, 4, 4, 512), dtype=tf.float32, name='flatten_input'), name='flatten_input', description="created by layer 'flatten_input'"), but it was called on an input with incompatible shape (None, 150, 150, 3). 2--------------------------------------------------------------------------- 3ValueError Traceback (most recent call last) 4<ipython-input-12-baa28c867e4e> in <module> 5 35 model = load_model(keras_param) 6 36 img = load_image(testpic) 7---> 37 prd = model.predict(np.array([img])) 8 38 # print(prd) # 精度の表示 9 39 prelabel = np.argmax(prd, axis=1)
学習済みファイルの作成コード
python
1from keras.applications.vgg16 import VGG16 2from keras.preprocessing.image import ImageDataGenerator 3from keras.layers import Input 4import numpy as np 5import os 6 7num_train =2000 8num_validation=800 9img_h,img_w=150,150 10channels=3 11batch_size=32 12train_data_dir='data/train' 13validation_data_dir='data/validation' 14result_dir='results' 15 16if not os.path.exists(result_dir): 17 os.mkdir(result_dir) 18 19def save_VGG16_outputs(): 20 model=VGG16( 21 include_top=False, 22 weights='imagenet', 23 input_shape=(img_h,img_w,channels)) 24 25 model.summary() 26 27 datagen=ImageDataGenerator(rescale=1.0/255) 28 29 train_generator=datagen.flow_from_directory( 30 train_data_dir, 31 target_size=(img_w,img_h), 32 batch_size=batch_size, 33 class_mode=None, 34 shuffle=False) 35 36 print('train-label:',train_generator.class_indices) 37 38 vgg16_train=model.predict_generator( 39 train_generator, 40 verbose=1) 41 42 np.save(os.path.join(result_dir,'vgg16_train.npy'),vgg16_train) 43 44 validation_generator=datagen.flow_from_directory( 45 validation_data_dir, 46 target_size=(img_w,img_h), 47 batch_size=batch_size, 48 class_mode=None, 49 shuffle=False) 50 51 print('test-label:',validation_generator.class_indices) 52 53 vgg16_test=model.predict( 54 validation_generator, 55 verbose=1) 56 57 np.save(os.path.join(result_dir,'vgg16_test.npy'),vgg16_test) 58 59save_VGG16_outputs() 60 61import os 62import numpy as np 63from keras.models import Sequential 64from keras import optimizers 65from keras.layers import Activation,Dropout,Flatten,Dense 66 67def train_FClayer(): 68 69 train_data=np.load( 70 os.path.join(result_dir,'vgg16_train.npy')) 71 72 print(train_data.shape) 73 74 train_labels=np.array( 75 [0]*int(num_train/2)+[1]*int(num_train/2)) 76 77 validation_data=np.load( 78 os.path.join(result_dir,'vgg16_test.npy')) 79 80 print(validation_data.shape) 81 82 validation_labels=np.array( 83 [0]*int(num_validation/2)+[1]*int(num_validation/2)) 84 85 model=Sequential() 86 87 model.add(Flatten(input_shape=train_data.shape[1:])) 88 89 model.add(Dense(256,activation='relu')) 90 91 model.add(Dense(1,activation='sigmoid')) 92 93 model.compile( 94 loss='binary_crossentropy', 95 metrics=['accuracy'], 96 optimizer=optimizers.SGD(lr=1e-4,momentum=0.9),) 97 98 epoch=60 99 batch_size=32 100 history=model.fit(train_data, 101 train_labels, 102 epochs=epoch, 103 batch_size=batch_size, 104 verbose=1, 105 validation_data=(validation_data,validation_labels)) 106 with open('model.json','w') as json_file: 107 json_file.write(model.to_json()) 108 model.save('model_and_weight.h5') 109 110 return history 111 112history=train_FClayer()
画像の処理コード
python
1from keras.applications.vgg16 import VGG16 2from keras.preprocessing.image import ImageDataGenerator 3from keras.layers import Input 4import numpy as np 5import os 6 7num_eva =1 8img_h,img_w=150,150 9channels=3 10batch_size=32 11eva_data_dir='data/evaluation' 12result_dir='results' 13 14if not os.path.exists(result_dir): 15 os.mkdir(result_dir) 16 17def save_VGG16_outputs(): 18 model=VGG16( 19 include_top=False, 20 weights='imagenet', 21 input_shape=(img_h,img_w,channels)) 22 23 model.summary() 24 25 datagen=ImageDataGenerator(rescale=1.0/255) 26 27 eva_generator=datagen.flow_from_directory( 28 eva_data_dir, 29 target_size=(img_w,img_h), 30 batch_size=batch_size, 31 class_mode=None, 32 shuffle=False) 33 34 print('eva-label:',eva_generator.class_indices) 35 36 vgg16_eva=model.predict_generator( 37 eva_generator, 38 verbose=1) 39 40 np.save(os.path.join(result_dir,'vgg16_eva.npy'),vgg16_eva) 41 42 print(vgg16_eva.shape) 43 44save_VGG16_outputs() 45 46Model: "vgg16" 47_________________________________________________________________ 48Layer (type) Output Shape Param # 49================================================================= 50input_2 (InputLayer) [(None, 150, 150, 3)] 0 51_________________________________________________________________ 52block1_conv1 (Conv2D) (None, 150, 150, 64) 1792 53_________________________________________________________________ 54block1_conv2 (Conv2D) (None, 150, 150, 64) 36928 55_________________________________________________________________ 56block1_pool (MaxPooling2D) (None, 75, 75, 64) 0 57_________________________________________________________________ 58block2_conv1 (Conv2D) (None, 75, 75, 128) 73856 59_________________________________________________________________ 60block2_conv2 (Conv2D) (None, 75, 75, 128) 147584 61_________________________________________________________________ 62block2_pool (MaxPooling2D) (None, 37, 37, 128) 0 63_________________________________________________________________ 64block3_conv1 (Conv2D) (None, 37, 37, 256) 295168 65_________________________________________________________________ 66block3_conv2 (Conv2D) (None, 37, 37, 256) 590080 67_________________________________________________________________ 68block3_conv3 (Conv2D) (None, 37, 37, 256) 590080 69_________________________________________________________________ 70block3_pool (MaxPooling2D) (None, 18, 18, 256) 0 71_________________________________________________________________ 72block4_conv1 (Conv2D) (None, 18, 18, 512) 1180160 73_________________________________________________________________ 74block4_conv2 (Conv2D) (None, 18, 18, 512) 2359808 75_________________________________________________________________ 76block4_conv3 (Conv2D) (None, 18, 18, 512) 2359808 77_________________________________________________________________ 78block4_pool (MaxPooling2D) (None, 9, 9, 512) 0 79_________________________________________________________________ 80block5_conv1 (Conv2D) (None, 9, 9, 512) 2359808 81_________________________________________________________________ 82block5_conv2 (Conv2D) (None, 9, 9, 512) 2359808 83_________________________________________________________________ 84block5_conv3 (Conv2D) (None, 9, 9, 512) 2359808 85_________________________________________________________________ 86block5_pool (MaxPooling2D) (None, 4, 4, 512) 0 87================================================================= 88Total params: 14,714,688 89Trainable params: 14,714,688 90Non-trainable params: 0 91_________________________________________________________________ 92Found 1 images belonging to 1 classes. 93eva-label: {'1': 0} 941/1 [==============================] - 2s 2s/step 95(1, 4, 4, 512)
回答1件
あなたの回答
tips
プレビュー