kerasで学習モデルを作成したい
Kerasで2種類の表情分類(喜び・悲しみ)を行う学習モデルの作成をしています。
参考にしているサイトでは他クラス分類を行っていて、サイトを引用しながら所々書き換えているのですが、以下のようなエラーが出てしまいました。
長くなりますが、出力結果をすべて載せておきます。
ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))
Found 1400 images belonging to 2 classes. Found 300 images belonging to 2 classes. /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1844: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators. warnings.warn('`Model.fit_generator` is deprecated and ' Epoch 1/100 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-9-f36fb08357c3> in <module>() 59 epochs=100, 60 validation_data=validation_generator, ---> 61 validation_steps=10) 62 63 model.save('face_analysis_men.h5') 10 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 975 except Exception as e: # pylint:disable=broad-except 976 if hasattr(e, "ag_error_metadata"): --> 977 raise e.ag_error_metadata.to_exception(e) 978 else: 979 raise ValueError: in user code: /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function * return step_function(self, iterator) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica return self._call_for_each_replica(fn, args, kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica return fn(*args, **kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step ** outputs = model.train_step(data) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:756 train_step y, y_pred, sample_weight, regularization_losses=self.losses) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:203 __call__ loss_value = loss_obj(y_t, y_p, sample_weight=sw) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:152 __call__ losses = call_fn(y_true, y_pred) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:256 call ** return ag_fn(y_true, y_pred, **self._fn_kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper return target(*args, **kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1608 binary_crossentropy K.binary_crossentropy(y_true, y_pred, from_logits=from_logits), axis=-1) /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper return target(*args, **kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:4979 binary_crossentropy return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output) /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper return target(*args, **kwargs) /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_impl.py:174 sigmoid_cross_entropy_with_logits (logits.get_shape(), labels.get_shape())) ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))
該当のソースコード
import keras from keras import layers from keras import models from keras import optimizers from keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt import tensorflowjs as tfjs model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dropout(0.5)) model.add(layers.Dense(512, activation='relu')) model.add(layers.Dense(2, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc']) classes = ['zero', 'one'] train_dir = 'drive/My Drive/face_data/train_men' validation_dir = 'drive/My Drive/face_data/validation_men' train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True,) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_dir, target_size=(178, 218), batch_size=32, class_mode='binary') validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(178, 218), batch_size=32, class_mode='binary') history = model.fit_generator( train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=10) model.save('face_analysis_men.h5') #convert the vgg16 model into tf.js model save_path = '../drive' tfjs.converters.save_keras_model(model, save_path) print("[INFO] saved tf.js vgg16 model to disk..") acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show()
試したこと
英語の質問サイトで同じエラーが出ている方の解決策をのぞきましたが、理解できずに解決できませんでした。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/01/10 07:30