简体   繁体   English

使用dtype float32(lambda输入)的Tensor的Tensor转换请求dtype字符串

[英]Tensor conversion requested dtype string for Tensor with dtype float32 (lambda input)

I am using Keras' Lambda layer with TensorFlow Hub to download word embeddings from a pre-built embedder. 我正在使用带有TensorFlow Hub的Keras的Lambda层从预建的嵌入器中下载单词嵌入。

import tensorflow_hub as hub
from tensorflow.dtypes import as_string
def embedding(x):
    print(x.shape)
    module = hub.Module("https://tfhub.dev/google/nnlm-en-dim128/1")
    return module(x)
answers_network_rnn = Sequential()
print(trainingData["question"].shape)
answers_network_rnn.add(Lambda(embedding,output_shape=(128,)))
answers_network_rnn.add(Dense(16))
answers_network_rnn.add(Dense(Y_2_train_num.shape[1]))
answers_network_rnn.summary()
answers_network_rnn.compile("adam","categorical_crossentropy",metrics=['accuracy',f1]) answers_network_rnn_checkpoint = ModelCheckpoint('answers_network-rnn-best.h5', verbose=1, monitor='val_f1',save_best_only=True, mode='auto') answers_network_rnn.fit(x=X_2_train_text.values,y=Y_2_train_num) 

I expect Keras to have built a model with a list of 128 word embeddings for each word in my inputs. 我希望Keras可以建立一个包含输入中每个单词的128个单词嵌入列表的模型。 In reality, the Lambda layer causes the following error when it runs on the "embedding" function. 实际上,Lambda层在“嵌入”功能上运行时会导致以下错误。

"ValueError: Tensor conversion requested dtype string for Tensor with dtype float32: 'Tensor("sequential_5_input:0", shape=(?, 2), dtype=float32)'" “ ValueError:Tensor转换请求具有dtype float32的Tensor的dtype字符串:'Tensor(“ sequential_5_input:0”,shape =(?, 2),dtype = float32)'

According to user nuric on a GitHub issue ( https://github.com/keras-team/keras/issues/10021 ) this problem is caused by Keras attempting to infer the output shape. 根据GitHub问题( https://github.com/keras-team/keras/issues/10021 )上的用户nuric所说,此问题是由Keras尝试推断输出形状引起的。 As you can see, I have attempted to resolve this issue by specifying the desired output shape. 如您所见,我尝试通过指定所需的输出形状来解决此问题。

Here's the input and desired output for the neural network: 这是神经网络的输入和所需的输出:

Input 输入

[['to whom did the virgin mary allegedly appear in 1858 in lourdes france?'
  'architecturally, the school has a catholic character. atop the main building\'s gold dome is a golden statue of the virgin mary. immediately in front of the main building and facing it, is a copper statue of christ with arms upraised with the legend "venite ad me omnes". next to the main building is the basilica of the sacred heart. immediately behind the basilica is the grotto, a marian place of prayer and reflection. it is a replica of the grotto at lourdes, france where the virgin mary reputedly appeared to saint bernadette soubirous in 1858. at the end of the main drive (and in a direct line that connects through 3 statues and the gold dome), is a simple, modern stone statue of mary.']
 ['what is in front of the notre dame main building?'
  'architecturally, the school has a catholic character. atop the main building\'s gold dome is a golden statue of the virgin mary. immediately in front of the main building and facing it, is a copper statue of christ with arms upraised with the legend "venite ad me omnes". next to the main building is the basilica of the sacred heart. immediately behind the basilica is the grotto, a marian place of prayer and reflection. it is a replica of the grotto at lourdes, france where the virgin mary reputedly appeared to saint bernadette soubirous in 1858. at the end of the main drive (and in a direct line that connects through 3 statues and the gold dome), is a simple, modern stone statue of mary.']
 ['the basilica of the sacred heart at notre dame is beside to which structure?'
  'architecturally, the school has a catholic character. atop the main building\'s gold dome is a golden statue of the virgin mary. immediately in front of the main building and facing it, is a copper statue of christ with arms upraised with the legend "venite ad me omnes". next to the main building is the basilica of the sacred heart. immediately behind the basilica is the grotto, a marian place of prayer and reflection. it is a replica of the grotto at lourdes, france where the virgin mary reputedly appeared to saint bernadette soubirous in 1858. at the end of the main drive (and in a direct line that connects through 3 statues and the gold dome), is a simple, modern stone statue of mary.']

Desired output: 所需的输出:

[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [1. 0. 0. ... 0. 0. 0.]]

I just tried it out and it works for me when I remove "input_shape = [None],". 我只是尝试了一下,当我删除“ input_shape = [None]”时,它对我有用。 So this code should work: 所以这段代码应该可以工作:

import tensorflow_hub as hub
from tensorflow.dtypes import as_string
def embedding(x):
    print(x.shape)
    module = hub.Module("https://tfhub.dev/google/nnlm-en-dim128/1")
    return module(x)
answers_network_rnn = Sequential()
print(trainingData["question"].shape)
from keras.layers import InputLayer
answers_network_rnn.add(Lambda(embedding,output_shape=(128,)))
answers_network_rnn.add(Dense(16))
answers_network_rnn.add(Dense(Y_2_train_num.shape[1]))
answers_network_rnn.summary()

EDIT 编辑

This keras model should be equal to the SequentialModel (except the explicit input layer): 此keras模型应等于SequentialModel(显式输入层除外):

input_text = tf.keras.layers.Input(shape=(1,), dtype=tf.string)
embedding_layer = tf.keras.layers.Lambda(embedding,output_shape=(128,))(input_text)
dense = tf.keras.layers.Dense(16)(embedding_layer)
outputs = tf.keras.layers.Dense(Y_2_train_num.shape[1])(dense)

answers_network_rnn = tf.keras.Model(inputs=[input_text], outputs=outputs)
answers_network_rnn.compile(...)

Running this works for me ... 运行这个对我有用...

with tf.Session() as session:
  session.run([tf.global_variables_initializer(), tf.tables_initializer()])
  answers_network_rnn.fit(...)

... after changing this in the lambda function: ...在lambda函数中更改此设置后:

#return module(x)
return module(tf.squeeze(tf.cast(x, tf.string)),signature="default", as_dict=True)["default"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自己的数据集ValueError:使用dtype float32的Tensor的Tensor转换请求了dtype字符串 - Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32 ValueError:张量转换为具有 dtype float32 的张量请求 dtype float32_ref - ValueError: Tensor conversion requested dtype float32_ref for Tensor with dtype float32 Tensor转换请求dtype float32的dtype float64 - Tensor conversion requested dtype float64 for Tensor with dtype float32 ValueError: Tensor 转换请求 dtype int32 for Tensor with dtype float32 - LSTM Implementation(tensorflow 2.0.0) - ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32 - LSTM Implementation( tensorflow 2.0.0) 值错误:列名:<name> input_tensor dtype 必须是字符串或 integer。 数据类型:<dtype: 'float32'></dtype:></name> - ValueError: column_name: <Name> input_tensor dtype must be string or integer. dtype: <dtype: 'float32'> ValueError: column_name: input_tensor dtype 必须是字符串或 integer。 数据类型:<dtype: 'float32'></dtype:> - ValueError: column_name: input_tensor dtype must be string or integer. dtype: <dtype: 'float32'> Tensorflow 图像生成器通过 dtype=string 的张量而不是 dtype=float32 的张量来丢失 function - Tensorflow Image Generator passing Tensor with dtype=string instead of Tensor with dtype=float32 to loss function ValueError: Tensor(&quot;ExponentialDecay_4:0&quot;, shape=(), dtype=float32) - ValueError: Tensor("ExponentialDecay_4:0", shape=(), dtype=float32) Tensorflow 2.0 警告-dense_features 正在将输入张量从 dtype float64 转换为 float32 层的 dtype - Tensorflow 2.0 Warnings - dense_features is casting an input tensor from dtype float64 to the layer's dtype of float32 图断开连接:无法在“input_1”层获取张量 Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) 的值 - Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM