model.fitした際に、Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 64 but received input with shape [None, 64, 64, 3]と表示され、正常にmodel.fit出来ない。
エラー文
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 64 but received input with shape [None, 64, 64, 3]
Python
1import os, cv2, random 2import numpy as np 3import pandas as pd 4 5import matplotlib.pyplot as plt 6from matplotlib import ticker 7import seaborn as sns 8%matplotlib inline 9 10import tensorflow 11from tensorflow.keras.models import Sequential 12from tensorflow.keras.layers import Input, Dropout, Flatten, Convolution2D, MaxPooling2D, Dense, Activation 13from tensorflow.keras.optimizers import RMSprop 14from tensorflow.keras.callbacks import ModelCheckpoint, Callback, EarlyStopping 15import np_utils 16 17TRAIN_DIR = './archive/casting_data/casting_data/train/' 18TEST_DIR = './archive/casting_data/casting_data/test/' 19 20 21ROWS = 64 22COLS = 64 23CHANNELS = 3 24 25train_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] # use this for full dataset 26train_ok = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cast_ok' in i] 27train_def = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cast_def' in i] 28 29test_images = [TEST_DIR+i for i in os.listdir(TEST_DIR)] 30 31# slice datasets for memory efficiency on Kaggle Kernels, delete if using full dataset 32train_images = train_ok + train_def 33random.shuffle(train_images) 34test_images = test_images 35 36def read_image(file_path): 37 img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE 38 return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC) 39 40 41def prep_data(images): 42 count = len(images) 43 data = np.ndarray((count, CHANNELS, ROWS, COLS), dtype=np.uint8) 44 45 for i, image_file in enumerate(images): 46 image = read_image(image_file) 47 data[i] = image.T #transpose mxn > nxm 48 if i%250 == 0: print('Processed {} of {}'.format(i, count)) 49 50 return data 51 52train = prep_data(train_images) 53test = prep_data(test_images) 54 55print("Train shape: {}".format(train.shape)) 56print("Test shape: {}".format(test.shape)) 57 58labels = [] 59for i in train_images: 60 if 'cast_ok_' in i: 61 labels.append(1) 62 else: 63 labels.append(0) 64 65sns.countplot(labels) 66plt.title('OK and def') 67 68labels = np.array(labels) 69 70def show_OK_and_def(idx): 71 OK = read_image(train_ok[idx]) 72 DEF = read_image(train_def[idx]) 73 pair = np.concatenate((DEF, OK), axis=1) 74 plt.figure(figsize=(10,5)) 75 plt.imshow(pair) 76 plt.show() 77 78DEF_avg = np.array([DEF[0].T for i, DEF in enumerate(train) if labels[i]==1]).mean(axis=0) 79plt.imshow(DEF_avg) 80plt.title('Average DEF') 81 82OK_avg = np.array([OK[0].T for i, OK in enumerate(train) if labels[i]==0]).mean(axis=0) 83plt.imshow(OK_avg) 84plt.title('Average OK') 85 86optimizer = RMSprop(lr=1e-4) 87objective = 'binary_crossentropy' 88 89 90def OKDEF(): 91 92 model = Sequential() 93 94 model.add(Convolution2D(32, (3, 3), input_shape=(3, ROWS, COLS), activation='relu', padding="same")) 95 model.add(Convolution2D(32, (3, 3), activation='relu', padding="same")) 96 model.add(MaxPooling2D(data_format="channels_first", pool_size=(2, 2))) 97 98 model.add(Convolution2D(64, (3, 3), activation='relu', padding="same")) 99 model.add(Convolution2D(64, (3, 3), activation='relu', padding="same")) 100 model.add(MaxPooling2D(data_format="channels_first", pool_size=(2, 2))) 101 102 model.add(Convolution2D(128, (3, 3), activation='relu', padding="same")) 103 model.add(Convolution2D(128, (3, 3), activation='relu', padding="same")) 104 model.add(MaxPooling2D(data_format="channels_first", pool_size=(2, 2))) 105 106 model.add(Convolution2D(256, (3, 3), activation='relu', padding="same")) 107 model.add(Convolution2D(256, (3, 3), activation='relu', padding="same")) 108 model.add(MaxPooling2D(data_format="channels_first", pool_size=(2, 2))) 109 110 model.add(Flatten()) 111 model.add(Dense(256, activation='relu')) 112 model.add(Dropout(0.5)) 113 114 model.add(Dense(256, activation='relu')) 115 model.add(Dropout(0.5)) 116 117 model.add(Dense(1)) 118 model.add(Activation('sigmoid')) 119 120 model.compile(loss=objective, optimizer=optimizer, metrics=['accuracy']) 121 return model 122 123 124model = OKDEF() 125 126train = tensorflow.transpose(train, [0, 2, 3, 1]) 127test = tensorflow.transpose(test,[0, 2, 3, 1]) 128 129epochs = 10 130batch_size = 16 131 132class LossHistory(Callback): 133 def on_train_begin(self, logs={}): 134 self.losses = [] 135 self.val_losses = [] 136 137 def on_epoch_end(self, batch, logs={}): 138 self.losses.append(logs.get('loss')) 139 self.val_losses.append(logs.get('val_loss')) 140 141early_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='auto') 142 143def run_OKDEF(): 144 145 history = LossHistory() 146 model.fit(train, labels, batch_size=batch_size, epochs=epochs, 147 validation_split=0.25, verbose=0, shuffle=True, callbacks=[history, early_stopping]) 148 149 predictions = model.predict(test, verbose=0) 150 return predictions, history 151 152predictions, history = run_OKDEF()
エラーの確認
エラー文を用いた検索
バージョン
windows 11
Python 3.8.8
tensorflow 2.3.0
あなたの回答
tips
プレビュー