【问题标题】:How to use tensorflow hub layer embedding in convolutional layer for text?如何在文本的卷积层中使用 tensorflow hub 层嵌入?
【发布时间】:2021-07-08 00:21:25
【问题描述】:

我是 TensorFlow 集线器的新手,我正在尝试在我的 Conv1D 网络中使用集线器嵌入层来进行文本分类。

在顺序模型中使用集线器嵌入层没有任何问题:

hub_layer = hub.KerasLayer("https://tfhub.dev/google/nnlm-en-dim50/2", 
input_shape=[], dtype=tf.string, trainable=False)

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(128))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dense(5))
model.add(tf.keras.layers.Activation('softmax'))

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.summary()

但是,我无法在 Conv1D 模型中使用:

第一个模型:

int_sequences_input = Input(shape=(max_length,))
embedded_sequences = hub_layer(int_sequences_input)
x = layers.Conv1D(128, 5, activation="relu")(embedded_sequences)
x = layers.MaxPooling1D(5)(x)
x = layers.Conv1D(128, 5, activation="relu")(x)
x = layers.GlobalMaxPooling1D()(x)
x = layers.Dense(128, activation="relu")(x)
x = layers.Dropout(0.5)(x)
preds = layers.Dense(len(class_names), activation="softmax")(x)
model = keras.Model(int_sequences_input, preds)
model.summary()

或:

第二个模型:

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Conv1D(128, 7, activation='relu'))
model.add(tf.keras.layers.GlobalMaxPooling1D())
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.summary()

当我收到价值错误时:

ValueError: Input 0 of layer conv1d_11 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 50]

我想知道有没有办法解决这个问题? 我查看了this 或this,但没有一个能解决我的问题。

【问题讨论】:

    标签: python tensorflow keras tensorflow-hub


    【解决方案1】:

    生成的嵌入维度为:(num_examples, embedding_dimension),它与 1D 卷积不兼容,因为它需要 3D 输入。

    在hub层之后尝试reshape,像这样:

    model.add(hub_layer)
    model.add(tf.keras.layers.Reshape((1,50)))
    model.add(tf.keras.layers.Conv1D(16, 3, activation='relu', padding = 'same'))
    ...
    

    【讨论】:

    • 感谢 cmets。有没有机会我们可以使用int_sequences_input ..... 应用到上面的第一个 Conv1D 模型?
    • 你需要先应用嵌入,否则它没有现在那么有意义。
    • 你的意思是先hub layer 然后int_sequences_input。你能提供一个代码示例吗?谢谢
    • 我的意思是嵌入层应该是你的第一层,毕竟从卷积开始然后继续嵌入是没有意义的。如果我误解了你,请纠正我。
    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 2021-04-09
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多