【问题标题】:How to use Keras Embedding layer when there are more than 1 text features当有超过1个文本特征时如何使用Keras Embedding层
【发布时间】:2018-09-11 08:19:48
【问题描述】:

我了解如何使用 Keras 嵌入层,以防 IMDB 评论分类中存在单个文本功能。但是,当我遇到分类问题时,我很困惑如何使用嵌入层,其中有多个文本特征。例如,我有一个包含 2 个文本特征诊断文本和请求程序的数据集,标签是二进制类(1 表示批准,0 表示未批准)。在下面的示例中,与 IMDB 数据集不同,x_train 有 2 列诊断和过程。我是否需要创建 2 个嵌入层,一个用于诊断和程序?如果是这样,需要哪些代码更改?

x_train = preprocessing.sequences.pad_sequences(x_train, maxlen=20)
x_test = preprocessing.sequences.pad_sequences(x_test, maxlen=20)
model = Sequential()
model.add(Embedding(10000,8,input_length=20)
model.add(Flatten())
model.add(Dense(1, activation='sigmoid')
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)

【问题讨论】:

    标签: keras word2vec word-embedding


    【解决方案1】:

    您有一些选择,您可以将这两个功能合并为一个 并为它们创建一个嵌入。这是逻辑

    all_features = np.hstack(X['diag'] + X['proc'])
    X = pad_sequence(all_features, max_len)
    # build model as usual, as you can see on a single embedding layer is
    # needed.
    

    或者您可以使用Functional api 并构建多输入模型

    diag_inp = Input()
    diag_emb = Embedding(512)(diag_input)
    proc_inp = Input()
    proc_emb = Embedding(512)(proc_input)
    
    # concatenate them to makes a single vector per sample
    merged = Concatenate()[diag_emb, proc_emb]
    out = Dense(2,  activation='sigmoid')(merged)
    model = Model(inputs=[diag_inp, proc_inp], outputs=[out])
    

    也就是说,您可以学习连接的嵌入,或者您可以学习 多个嵌入并在训练时将它们连接起来。

    【讨论】:

    • 合并在哪里使用?
    • @timekeeper 在连接步骤中
    • 在 concat 步骤中,创建了合并。不应该是out = Dense(2, activation='sigmoid')(merged) 之类的吗?
    • @timekeeper 是的!固定!
    猜你喜欢
    • 2021-06-17
    • 2019-10-26
    • 1970-01-01
    • 2018-05-09
    • 2017-07-28
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多