【问题标题】:TensorFlow2: ResNet50 - ValueErrorTensorFlow2:ResNet50 - ValueError
【发布时间】:2021-05-12 17:29:10
【问题描述】:

我正在尝试在具有 (32、32、3) 图像的 CIFAR-10 数据集上使用 TensorFlow2 和 Keras 中的 ResNet-50 进行迁移学习。

默认 ResNet-50 的第一个 conv 层使用 (7, 7) 的过滤器大小,stride = 2,由此产生的 CIFAR-10 在空间上减少了太多,这是要避免的。作为“黑客”,尝试将图像从 (32, 32) 放大到 (224, 224)。代码是:

import tensorflow.keras as K

# Define KerasTensor as input-
input_t = K.Input(shape = (32, 32, 3))

res_model = K.applications.ResNet50(
    include_top = False,
    weights = "imagenet",
    input_tensor = input_t
)

# Since CIFAR-10 dataset is small as compared to ImageNet, the images are upscaled to (224, 224)-
to_res = (224, 224)

model = K.models.Sequential()
model.add(K.layers.Lambda(lambda image: tf.image.resize(image, to_res))) 
model.add(res_model)
model.add(K.layers.Flatten())
model.add(K.layers.BatchNormalization())
model.add(K.layers.Dense(units = 10, activation = 'softmax'))

# Choose an optimizer and loss function for training-
loss_fn = tf.keras.losses.CategoricalCrossentropy()
optimizer = tf.keras.optimizers.SGD(learning_rate = 0.1, momentum = 0.9)

model.compile(
    # loss = 'categorical_crossentropy',
    loss = loss_fn,
    # optimizer = K.optimizers.RMSprop(lr=2e-5),
    optimizer = optimizer,
    metrics=['accuracy']
)

history = model.fit(
    x = X_train, y = y_train,
    batch_size = batch_size, epochs = 10,
    validation_data = (X_test, y_test),
    # callbacks=[check_point]
    )

我得到错误:

Epoch 1/10 警告:tensorflow:模型是用形状构建的(无, 32, 32, 3) 用于输入 KerasTensor(type_spec=TensorSpec(shape=(None, 32, 32, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"),但它是在 形状不兼容的输入(无、224、224、3)。


ValueError Traceback(最近调用 最后)

在 () 2 x = X_train,y = y_train, 3 batch_size = batch_size, epochs = 10, ----> 4 验证数据 = (X_test, y_test), 5 # 回调=[check_point] 6)

9 帧

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py 在包装器中(*args,**kwargs) 975 例外为 e:# pylint:disable=broad-except 第976章 --> 977 引发 e.ag_error_metadata.to_exception(e) 978 其他: 第979章

ValueError:在用户代码中:

ValueError:输入 0 与层 resnet50 不兼容:预期 shape=(None, 32, 32, 3), 找到 shape=(None, 224, 224, 3)

【问题讨论】:

  • 您将 Resnet 设置为拍摄 32x32 图像,而不是 224x224 图像。

标签: python-3.x keras conv-neural-network tensorflow2.0 resnet


【解决方案1】:

模型的输入还是(32,32,3)

input_t = K.Input(shape = (32, 32, 3))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多