python - 使用 tf.keras.layers.Reshape 时出现类型错误

标签 python tensorflow machine-learning keras

在 Keras 中构建模型时,遇到此错误:

TypeError: Expected int32, got 8.0 of type 'float' instead.

错误发生在最初构建模型时(而不是执行期间),更具体地说是在此代码段的最后一行:

    d_dense1 = Dense(
        ((IMAGE_SIZE/4)**2)*(n if vanilla_architecture else 3*n),
        input_shape = (h,),
        activation = "relu",
        name = name_prefix + "dense1"
    )(d_in)
    d_reshape1 = tf.keras.layers.Reshape(
        (IMAGE_SIZE/4, IMAGE_SIZE/4, (n if vanilla_architecture else 3*n)),
        name = name_prefix + "reshape1"
    )(d_dense1)

Side note: I am using tf.keras.layers.Dense, IMAGE_SIZE is an integer, vanilla_architecture is a boolean, and n is an integer

显然,密集层将传递 float 张量,因为这是一个机器学习操作。问题似乎是 Reshape 需要整数张量。我阅读了文档,但那里没有任何信息。

以下是我尝试过的一些方法:

  • 使用 tf.reshape
    • 同样的问题
  • 使用 numpy reshape
    • 仅仅简单是行不通的
  • 阅读示例代码,例如 this 的 54
    • 他们似乎在做与我相同的事情,但他们的作品有效

奇怪的是,它在使用急切执行时工作得很好。但我不想启用急切执行,因为我想使用张量板。

最佳答案

解决方案是在这一行中使用整数除法:

(IMAGE_SIZE//4, IMAGE_SIZE//4, (n if vanilla_architecture else 3*n)),

类型错误不是由于张量引起的,而是 IMAGE_SIZE/4 返回了一个 float

关于python - 使用 tf.keras.layers.Reshape 时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323297/

相关文章:

python - 使用 TF-IDF 方案从给定句子中提取关键短语的任何有效解决方法?

python - 使用 scipy.signal 库中的 savgol_filter 平滑 Python 上的在线数据

python - CNN : why it is making no difference whether i measure accuracy by logits or softmax layer?

Tensorflow first epoch 极慢(可能与 pool_allocator 有关)

tensorflow - 在 Keras 中训练目标检测模型时出现张量形状不兼容的问题

python - 无法让 Elasticsearch 与 Django 一起工作

python - 如何在 Python 中将二进制数组写为图像?

python - keras 和 tf.keras 中的 ResNet 模型对同一图像给出不同的输出

python - tensorflow 非线性分类

matlab - 将预计算的 chi2 内核与 libsvm (matlab) 一起使用时的错误结果