在 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/