【问题标题】:Trying to make machine learning code with python. but i get error when first epoch finishes尝试用 python 编写机器学习代码。但是当第一个时代结束时我得到错误
【发布时间】:2021-11-24 23:19:08
【问题描述】:

我正在尝试制作读取图像的机器学习模型。但在第一个 epoch 结束时出现错误。

tensorflow.python.framework.errors_impl.InvalidArgumentError:reshape 的输入是一个具有 147456 个值的张量,但请求的形状需要 12544 的倍数 有什么想法吗?

validation_generator = ImageDataGenerator(rescale=1./255)

train_data_gen = train_generator.flow_from_dataframe(
    dataframe=df,
    #directory="CatDog",   
    x_col="images",
    y_col="label",
    class_mode="binary",
    batch_size=64,
    target_size=(128,128))

validation_data_gen = validation_generator.flow_from_dataframe(
    dataframe=df,
    #directory='',
    x_col="images",
    y_col="label",
    class_mode="binary",
    batch_size=64,
    target_size=(64,64))

from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten

model = Sequential([
    Conv2D(16, (3,3), activation='relu', input_shape=(128,128,3)),
    MaxPool2D((2,2)),
    Conv2D(32, (3,3), activation='relu'),
    MaxPool2D((2,2)),
    Conv2D(64, (3,3), activation='relu'),
    MaxPool2D((2,2)),
    Flatten(),
    Dense(512, activation='relu'),
    Dense(1, activation='sigmoid')
])

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

model.summary()

history = model.fit(train_data_gen, epochs=2, validation_data=validation_data_gen)

【问题讨论】:

  • 欢迎来到Stack Overflow.!如果不查看产生问题的数据和您编写的代码,就很难回答您的问题。请阅读如何提出一个好问题并尝试发布Minimal Reproducible Example,以便我们更好地帮助您。

标签: python tensorflow machine-learning keras


【解决方案1】:

我不确定是否有您的完整代码。 已经有些问题了。

  1. line1:rescale=1./255 rescale=1./255 将使您的图像从“0~255 8bit int image”变为“0~1 float image”。所以请确保您的训练数据、验证数据和测试数据的格式相同。也就是说,您可能还想重新调整 train_generator。
  2. line19:target_size=(64,64) 使用相同的target_size 可能会更好。如果图像的原始尺寸足够大,请将target_size 设置为不小于模型的input_shape,以避免多次调整图像大小。它可能会丢失您的图像的一些信息。
  3. line33:Dense(1, activation='sigmoid') 最后一个Dense layer 通常是您的分类层。设置Dense(1, ...)意味着你的标签数量只有1个。如果你想将图像分类为猫或狗,你可以设置Dense(2, ...)activation='sigmoid' 会给你一个模型认为图像匹配标签的百分比。 您可能想使用activation='softmax' 为您提供分类结果。

基本上,我猜,错误是由错误的 Dense(unit, ...) 引起的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2020-03-15
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多