python - 在 keras 层中包装 tensorflow 函数

标签 python python-3.x keras

我正在尝试在 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/

相关文章:

Linux 中的 Python : kill processes and sub-processes using the shell

python - 使用ptrepack回收hdf5文件中删除的节点

ios - 为什么我们总是在tf.compat.v1.random.set_random_seed(1234)中使用seed =1234。有什么具体原因吗?

tensorflow - 分析 keras 模型时出错

tensorflow - Keras/Tensorflow 中一组矩阵之间的成对距离

python - 在 BST 中查找小于给定元素的元素数

python - 合并多个字典,根据不同的值创建数组

python - 在 Windows 中设置项目的相对 pythonpath (Visual Studio Code)

Python RegEx - Negative Lookahead 在 a 之后不起作用?量词

sql - 将大量数据集从 SQL 服务器导入 HDF5