【问题标题】:ValueError: The last dimension of the inputs to a Dense layer should be defined. Found NoneValueError:应定义密集层输入的最后一个维度。没有找到
【发布时间】:2022-01-01 15:54:17
【问题描述】:

我正在使用 Tensorflow 2.7.0 及其新的TextVectorization 层。然而,在这个简单的例子中,有些事情并不完全正确:

import tensorflow as tf
import numpy as np

X = np.array(['this is a test', 'a nice test', 'best test this is'])

vectorize_layer = tf.keras.layers.TextVectorization()
vectorize_layer.adapt(X)
emb_layer = tf.keras.layers.Embedding(input_dim=vectorize_layer.vocabulary_size()+1, output_dim=2, input_length=4)
flatten_layer = tf.keras.layers.Flatten()
dense_layer = tf.keras.layers.Dense(1)


model = tf.keras.models.Sequential()
model.add(vectorize_layer)
model.add(emb_layer)
model.add(flatten_layer)
#model.add(dense_layer)

model(X)

到目前为止,这有效。我用词制作整数,嵌入它们,压平它们。但是如果我想在展平后添加一个Dense 层(即取消注释一行),事情就会中断,我会从问题标题中收到错误消息。我什至使用了Embedding 层的input_length 参数,因为文档说我应该在使用embedding->flatten->dense 时指定它。但它只是不起作用。

你知道我如何使用Flatten 而不是GlobalAveragePooling1D 之类的东西让它工作吗?

非常感谢!

【问题讨论】:

    标签: python tensorflow keras nlp embedding


    【解决方案1】:

    您需要定义序列的最大长度。

    vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int',
                                                        output_sequence_length=10)
    

    如果您选中model.summary(),则TextVectorization 的输出形状将为(None, None)

    第一个None 表示模型可以接受任何批量大小,第二个表示传递给TextVectorization 的任何句子都不会被截断或填充。所以输出的句子可以有可变长度。

    例子:

    import tensorflow as tf
    import numpy as np
    
    X = np.array(['this is a test', 'a nice test', 'best test this is'])
    
    vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int')
    vectorize_layer.adapt(X)
    
    model = tf.keras.models.Sequential()
    model.add(vectorize_layer)
    
    model(np.array(['this is a test']))
    >> <tf.Tensor: shape=(1, 4), dtype=int64, numpy=array([[3, 4, 5, 2]])>
    
    model(np.array(['this is a longer test sentence']))
    >> <tf.Tensor: shape=(1, 6), dtype=int64, numpy=array([[3, 4, 5, 1, 2, 1]])>
    

    重新定义它:

    vectorize_layer = tf.keras.layers.TextVectorization(output_mode = 'int',
                                                        output_sequence_length = 5)
    
    model(np.array(['this is a longer test sentence']))
    >> <tf.Tensor: shape=(1, 5), dtype=int64, numpy=array([[3, 4, 5, 1, 2]])>
    
    model(np.array(['this is']))
    >> <tf.Tensor: shape=(1, 5), dtype=int64, numpy=array([[3, 4, 0, 0, 0]])>
    

    output_sequence_length 定义为一个数字将确保输出的长度是一个固定数字。

    【讨论】:

    • 嗨!非常感谢,这成功了。此外,只需检查模型摘要就可以了,这可能会在其他情况下为我省去一些麻烦。祝你新年快乐! :)
    • 是的,模型摘要会让您洞察可能出现的问题。新年快乐! :)
    猜你喜欢
    • 2018-10-09
    • 2019-11-16
    • 1970-01-01
    • 2019-04-11
    • 2021-05-07
    • 2020-05-23
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多