在keras层中包装张量流功能

Nic*_*wes 2 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)
Run Code Online (Sandbox Code Playgroud)

现在使用时**model.compile(optimizer='Adam', loss='mean_squared_error')** 出现错误:

ValueError:张量转换请求的dtype float32的张量为dtype int32:'Tensor(“ lambda_9_sample_weights_1:0”,shape =(?,),dtype = float32)'

有人知道这里的错误是什么或使用张量流函数的其他方式吗?

lda*_*vid 7

一个keras模型需要一个float32作为输出,但是indices从返回的tf.unique是一个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')
Run Code Online (Sandbox Code Playgroud)