前提・実現したいこと
雲の画像を学習させて種類の分類を行おうとしています
機械学習始めたばかりの初心者なのであまり理解が足りていないだけかもしれません
発生している問題・エラーメッセージ
WARNING:tensorflow:Model was constructed with shape (None, None, None, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"), but it was called on an input with incompatible shape (None, 1). --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-17-913039fb19c7> in <module>() ----> 1 model.fit(image_list_numpy, label_list, epochs=1000, batch_size=64, verbose=1, validation_split=0.2) 9 frames /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 992 except Exception as e: # pylint:disable=broad-except 993 if hasattr(e, "ag_error_metadata"): --> 994 raise e.ag_error_metadata.to_exception(e) 995 else: 996 raise ValueError: in user code: /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function * return step_function(self, iterator) /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:842 step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1286 run return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica return self._call_for_each_replica(fn, args, kwargs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica return fn(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:835 run_step ** outputs = model.train_step(data) /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:787 train_step y_pred = self(x, training=True) /usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py:1037 __call__ outputs = call_fn(inputs, *args, **kwargs) /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:415 call inputs, training=training, mask=mask) /usr/local/lib/python3.7/dist-packages/keras/engine/functional.py:550 _run_internal_graph outputs = node.layer(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py:1020 __call__ input_spec.assert_input_compatibility(self.input_spec, inputs, self.name) /usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py:234 assert_input_compatibility str(tuple(shape))) ValueError: Input 0 of layer conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 1)
該当のソースコード
python
1import tensorflow as tf 2from keras.applications.inception_v3 import InceptionV3 3from keras.models import Model 4from keras.layers import Dense, GlobalAveragePooling2D 5from tensorflow.keras.optimizers import SGD 6from keras.regularizers import l2 7import numpy as np 8from PIL import Image 9import os 10 11for dir in os.listdir("/content/drive/MyDrive/data/train"): 12 dir1 = "/content/drive/MyDrive/data/train/" + dir 13 label = 0 14 15 if dir == "KenUn": # 巻雲はラベル0 16 label = 0 17 elif dir == "KensekiUn": # 巻積雲はラベル1 18 label = 1 19 elif dir == "KensouUn": # 巻層雲はラベル2 20 label = 2 21 elif dir == "KousekiUn": # 高積雲はラベル3 22 label = 3 23 elif dir == "KousouUn": # 高層雲はラベル4 24 label = 4 25 elif dir == "RansouUn": # 乱層雲はラベル5 26 label = 5 27 elif dir == "SousekiUn": # 層積雲はラベル6 28 label = 6 29 elif dir == "SouUn": # 層雲はラベル7 30 label = 7 31 elif dir == "SekiranUn": # 積乱雲はラベル8 32 label = 8 33 elif dir == "SekiUn": # 積雲はラベル9 34 label = 9 35 for file in os.listdir(dir1): 36 # label_listに正解ラベルを追加 37 label_list.append(label) 38 filepath = dir1 + "/" + file 39 # 画像を299x299pixelに変換し、2次元配列として読み込む 40 image =np.array(Image.open(filepath).resize((299, 299))) 41 print(filepath) 42 # 画像をimage_listに追加(値を-1~1に変換) 43 image_list.append((image/127.5)-1.0) 44 45# kerasに渡すためにnumpy配列に変換 46 47numpy_list=np.array([]) 48for i in range(len(image_list)): 49 image_list_numpy=np.append(numpy_list,image_list[i]) 50label_list = np.array(label_list) 51 52print(image_list_numpy) 53 54# 順番をシャッフル 55p = np.random.permutation(len(image_list)) 56image_list_numpy = image_list_numpy[p] 57label_list = label_list[p] 58 59# Inception v3モデルの読み込み ※最終層は読み込まない 60base_model = InceptionV3(weights='imagenet', include_top=False) 61# 最終層の設定 62x = base_model.output 63x = GlobalAveragePooling2D()(x) 64predictions = Dense(1, kernel_initializer="glorot_uniform", activation="sigmoid", kernel_regularizer=l2(.0005))(x) 65model = Model(inputs=base_model.input, outputs=predictions) 66for layer in base_model.layers: 67 layer.trainable = False 68# オプティマイザにSDGを使用 69opt = SGD(lr=.01, momentum=.9) 70# モデルをコンパイル 71model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["accuracy"]) 72 73print(len(image_list_numpy)) 74 75 76model.fit(image_list_numpy, label_list, epochs=1000, batch_size=64, verbose=1, validation_split=0.2)
試したこと
エラーメッセージで調べて以下を追加したのですが、これ自体がエラーを出したため全く分からなくなりました
image_list_numpy= image_list_numpy.reshape((-1,299,299,3))
補足情報(FW/ツールのバージョンなど)
回答1件
あなたの回答
tips
プレビュー