创建输出两个 Y 变量的 LSTM 神经网络

Creating a LSTM Neural Network outputting two Y variables

我有一个基于推文的分类任务。推文是我唯一的输入 (X) 变量。然而,我有两个目标 (y) 变量,一个目标变量应该输出 1 或 0 表示正或负,而另一个目标变量应该输出 1 或 0 表示政治或非政治。

我创建了一个 运行 的 LSTM 神经网络,但我似乎无法让它输出两个目标变量。有人可以指点一下吗?

我的输入形状是:

X_train        y_train
(15203, 250) (15203, 2)
X_val         y_val
(3801, 250) (3801, 2)

我的模型是:

    model = Sequential()
    model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))
    model.add(SpatialDropout1D(0.2))
    model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
    
    # For two label classification
    model.add(Dense(2, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

我注意到我后来 运行 这段关于看不见的数据的代码

我没有得到两个目标变量
    new_text = ["Tony Gonzales (@TonyGonzales4TX) will be a GREAT Congressman for Texas! A Navy veteran, he is Strong on the Economy, Life and the Second Amendment. We need him to defeat the Radical Left in November. Tony has my Complete and Total Endorsement! #TX23"]
    seq = tokenizer.texts_to_sequences(new_text)
    padded = pad_sequences(seq, maxlen = 250)
    pred = model.predict(padded)
    labels = [0,1]
    print(pred, labels[np.argmax(pred)])

在此测试和所有其他测试中,我注意到我的预测仅返回二进制分类。例如在上面我得到了 0.13 0.87(这些数字加起来是 100,所以并列在一起)

然而,在上述情况下,一条积极的政治推文,我预计会有大约 0.88 0.91 的双重结果

任何关于如何获得两个输出 y 变量的帮助将不胜感激。

您可以在输出层中添加 4 个节点,代表(负面、正面、政治、非政治) 并以这种方式映射你的训练 或者你可以试试这个:

x = your input numpy array
y1 = your sentiment one hot encoded output numpy array
y2 = your political one hot encoded output numpy array
# x, y1, y2 should have same length or shape[0]
data = tensorflow.data.Dataset.from_tensor_slices((x, [y1, y2]))
data = data.shuffle(len(x))

input =  Input(shape=(X.shape[1], ))
x = Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1])(input)
x = SpatialDropout1D(0.2)(x)
x = LSTM(100, dropout=0.2, recurrent_dropout=0.2)(x)
out1 = Dense(2, activation='softmax', name='sentiment')(x)
out2 = Dense(2, activation='softmax', name='political')(x)
model = Model(inputs = input, outputs=[out1, out2])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(data, other arguments....]  #supposing your output is one hot encoded

看看行不行。