Keras学习(九)-IMDB情感分析(LSTM形式)

  • LSTM,是专门设计来解决RNN长期依赖的问题
    在这里插入图片描述
    在这里插入图片描述

1.数据准备

from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
import numpy as np
np.random.seed(10)

import re
re_tag = re.compile(r'<[^>]+>')

def rm_tags(text):
    return re_tag.sub('', text)

import os
def read_files(filetype):
    path = "data/aclImdb/"
    file_list=[]

    positive_path=path + filetype+"/pos/"
    for f in os.listdir(positive_path):
        file_list+=[positive_path+f]
    
    negative_path=path + filetype+"/neg/"
    for f in os.listdir(negative_path):
        file_list+=[negative_path+f]
        
    print('read',filetype, 'files:',len(file_list))
       
    all_labels = ([1] * 12500 + [0] * 12500) 
    
    all_texts  = []
    
    for fi in file_list:
        with open(fi,encoding='utf8') as file_input:
            all_texts += [rm_tags(" ".join(file_input.readlines()))]
            
    return all_labels,all_texts

token = Tokenizer(num_words=3800)
token.fit_on_texts(train_text)

x_train_seq = token.texts_to_sequences(train_text)
x_test_seq  = token.texts_to_sequences(test_text)

x_train = sequence.pad_sequences(x_train_seq, maxlen=380)
x_test  = sequence.pad_sequences(x_test_seq,  maxlen=380)

2.建立模型

from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation,Flatten
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM

model = Sequential()

model.add(Embedding(output_dim=32,
                    input_dim=3800, 
                    input_length=380))
model.add(Dropout(0.2))

model.add(LSTM(32))

model.add(Dense(units=256,
                activation='relu' ))
model.add(Dropout(0.2))

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

model.summary()

在这里插入图片描述

3.训练模型

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

train_history =model.fit(x_train, y_train,batch_size=100, 
                         epochs=10,verbose=1,
                         validation_split=0.2)

%pylab inline
import matplotlib.pyplot as plt
def show_train_history(train_history,train,validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train History')
    plt.ylabel(train)
    plt.xlabel('Epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()

show_train_history(train_history,'acc','val_acc')
show_train_history(train_history,'loss','val_loss')

4.模型准确率

scores = model.evaluate(x_test, y_test, verbose=1)
scores[1]

在这里插入图片描述

5.结果预测

  • 概率预测
probility=model.predict(x_test)

在这里插入图片描述

  • 预测结果
predict=model.predict_classes(x_test)

在这里插入图片描述

  • 查看预测结果
SentimentDict={1:'正面的',0:'负面的'}
def display_test_Sentiment(i):
    print(test_text[i])
    print('标签label:',SentimentDict[y_test[i]],'预测结果:',SentimentDict[predict_classes[i]])

display_test_Sentiment(2)

在这里插入图片描述

6.模型保存

model_json = model.to_json()
with open("SaveModel/Imdb_LSTM_model.json", "w") as json_file:
    json_file.write(model_json)

model.save_weights("SaveModel/Imdb_LSTM_model.h5")
print("Saved model to disk")
基于深度学习LSTM情感分析是一种常用的文本情感分析方法。LSTM(Long Short-Term Memory)是一种特殊的循环神经网络,它能够有效地处理序列数据,因此在文本处理中得到了广泛应用。下面是一个简单的LSTM情感分析模型的实现示例: ```python import numpy as np from keras.datasets import imdb from keras.models import Sequential from keras.layers import Dense, LSTM, Embedding from keras.preprocessing import sequence # 加载IMDB数据集 top_words = 5000 (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words) # 对数据进行预处理 max_review_length = 500 X_train = sequence.pad_sequences(X_train, maxlen=max_review_length) X_test = sequence.pad_sequences(X_test, maxlen=max_review_length) # 构建LSTM模型 embedding_vecor_length = 32 model = Sequential() model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length)) model.add(LSTM(100)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) # 训练模型 model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3, batch_size=64) # 评估模型 scores = model.evaluate(X_test, y_test, verbose=0) print("Accuracy: %.2f%%" % (scores[1]*100)) ``` 在上面的代码中,我们使用Keras框架构建了一个简单的LSTM模型,用于对IMDB电影评论进行情感分析。首先,我们加载了IMDB数据集,并对数据进行了预处理。然后,我们构建了一个包含一个嵌入层、一个LSTM层和一个全连接层的模型,并使用二元交叉熵作为损失函数,Adam优化器进行优化。最后,我们训练了模型,并评估了模型的准确率。 --相关问题--: 1. LSTM模型的优点是什么? 2. 除了LSTM,还
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值