前提・実現したいこと
Python初心者です
Python3でKeras、Numpy、Tensorflowを使って画像の判別をするプログラムを組んでいたのですがテストデータとトレインデータを参照しモデルにする際にエラーが発生しました
発生している問題・エラーメッセージ
Using TensorFlow backend. --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-1-01647cf04319> in <module> 87 y_test = np_utils.to_categorical(y_test, nb_classes) 88 ---> 89 model = model.fit(X_train,y_train,epochs=6,batch_size=1,validation_data=(X_test,y_test)) 90 91 score = model.model.evaluate(x=X_test,y=y_test) ~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs) 1173 val_x, val_y, 1174 sample_weight=val_sample_weight, -> 1175 batch_size=batch_size) 1176 if self._uses_dynamic_learning_phase(): 1177 val_inputs = val_x + val_y + val_sample_weights + [0] ~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 577 feed_input_shapes, 578 check_batch_axis=False, # Don't enforce the batch size. --> 579 exception_prefix='input') 580 581 if y is not None: ~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 133 ': expected ' + names[i] + ' to have ' + 134 str(len(shape)) + ' dimensions, but got array ' --> 135 'with shape ' + str(data_shape)) 136 if not check_batch_axis: 137 data_shape = data_shape[1:] ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (0, 1)
該当のソースコード
Python
1from PIL import Image 2import os, glob 3import numpy as np 4import random, math 5 6train_dir = "/users/User/documents/train_pic" 7 8test_dir = "/users/User/documents/test_pic" 9 10categories = ["1","2","3","4","5","6"] 11 12nb_classes = len(categories) 13 14X = [] 15 16Y = [] 17 18def make_sample(files): 19 global X, Y 20 X = [] 21 Y = [] 22 for cat, fname in files: 23 add_sample(cat, fname) 24 return np.array(X), np.array(Y) 25 26def add_sample(cat, fname): 27 img = Image.open(fname) 28 img = img.convert("RGB") 29 img = img.resize((150, 150)) 30 data = np.asarray(img) 31 X.append(data) 32 Y.append(cat) 33 34trainfiles = [] 35 36testfiles = [] 37 38for idx, cat in enumerate(categories): 39 image_dir = train_dir + "/" + cat 40 files = glob.glob(image_dir + "/*.jpeg") 41 for f in files: 42 trainfiles.append((idx, f)) 43 44for idx, cat in enumerate(categories): 45 image_dir = test_dir + "/" + cat 46 files = glob.glob(image_dir + "/*.jpeg") 47 for f in files: 48 testfiles.append((idx, f)) 49 50X_train, y_train = make_sample(trainfiles) 51X_test, y_test = make_sample(testfiles) 52xy = (X_train, X_test, y_train, y_test) 53 54np.save("/users/User/documents/cat.npy", xy) 55from keras import layers, models,optimizers 56 57from PIL import Image 58import os, glob 59import numpy as np 60import random, math 61import matplotlib.pyplot as plt 62from keras.utils import np_utils 63 64os.environ ['KMP_DUPLICATE_LIB_OK'] = 'True' 65 66model = models.Sequential() 67model.add(layers.Conv2D(32,(3,3),activation="relu",input_shape=(150,150,3))) 68model.add(layers.MaxPooling2D((2,2))) 69model.add(layers.Conv2D(64,(3,3),activation="relu")) 70model.add(layers.MaxPooling2D((2,2))) 71model.add(layers.Conv2D(128,(3,3),activation="relu")) 72model.add(layers.MaxPooling2D((2,2))) 73model.add(layers.Conv2D(128,(3,3),activation="relu")) 74model.add(layers.MaxPooling2D((2,2))) 75model.add(layers.Flatten()) 76model.add(layers.Dense(512,activation="relu")) 77 78model.add(layers.Dense(6,activation="sigmoid")) 79model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy']) 80 81X_train, X_test, y_train, y_test = np.load("/users/User/documents/cat.npy",allow_pickle = True) 82 83X_train = X_train.astype("float") / 255 84X_test = X_test.astype("float") / 255 85 86y_train = np_utils.to_categorical(y_train, nb_classes) 87y_test = np_utils.to_categorical(y_test, nb_classes) 88 89model = model.fit(X_train,y_train,epochs=6,batch_size=1,validation_data=(X_test,y_test)) 90 91score = model.model.evaluate(x=X_test,y=y_test) 92 93print('loss=', score[0]) 94print('accuracy=', score[1]) 95 96for i in range(5): 97 plt.subplot(2, 5, i+1) 98 plt.imshow(X_test[i], 'gray') 99 100pred = np.argmax(model.predict(X_test[0:5]), axis=1) 101print(pred)
試したこと
自身の学習途中だったのでどういったことが原因になっているのかわからず参考にしているサイトを確認しその通りにしてみたのですがうまくいかずヴァージョン違いもいくつか発見したため書き換えましたがこのエラーが治らずに困っています
補足情報(FW/ツールのバージョンなど)
Jupyterlabを使用しています
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。