python - Keras 简单数学运算模型失败并显示 "Output tensors to a Model must be Keras tensors"

标签 python tensorflow keras backend

我想定义一个使用基本数学运算的简单模型。我尝试使用多种方法来实现它,但最明显的方法失败了,我想了解原因。

让我们看一下代码:

import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
import numpy as np

x = Input(shape=(3,))
y = Lambda(lambda x: x ** 2)(x)
print y
# Tensor("lambda_1/pow:0", shape=(?, 3), dtype=float32)
model = Model(inputs=x, outputs=y)
# Works!

y = x ** 2
print y
# Tensor("pow:0", shape=(?, 3), dtype=float32)
model = Model(inputs=x, outputs=y)
# Fails: TypeError: Output tensors to a Model must be Keras tensors.

y = K.pow(x, 2)
print y
# Tensor("Pow:0", shape=(?, 3), dtype=float32)
model = Model(inputs=x, outputs=y)
# Fails: TypeError: Output tensors to a Model must be Keras tensors. 

如您所见,所有模型的 y 输出几乎相同,但直观的输出由于某种原因失败了。

最佳答案

收到回复:https://github.com/fchollet/keras/issues/6443#issuecomment-298259821

Here both x and y should be the outputs of Keras layers.

x 是输入层的输出,在上面的例子中,y 是 Lambda 层的输出。也可以编写自定义图层:https://keras.io/layers/writing-your-own-keras-layers/

关于python - Keras 简单数学运算模型失败并显示 "Output tensors to a Model must be Keras tensors",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538304/

相关文章:

python - TensorFlow - 从模板中创建张量

python - 如何创建一个包含最后一个元素的子列表,但对所有其他相同大小的子列表使用通用公式?

python - 如何在 Keras 中创建自定义回调?

Tensorflow - 任何输入都会给我相同的输出

tensorflow - tf keras SparseCategoricalCrossentropy 和 sparse_categorical_accuracy 在训练期间报告错误值

python - 如何根据keras中的条件替换张量的某些部分?

python - 带有 pandas 数据框的矢量化半正矢公式

python - 重新启动自更新 python 脚本

tensorflow - AttributeError : module 'tensorflow_core._api.v2.config' has no attribute 'list_physical_devices'

python - 获取值错误 : "Can only tuple-index with a MultiIndex "