[英]Wrap tensorflow function in keras layer
我正在嘗試在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:張量轉換請求dtype int32 for Tensor with dtype float32:'Tensor(“lambda_9_sample_weights_1:0”,shape =(?,),dtype = float32)'
有誰知道這里的錯誤或使用張量流函數的不同方式?
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.