基于深度学习的文本分类案例:使用LSTM进行情绪分类
Sentiment classification using LSTM
在这个笔记本中,我们将使用LSTM架构在电影评论数据集上训练一个模型来预测评论的情绪。首先,让我们看看什么是LSTM?
LSTM,即长短时记忆,是一种序列神经网络架构,它利用其结构保留了对前一序列的记忆。第一个被引入的序列模型是RNN。但是,很快研究人员发现,RNN并没有保留很多以前序列的记忆。这导致在长文本序列中失去上下文。
为了维护这一背景,LSTM被引入。在LSTM单元中,有一些特殊的结构被称为门和单元状态,它们被改变和维护以保持LSTM中的记忆。要了解这些结构如何工作,请阅读 this blog.
从代码上看,我们正在使用tensorflow和keras来建立模型和训练它。为了进一步了解本项目的代码/概念,我们使用了以下参考资料。
References:
(1) Medium article on keras lstm
(2) Keras embedding layer documentation
(3) Keras example of text classification from scratch
(4) Bi-directional lstm model example
(5) kaggle notebook for text preprocessing
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
/kaggle/input/sentiment-analysis-on-movie-reviews/sampleSubmission.csv
/kaggle/input/sentiment-analysis-on-movie-reviews/train.tsv.zip
/kaggle/input/sentiment-analysis-on-movie-reviews/test.tsv.zip
train_data = pd.read_csv('/kaggle/input/sentiment-analysis-on-movie-reviews/train.tsv.zip',sep = '\t')
test_data = pd.read_csv('/kaggle/input/sentiment-analysis-on-movie-reviews/train.tsv.zip',sep = '\t')
train_data.head()
PhraseId | SentenceId | Phrase | Sentiment | |
---|---|---|---|---|
0 | 1 | 1 | A series of escapades demonstrating the adage ... | 1 |
1 | 2 | 1 | A series of escapades demonstrating the adage ... | 2 |
2 | 3 | 1 | A series | 2 |
3 | 4 | 1 | A | 2 |
4 | 5 | 1 | series | 2 |
train_data = train_data.drop(['PhraseId','SentenceId'],axis = 1)
test_data = test_data.drop(['PhraseId','SentenceId'],axis = 1)
import keras
from keras.models import Sequential
from keras.layers import Dense #层lyer
from keras.layers import LSTM
from keras.layers import Activation
from keras.layers import Embedding
from keras.layers import Bidirectional
max_features = 20000 # 只考虑前20千字
maxlen = 200
train_data.head()
Phrase | Sentiment | |
---|---|---|
0 | A series of escapades demonstrating the adage ... | 1 |
1 | A series of escapades demonstrating the adage ... | 2 |
2 | A series | 2 |
3 | A | 2 |
4 | series | 2 |
from nltk.corpus import stopwords
import re
# 定义文本清理函数
def text_cleaning(text):
forbidden_words = set(stopwords.words('english'))#停用词,对于理解文章没有太大意义的词,比如"the"、“an”、“his”、“their”
if text:
text = ' '.join(text.split('.'))
text = re.sub('\/',' ',text)
text = re.sub(r'\\',' ',text)
text = re.sub(r'((http)\S+)','',text)
text = re.sub(r'\s+', ' ', re.sub('[^A-Za-z]', ' ', text.strip().lower())).strip()
text = re.sub(r'\W+', ' ', text.strip().lower()).strip()
text = [word for word in text.split() if word not in forbidden_words]
return text
return []
# 将句子转化为词语列表
train_data['flag'] = 'TRAIN'
test_data['flag'] = 'TEST'
total_docs = pd.concat([train_data,test_data],axis = 0,ignore_index = True)
total_docs['Phrase'] = total_docs['Phrase'].apply(lambda x: ' '.join(text_cleaning(x)))
phrases = total_docs['Phrase'].tolist()
from keras.preprocessing.text import one_hot
vocab_size = 50000
encoded_phrases = [one_hot(d, vocab_size) for d in phrases]
total_docs['Phrase'] = encoded_phrases
train_data = total_docs[total_docs['flag'] == 'TRAIN']
test_data = total_docs[total_docs['flag'] == 'TEST']
x_train = train_data['Phrase']
y_train = train_data['Sentiment']
x_val = test_data['Phrase']
y_val = test_data['Sentiment']
x_train.head()
y_train.unique()
array([1, 2, 3, 4, 0])
tf.keras.preprocessing.sequence.pad_sequences()的用法:https://blog.csdn.net/qq_45465526/article/details/109400926)
# 将序列转化为经过填充以后得到的一个长度相同新的序列
x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)
x_val = keras.preprocessing.sequence.pad_sequences(x_val, maxlen=maxlen)
model = Sequential()
inputs = keras.Input(shape=(None,), dtype="int32")
# 将每个整数嵌入一个128维的向量中
model.add(inputs)
model.add(Embedding(50000, 128))
# 增加2个双向的LSTM
model.add(Bidirectional(LSTM(64, return_sequences=True)))
model.add(Bidirectional(LSTM(64)))
# 添加一个分类器
model.add(Dense(5, activation="sigmoid"))
#model = keras.Model(inputs, outputs)
model.summary()
result:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding (Embedding) (None, None, 128) 6400000
_________________________________________________________________
bidirectional (Bidirectional (None, None, 128) 98816
_________________________________________________________________
bidirectional_1 (Bidirection (None, 128) 98816
_________________________________________________________________
dense (Dense) (None, 5) 645
=================================================================
Total params: 6,598,277
Trainable params: 6,598,277
Non-trainable params: 0
_________________________________________________________________
model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=32, epochs=30, validation_data=(x_val, y_val))
result:
Epoch 1/30
4877/4877 [==============================] - 562s 115ms/step - loss: 0.9593 - accuracy: 0.6107 - val_loss: 0.7819 - val_accuracy: 0.6798
Epoch 2/30
4877/4877 [==============================] - 520s 107ms/step - loss: 0.7942 - accuracy: 0.6729 - val_loss: 0.7094 - val_accuracy: 0.7114
.....................................................................
Epoch 29/30
4877/4877 [==============================] - 539s 111ms/step - loss: 0.3510 - accuracy: 0.8117 - val_loss: 0.3220 - val_accuracy: 0.8242
Epoch 30/30
4877/4877 [==============================] - 553s 113ms/step - loss: 0.3485 - accuracy: 0.8124 - val_loss: 0.3187 - val_accuracy: 0.8238
<tensorflow.python.keras.callbacks.History at 0x7fa9b82520d0>
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_val, y_val))
result:
Epoch 1/5
4877/4877 [==============================] - 535s 110ms/step - loss: 0.3477 - accuracy: 0.8128 - val_loss: 0.3193 - val_accuracy: 0.8240
Epoch 2/5
4877/4877 [==============================] - 543s 111ms/step - loss: 0.3457 - accuracy: 0.8134 - val_loss: 0.3173 - val_accuracy: 0.8250
Epoch 3/5
4877/4877 [==============================] - 542s 111ms/step - loss: 0.3428 - accuracy: 0.8140 - val_loss: 0.3158 - val_accuracy: 0.8254
Epoch 4/5
4877/4877 [==============================] - 541s 111ms/step - loss: 0.3429 - accuracy: 0.8144 - val_loss: 0.3165 - val_accuracy: 0.8257
Epoch 5/5
4877/4877 [==============================] - 557s 114ms/step - loss: 0.3395 - accuracy: 0.8150 - val_loss: 0.3136 - val_accuracy: 0.8259
<tensorflow.python.keras.callbacks.History at 0x7fa8e0763150>
总之,我们创建了一个双向的LSTM模型,并对其进行了检测情感的训练。我们达到了80%的训练和82%的验证准确率。
Notebook code:https://www.kaggle.com/code/shyambhu/sentiment-classification-using-lstm
原创作者:孤飞-博客园
个人博客:https://blog.onefly.top
基于深度学习的文本分类案例:使用LSTM进行情绪分类的更多相关文章
- 【AI in 美团】深度学习在文本领域的应用
背景 近几年以深度学习技术为核心的人工智能得到广泛的关注,无论是学术界还是工业界,它们都把深度学习作为研究应用的焦点.而深度学习技术突飞猛进的发展离不开海量数据的积累.计算能力的提升和算法模型的改进. ...
- 万字总结Keras深度学习中文文本分类
摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...
- 回望2017,基于深度学习的NLP研究大盘点
回望2017,基于深度学习的NLP研究大盘点 雷锋网 百家号01-0110:31 雷锋网 AI 科技评论按:本文是一篇发布于 tryolabs 的文章,作者 Javier Couto 针对 2017 ...
- #Deep Learning回顾#之基于深度学习的目标检测(阅读小结)
原文链接:https://www.52ml.net/20287.html 这篇博文主要讲了深度学习在目标检测中的发展. 博文首先介绍了传统的目标检测算法过程: 传统的目标检测一般使用滑动窗口的框架,主 ...
- 【OCR技术系列之四】基于深度学习的文字识别(3755个汉字)
上一篇提到文字数据集的合成,现在我们手头上已经得到了3755个汉字(一级字库)的印刷体图像数据集,我们可以利用它们进行接下来的3755个汉字的识别系统的搭建.用深度学习做文字识别,用的网络当然是CNN ...
- OCR技术浅探:基于深度学习和语言模型的印刷文字OCR系统
作者: 苏剑林 系列博文: 科学空间 OCR技术浅探:1. 全文简述 OCR技术浅探:2. 背景与假设 OCR技术浅探:3. 特征提取(1) OCR技术浅探:3. 特征提取(2) OCR技术浅探:4. ...
- 基于深度学习的目标检测技术演进:R-CNN、Fast R-CNN、Faster R-CNN
object detection我的理解,就是在给定的图片中精确找到物体所在位置,并标注出物体的类别.object detection要解决的问题就是物体在哪里,是什么这整个流程的问题.然而,这个问题 ...
- (转)基于深度学习的目标检测技术演进:R-CNN、Fast R-CNN、Faster R-CNN
object detection我的理解,就是在给定的图片中精确找到物体所在位置,并标注出物体的类别.object detection要解决的问题就是物体在哪里,是什么这整个流程的问题.然而,这个问题 ...
- 基于深度学习的安卓恶意应用检测----------android manfest.xml + run time opcode, use 深度置信网络(DBN)
基于深度学习的安卓恶意应用检测 from:http://www.xml-data.org/JSJYY/2017-6-1650.htm 苏志达, 祝跃飞, 刘龙 摘要: 针对传统安卓恶意程序检测 ...
随机推荐
- ClickHouse(03)ClickHouse怎么安装和部署
本文会介绍如何安装和部署ClickHouse,官方推荐的几种安装模式,以及安装之后如何启动,ClickHouse集群如何配置等. 简单来说,ClickHouse的搭建流程如下: 环境检查,环境依赖安装 ...
- 贝壳自动化测试平台sosotest 学习记录
手工测试VS自动化测试 用例执行: 手动执行 自动执行 是否需要些脚本: 需要 不需要 测试报告生成: 手动 自动 常见的测试技术 关键字驱动的测试框架 RobotFRamework 单元测试框架 自 ...
- Linux sed工具的使用
基础知识 - 行编辑工具: 一行一行处理文件内容 - 全屏编辑工具:一次性将文件所有内容加载到内存中 sed编辑器: Stream Editor 工作原理: 逐行处理文件内容,一次读取一行内容到模式空 ...
- Mybatis-Generator 自定义注释
继承DefaultCommentGenerator 或者CommentGenerator package com.zhianchen.mysqlremark.toword.config;import ...
- STC8H开发(十四): I2C驱动RX8025T高精度实时时钟芯片
目录 STC8H开发(一): 在Keil5中配置和使用FwLib_STC8封装库(图文详解) STC8H开发(二): 在Linux VSCode中配置和使用FwLib_STC8封装库(图文详解) ST ...
- 2、MYSQL介绍
一.mysql优点 1.成本低:开放源代码,一般可以免费试用,采用的是gpl协议 2.性能高:执行很快 3.简单:很容易安装和使用 二.DBMS分为两类: 1.基于共享文件系统的DBMS(Acce ...
- CSS面试总结
文章首次发表:_时雨_CSDN 1. BFC:块级格式化上下文(重点关注) BFC基本概念:BFC是 CSS布局的一个概念,是一块独立的渲染区域(环境),里面的元素不会影响到外部的元素. BFC原理( ...
- java关键字的概念与特征和标识符的概念和规则
什么是关键字 比如说邮箱地址 abc@qq.com 123abc@qq.com 这样的只要没有人占用都是和发布的 那么这样呢 hahah@enen@itcast.cn呢 @是电子邮箱当中有特殊含义的 ...
- 跳转语句break、continue、return
1.break 语句 概念: break语句在循环中的作用是终止当前循环,在switch语句中的作用是终止switch. 示例: 输出结果: 2.continue 语句 概念: continue语句 ...
- Redis 定长队列的探索和实践
vivo 互联网服务器团队 - Wang Zhi 一.业务背景 从技术的角度来说,技术方案的选型都是受限于实际的业务场景,都以解决实际业务场景为目标. 在我们的实际业务场景中,需要以游戏的维度收集和上 ...