简体   繁体   English

在使用 Keras 运行 CNN model 时如何解决此错误?

[英]How can I solve this error during running CNN model with Keras?

When running my CNN model, below are my code with Keras运行我的 CNN model 时,下面是我的代码 Keras

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator,array_to_img, img_to_array, load_img
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt

train = ImageDataGenerator(
        rotation_range=90,    
        width_shift_range=0.2,  
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.3, 
        horizontal_flip = True, 
        vertical_flip = True,
        zca_whitening = True, 
        brightness_range=[0.2,1.2], 
        fill_mode='wrap')

test = ImageDataGenerator(rescale=1./255)

train_dataset = train.flow_from_directory("/content/drive/MyDrive/dataset",
                                          target_size=(256,256),
                                          batch_size = 32,
                                          class_mode = 'binary')
                                         
test_dataset = test.flow_from_directory("/content/drive/MyDrive/dataset",
                                          target_size=(256,256),
                                          batch_size = 32,
                                          class_mode = 'binary')

model = keras.Sequential()

# Convolutional layer and maxpool layer 1
model.add(keras.layers.Conv2D(64,(3,3),activation='relu',input_shape=(256,256,3)))
model.add(keras.layers.MaxPool2D(2,2))

# Convolutional layer and maxpool layer 2
model.add(keras.layers.Conv2D(128,(3,3),activation='relu'))
model.add(keras.layers.MaxPool2D(2,2))

# Convolutional layer and maxpool layer 3
model.add(keras.layers.Conv2D(256,(3,3),activation='relu'))
model.add(keras.layers.MaxPool2D(2,2))

# Flattening Operation
model.add(keras.layers.Flatten())

# Fully Connected layer
model.add(keras.layers.Dense(1024,activation='relu'))

## Output layer
model.add(keras.layers.Dense(10,activation='softmax'))  

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

train_imagesize = 327
batch_size = 32
epochs = 10 
steps_per_epoch = train_imagesize//batch_size

model.fit_generator(
         train_dataset,
         steps_per_epoch = steps_per_epoch,
         epochs = epochs,
         validation_data = test_dataset)

I get such errors below, which show the error from my validation_data = test_dataset line, but I do not really understand the meaning of logits and labels must have the same shape.我在下面收到这样的错误,显示了我的validation_data = test_dataset行中的错误,但我并不真正理解logitslabels的含义必须具有相同的形状。


ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1021, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1000, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 860, in train_step
        loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 919, in compute_loss
        y, y_pred, sample_weight, regularization_losses=self.losses)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 201, in __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 141, in __call__
        losses = call_fn(y_true, y_pred)
    File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 245, in call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 1932, in binary_crossentropy
        backend.binary_crossentropy(y_true, y_pred, from_logits=from_logits),
    File "/usr/local/lib/python3.7/dist-packages/keras/backend.py", line 5247, in binary_crossentropy
        return tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)

    ValueError: `logits` and `labels` must have the same shape, received ((None, 10) vs (None, 1)).

I have no idea how to solve this.我不知道如何解决这个问题。 Any help is appreciated.任何帮助表示赞赏。

Because this is a binary classification problem, the output layer should have 1 neuron(unit) and a sigmoid activation function. To overcome the error, replace the following line of code:因为这是一个二元分类问题,output 层应该有 1 个神经元(单元)和一个sigmoid激活 function。要克服错误,请替换以下代码行:

# Output layer
model.add(keras.layers.Dense(10,activation='softmax'))

with the following code:使用以下代码:

# Output layer
model.add(keras.layers.Dense(1,activation='sigmoid'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 CNN 模型 Keras 解决错误? - How can solve Error with CNN Model Keras? 如何预测 Keras CNN model 中的单个图像? - How can I predict single image in Keras CNN model? 如何解决 tensorflow CNN 中“:形状不兼容”的错误? - How can I solve error of ": Incompatible shapes" in tensorflow CNN? 如何使用功能 API 模型实现 CNN 并解决 keras 层中的“_keras_shape”错误 - How do I implement CNN using Functional API model and resolve '_keras_shape' error in keras layers 如何解决 keras model 中的输入大小问题? - How I can solve a problem with input size in a keras model? 当我在 python 中使用自定义数据生成器将数据与 CNN model 拟合时,如何解决“ValueError: 0 is not in range”?(tf.Keras.utils.Sequence)) - How to solve the "ValueError: 0 is not in range" when I fit data with CNN model using custom data generator in python ?(tf.Keras.utils.Sequence)) 如何使用现有CNN模型中的预训练权重在Keras中进行迁移学习? - How can I use pre-trained weights from an existing CNN model for transfer learning in Keras? 如何在 CNN model 中添加用户定义的激活 function 而不是 Z0623009BB15C81621 中的内置 function? - How can I add user defined activation function in CNN model instead of builtin function in keras? 如何在测试 Costum resnet model 期间解决此错误? - How do I solve this error during testing Costum resnet model? 使用keras加载模型时如何解决错误 - How to solve error while loading model with keras
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM