[英]Wrap tensorflow function in keras layer
i'm trying to use the tensorflow unique function ( https://www.tensorflow.org/api_docs/python/tf/unique ) in a keras lambda layer. 我正在尝试在keras lambda层中使用tensorflow唯一函数( https://www.tensorflow.org/api_docs/python/tf/unique )。 Code below:
代码如下:
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)
when I now use **model.compile(optimizer='Adam', loss='mean_squared_error')**
I get the error: 当我现在使用
**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)'
ValueError:张量转换请求dtype int32 for Tensor with dtype float32:'Tensor(“lambda_9_sample_weights_1:0”,shape =(?,),dtype = float32)'
Does anybody know whats the error here or a different way of using the tensorflow function? 有谁知道这里的错误或使用张量流函数的不同方式?
A keras model expects a float32
as output, but the indices
returned from tf.unique
is a int32
. keras模型期望将
float32
作为输出,但是从tf.unique
返回的indices
是int32
。 A casting fixes your problem. 一个演员可以解决您的问题。
Another issue is that unique expects a flatten array. 另一个问题是,unique需要一个扁平阵列。
reshape
fixes this one. 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.