我正在尝试在 keras lambda 层中使用 tensorflow 独特函数 ( https://www.tensorflow.org/api_docs/python/tf/unique )。 代码如下:
def unique_idx(x):
output = tf.unique(x)
return output[1]
then
inp1 = Input(batch_shape(None, 1))
idx = Lambda(unique_idx)(inp1)
model = Model(inputs=inp1, outputs=idx)
当我现在使用 **model.compile(optimizer='Adam', loss='mean_squared_error')**
我收到错误:
ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("lambda_9_sample_weights_1:0", shape=(?,), dtype=float32)'
有人知道这里的错误是什么或使用 tensorflow 函数的不同方式吗?
最佳答案
keras 模型需要一个 float32
作为输出,但是 tf.unique
返回的 indices
是一个 int32
。类型转换解决你的问题。
另一个问题是 unique 需要展平数组。 reshape
修复了这个问题。
import tensorflow as tf
from keras import Input
from keras.layers import Lambda
from keras.engine import Model
def unique_idx(x):
x = tf.reshape(x, [-1])
u, indices = tf.unique(x)
return tf.cast(indices, tf.float32)
x = Input(shape=(1,))
y = Lambda(unique_idx)(x)
model = Model(inputs=x, outputs=y)
model.compile(optimizer='adam', loss='mse')
关于python - 在 keras 层中包装 tensorflow 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433065/