Keras - 文本分类 - LSTM - 如何输入文本?

时间:2016-04-18 17:40:36

标签: theano keras lstm lasagne

我试图了解如何使用LSTM对我拥有的某个数据集进行分类。

我研究并发现了这个keras和imdb的例子: https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py

但是,我很困惑必须如何处理数据集才能输入。

我知道keras有预处理文本方法,但我不确定使用哪种方法。

x包含带有文本的n行,y通过快乐/悲伤对文本进行分类。基本上,1.0意味着100%快乐,0.0意味着完全悲伤。数字可能会有所不同,例如0.25~~等等。

所以我的问题是,我如何正确输入x和y?我必须用文字袋吗? 任何提示表示赞赏!

我在下面对此进行了编码,但我仍然遇到同样的错误:

#('Bad input argument to theano function with name ... at index 1(0-based)', 
'could not convert string to float: negative')
import keras.preprocessing.text
import numpy as np

np.random.seed(1337)  # for reproducibility

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM

print('Loading data...')
import pandas

thedata = pandas.read_csv("dataset/text.csv", sep=', ', delimiter=',', header='infer', names=None)

x = thedata['text']
y = thedata['sentiment']

x = x.iloc[:].values
y = y.iloc[:].values

###################################
tk = keras.preprocessing.text.Tokenizer(nb_words=2000, filters=keras.preprocessing.text.base_filter(), lower=True, split=" ")
tk.fit_on_texts(x)

x = tk.texts_to_sequences(x)


###################################
max_len = 80
print "max_len ", max_len
print('Pad sequences (samples x time)')

x = sequence.pad_sequences(x, maxlen=max_len)

#########################
max_features = 20000
model = Sequential()
print('Build model...')

model = Sequential()
model.add(Embedding(max_features, 128, input_length=max_len, dropout=0.2))
model.add(LSTM(128, dropout_W=0.2, dropout_U=0.2))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='rmsprop')

model.fit(x, y=y, batch_size=200, nb_epoch=1, verbose=1, validation_split=0.2, show_accuracy=True, shuffle=True)

# at index 1(0-based)', 'could not convert string to float: negative')

1 个答案:

答案 0 :(得分:3)

查看您使用CSV解析器阅读文本的方式。如果您想在代码中编写解析器,请确保字段采用Text,Sentiment格式。

相关问题