karas 实现lstm 文本分类

该博客演示了如何使用Keras库中的LSTM层处理IMDB数据集,进行文本分类任务。首先,从Keras加载预处理的数据,然后通过pad_sequences调整序列长度。接着,构建了一个包含嵌入层和LSTM层的Sequential模型,并用二元交叉熵作为损失函数,Adam优化器进行训练。模型在15个周期内训练并验证,最后评估了测试集上的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# In[4]:
#网址来源
#https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py
from __future__ import print_function

from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb
import numpy as np

max_features = 20000
maxlen = 80  # cut texts after this number of words (among top max_features most common words)
batch_size = 32

print('Loading data...')
#(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
#np.savetxt("x_train.txt", x_train)
#np.savetxt("x_test.txt", x_test)
#np.savetxt(" y_train.txt", y_train)
#np.savetxt("y_test.txt", y_test)

# In[2]:


x_train = np.loadtxt("/mfsdata/pachong/RNN/x_train.txt")
y_train=np.loadtxt("/mfsdata/pachong/RNN/ y_train.txt")
x_test = np.loadtxt("/mfsdata/pachong/RNN/x_test.txt")
y_test = np.loadtxt("/mfsdata/pachong/RNN/y_test.txt")


# In[5]:


print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')


# In[6]:


print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)


# In[10]:




print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128))
model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))


model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])



print('Train...')
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=15,
          validation_data=(x_test, y_test))


score, acc = model.evaluate(x_test, y_test,
                            batch_size=batch_size)

print('Test score:', score)
print('Test accuracy:', acc)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值