【问题标题】:ValueError: non-broadcastable output operand with shape (256,256,1) doesn't match the broadcast shape (256,256,3)ValueError:形状为 (256,256,1) 的不可广播输出操作数与广播形状 (256,256,3) 不匹配
【发布时间】:2021-06-09 12:06:04
【问题描述】:

我正在使用 CNN 来训练灰度图像数据集(5 类)。图像大小为(100,100),像素值在 0-1 之间 代码:

from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import cv2

        
train = ImageDataGenerator(rescale=(100,100,1))
validation = ImageDataGenerator(rescale=(100,100,1))

train_dataset = train.flow_from_directory('C:/Users/abdul/OneDrive/Desktop/New folder/FYP/final/images/train',color_mode='grayscale')
validate_dataset = validation.flow_from_directory('C:/Users/abdul/OneDrive/Desktop/New folder/FYP/final/images/validate',color_mode='grayscale') 

model = tf.keras.models.Sequential([
    #convolutional layer
    tf.keras.layers.Conv2D(32,(3,3), activation ="relu", input_shape = (100,100,1)),
    
    # Flatten units
    tf.keras.layers.Flatten(),

    # Add a hidden layer with dropout
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dropout(0.5),

    # Add an output layer with output units for all 10 digits
    tf.keras.layers.Dense(4, activation="softmax")
])

# Train neural network
model.compile(
    optimizer="adam",
    loss="categorical_crossentropy",
    metrics=["accuracy"]
)

model.fit(train_dataset, epochs=10,validation_data = validate_dataset)

【问题讨论】:

    标签: python tensorflow keras conv-neural-network


    【解决方案1】:

    您的数据生成器存在一些问题。在rescale 中,您错误地设置了输入大小(可能),您应该在其中设置一些用于规范化输入的因素。根据文档:

    rescale:重新缩放因子。默认为无。如果 None 或 0,则不应用重新缩放,否则我们将数据乘以提供的值(在应用所有其他转换之后)。

    并且,默认情况下,target_size256 x 256,但您的模型输入是 100 x 100,因此您需要正确指定,否则数据加载器将根据其默认值 256 生成一个形状为 256 的图像。根据文档

    target_size:整数元组(高度,宽度),默认值:(256, 256)。找到的所有图像都将调整到的尺寸。

    进行这些更改后,您应该执行以下操作:

    train = ImageDataGenerator(rescale=1/255.)
    train_dataset = train.flow_from_directory('./train',
       color_mode='grayscale',
       class_mode='categorical', # one hot or 'sparse' if labels are integer
       target_size=(100, 100))
    

    对验证部分做同样的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2018-05-09
      • 2020-03-07
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多