首页 文章

如何构建LSTM神经网络进行分类

提问于
浏览
4

我的数据在两个人之间有各种对话 . 每个句子都有某种类型的分类 . 我试图使用NLP网来对话的每个句子进行分类 . 我尝试了一个卷积网并得到了不错的结果(不是突破性的) . 我认为,由于这是一次来回的对话,而LSTM网可能会产生更好的结果,因为之前所说的可能会对后面的内容产生很大的影响 .

Type of RNN nets

如果我遵循上面的结构,我会假设我做了多对多 . 我的数据看起来像 .

X_train = [[sentence 1],  
           [sentence 2],
           [sentence 3]]
Y_train = [[0],
           [1],
           [0]]

已使用word2vec处理数据 . 然后我按如下方式设计我的网络..

model = Sequential()      
model.add(Embedding(len(vocabulary),embedding_dim,
          input_length=X_train.shape[1]))
model.add(LSTM(88))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer='rmsprop',loss='binary_crossentropy',
              metrics['accuracy'])
model.fit(X_train,Y_train,verbose=2,nb_epoch=3,batch_size=15)

我假设这个设置将一次输入一批句子 . 但是,如果在model.fit中,shuffle不等于false接收洗牌批次,那么为什么LSTM网在这种情况下甚至有用?从对该主题的研究来看,为了实现多对多结构,还需要改变LSTM层

model.add(LSTM(88,return_sequence=True))

输出层需要......

model.add(TimeDistributed(Dense(1,activation='sigmoid')))

切换到此结构时,输入大小出错 . 我不确定如何重新格式化数据以满足此要求,以及如何编辑嵌入层以接收新数据格式 .

任何投入将不胜感激 . 或者如果您对更好的方法有任何建议,我非常乐意听到它们!

1 回答

  • 4

    你的第一次尝试很好 . 改组发生在句子之间,只是在他们之间改变训练样本,这样他们就不会总是以相同的顺序进入 . 句子里面的单词没有改组 .

    或者我可能没有正确理解这个问题?

    EDIT

    在更好地理解了这个问题之后,这是我的主张 .

    Data preparation : 您将语料库切成_2546663个句子(它们可以重叠) . 那么你应该有一个像 (number_blocks_of_sentences, n, number_of_words_per_sentence) 这样的形状,所以基本上是一个包含 n 句子块的2D数组列表 . n 不应该在训练时处理序列中的大量元素(消失梯度) . 你的目标应该是一个形状的数组 (number_blocks_of_sentences, n, 1) 所以也是一个二维数组的列表,其中包含你的句子块中每个句子的类 .

    Model :

    n_sentences = X_train.shape[1]  # number of sentences in a sample (n)
    n_words = X_train.shape[2]      # number of words in a sentence
    
    model = Sequential()
    # Reshape the input because Embedding only accepts shape (batch_size, input_length) so we just transform list of sentences in huge list of words
    model.add(Reshape((n_sentences * n_words,),input_shape = (n_sentences, n_words)))
    # Embedding layer - output shape will be (batch_size, n_sentences * n_words, embedding_dim) so each sample in the batch is a big 2D array of words embedded 
    model.add(Embedding(len(vocabaulary), embedding_dim, input_length = n_sentences * n_words ))
    # Recreate the sentence shaped array
    model.add(Reshape((n_sentences, n_words, embedding_dim))) 
    # Encode each sentence - output shape is (batch_size, n_sentences, 88)
    model.add(TimeDistributed(LSTM(88)))
    # Go over lines and output hidden layer which contains info about previous sentences - output shape is (batch_size, n_sentences, hidden_dim)
    model.add(LSTM(hidden_dim, return_sequence=True))
    # Predict output binary class - output shape is (batch_size, n_sentences, 1)
    model.add(TimeDistributed(Dense(1,activation='sigmoid')))
    ...
    

    这应该是一个好的开始 .

    我希望这有帮助

相关问题