PyTorch实例2——文本情绪分类器

该文详细介绍了使用Python和PyTorch进行文本分类的步骤,包括从网上爬取评论数据,进行数据预处理,构建基于词袋模型、RNN和LSTM的文本分类器,训练和测试模型,以及保存模型。实验涵盖了数据收集、清洗、建模和评估的全过程。
实例主要用于熟悉相关模型,并且练习创建一个模型的步骤:数据收集、数据预处理、构建模型、训练模型、测试模型、观察模型表现、保存模型

传送门:蓝桥云课实验

1. 实验环境

Jupyter Notebook
Python 3.7
PyTorch 1.4.0

2. 实验目的

编写一个自动爬虫程序,并使用它从在线商城的大量商品评论中抓取评论文本以及分类标签(评论得分)。
将根据文本的词袋(Bag of Word)模型来对文本进行建模,然后利用一个神经网络来对这段文本进行分类。识别一段文字中的情绪,从而判断出这句话是称赞还是抱怨。

3. 相关原理

使用 Python 从网络上爬取信息的基本方法
处理语料“洗数据”的基本方法
词袋模型搭建方法
简单 神经网络模型RNN 的搭建方法
简单 长短时记忆网络LSTM 的搭建方法
LSTM是RNN的一种,可以解决RNN短时记忆的不足。 参考博客:LSTM(长短时记忆网络)

4. 实验步骤

# 下载本实验所需数据并解压

!wget https://labfile.oss.aliyuncs.com/courses/1073/data3.zip
!unzip data3.zip

#下载分词工具 jieba,用于在评论文本的句子中进行中文分词。
!pip install jieba

4.1 数据收集

# 导入程序所需要的程序包

#抓取网页内容用的程序包
import json
import requests

#PyTorch用的包
import torch
import torch.nn as nn
import torch.optim
from torch.autograd import Variable

# 自然语言处理相关的包
import re #正则表达式的包
import jieba #结巴分词包
from collections import Counter #搜集器,可以让统计词频更简单

#绘图、计算用的程序包
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
从在线商城抓取评论数据

很多网站设置了反爬虫,这一步可以不做,后面会给数据文件
productId 为商品的 id,score 为评分,page 为对应的评论翻页的页码,pageSize 为总页数。
这里,我们设定只获得3星的商品评价,即 score=3 表示好的评分。
注意在下面每条 URL 中,都预留了 page={},用于后面的程序指定页号。
参考的代码:

# 在指定的url处获得评论
def get_comments(url):
    comments = []
    # 打开指定页面
    resp = requests.get(url)
    resp.encoding = 'gbk'

    #如果200秒没有打开则失败
    if resp.status_code != 200:
        return []

    #获得内容
    content = resp.text
    if content:
        #获得()括号中的内容
        ind = content.find('(')
        s1 = content[ind+1:-2]
        try:
            #尝试利用jason接口来读取内容,并做jason的解析
            js = json.loads(s1)
            #提取出comments字段的内容
            comment_infos = js['comments']
        except:
            print('error')
            return([])

        #对每一条评论进行内容部分的抽取
        for comment_info in comment_infos:
            comment_content = comment_info['content']
            str1 = comment_content + '\n'
            comments.append(str1)
    return comments

good_comments = []

# 对上述网址进行循环,并模拟翻页100次
j=0
for good_comment_url_template in good_comment_url_templates:
    for i in range(100):
        # 使用 format 指定 URL 中的页号,0~99
        url = good_comment_url_template.format(i)
        good_comments += get_comments(url)
        print('第{}条纪录,总文本长度{}'.format(j, len(good_comments)))
        j += 1
        
# 将结果存储到good.txt文件中
fw = open('data/good.txt', 'w')
fw.writelines(good_comments)
fw.close()
print('Finished')

在这里插入图片描述
再爬一颗星的负面评价

# 负向评论如法炮制
bad_comments = []

j = 0
for bad_comment_url_template in bad_comment_url_templates:
    for i in range(100):
        url = bad_comment_url_template.format(i)
        bad_comments += get_comments(url)
        print('第{}条纪录,总文本长度{}'.format(j, len(bad_comments)))
        j += 1

fw = open('data/bad.txt', 'w')
fw.writelines(bad_comments)
fw.close()
print('Finished')

在这里插入图片描述

4.2 数据预处理(洗数据)

根据数据收集步骤,爬取好的评论文本在 data/good.txt 以及 data/bad.txt 中。

# 过滤掉其中的标点符号等无意义的字符。这样可以使词袋模型预测的更加准确。
def filter_punc(sentence):
    sentence = re.sub("[\s+\.\!\/_,$%^*(+\"\'“”《》?“]+|[+——!,。?、~@#¥%……&*():]+", "", sentence)  
    return(sentence)
   
# 扫描所有的文本,分词、建立词典,分出正向还是负向的评论,is_filter可以过滤是否筛选掉标点符号
def Prepare_data(good_file, bad_file, is_filter = True):
    all_words = [] #存储所有的单词
    #将分词好的评论分别放置在 pos_sentences 与 neg_sentences 中
    pos_sentences = [] #存储正向的评论
    neg_sentences = [] #存储负向的评论
    with open(good_file, 'r') as fr:
        for idx, line in enumerate(fr):
            if is_filter:
                #过滤标点符号
                line = filter_punc(line)    #过滤无意义字符
            #分词
            words = jieba.lcut(line)
            if len(words) > 0:
                all_words += words
                pos_sentences.append(words)
    print('{0} 包含 {1} 行, {2} 个词.'.format(good_file, idx+1, len(all_words)))

    count = len(all_words)
    with open(bad_file, 'r') as fr:
        for idx, line in enumerate(fr):
            if is_filter:
                line = filter_punc(line)
            words = jieba.lcut(line)
            if len(words) > 0:
                all_words += words
                neg_sentences.append(words)
    print('{0} 包含 {1} 行, {2} 个词.'.format(bad_file, idx+1, len(all_words)-count))

    #建立词典,diction的每一项为{w:[id, 单词出现次数]}   建立好了词典,词典中包含评论中出现的每一种单词。
    diction = {
   
   }      #字典
    cnt = Counter(all_words)
    for word, freq in cnt.items():
        diction[word] = [len(diction), freq]
    print('字典大小:{}'.format(len(diction)))
    return(pos_sentences, neg_sentences, diction)
    
#根据单词返还单词的编码   用“词”来查“索引号”
def word2index(word, diction):
    if word in diction:
        value = diction[word][0]
    else:
        value = -1
    return(value)

#根据编码获得单词     用“索引号”来查“词”
def index2word(index, diction):
    for w,v in diction.items():
        if v[0] == index:
            return(w)
    return(None)

#主要代码:读取包含商品评论信息的两个文本文件。
good_file = 'data/good.txt'
bad_file  = 'data/bad.txt'

pos_sentences, neg_sentences, diction = Prepare_data(good_file, bad_file, True)
st = sorted([(v[1], w) for w, v in diction.items()])
st

在这里插入图片描述

4.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值