如何在Keras中使用自定义功能进行文本分类

时间:2018-07-23 12:39:55

标签: python keras classification data-analysis text-classification

我正在使用Keras在Python中为文本分类程序工作。现在,我尝试使用一词袋仅使用数据集的词来建立模型。现在,我将在分类器中使用其他自定义功能(例如极性),但是我不知道如何在代码中添加这些功能。我的数据集就像:

 Text                    | Polarity | Number of words | Classification 

 Hello my name is John   |    0,05  |        5        |        0
 How old are you?        |    0,00  |        4        |        1
 I'm very hungry         |   -0,05  |        4        |        0

中间两个列是我想要添加到分类器中的自定义功能,但我不知道如何。

train_x = tokenizer.sequences_to_matrix(allWordIndices, mode='binary')
train_x2 = train_x

train_x = train_x[1000:]
test_x = train_x2[:1000]
train_y = keras.utils.to_categorical(train_y, 2)
train_y2 = train_y
train_y = train_y[1000:]
test_y = train_y2[:1000]


from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation

model = Sequential()
model.add(Dense(30, input_shape=(max_words,), activation='relu'))
model.add(Dropout(0.45)) 
model.add(Dense(100, activation='softplus'))
model.add(Dropout(0.45))
model.add(Dense(2, activation='softmax'))

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

history = model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1,validation_split=0.1,shuffle=True)

score = model.evaluate(test_x,test_y, batch_size=128)

在此示例中,我仅使用第一列内容的单词袋功能,我想添加其他两列,例如功能(极性,单词数)。有人知道如何添加这些?预先感谢。

1 个答案:

答案 0 :(得分:0)

对于袋字,您可以将数字特征连接到BoW向量的顶部。因此,您可以只使用numpy甚至更简单的熊猫。然后,您有一个尺寸为max_words + custom_numerical_features的向量。

无论如何,我做过类似的事情,并且在BoW和嵌入等几种方法上做了很多工作。

最好在您的网络中分割文本特征和数字特征。为此,您可以使用多个输入模型。我刚刚写了一篇关于它的博客,您可以看看here。有嵌入的内容,但通常它也适用于BoW。

相关问题