汽车评论情感数据集
链接:https://pan.baidu.com/s/1K5TWrXbXBRXkCUpMbZq2XA
提取码:9mt9
代码
加载库与参数设置
首先先把一些基础的库进行加载
import random
import torch
from torch.utils.data import DataLoader
from transformers import AdamW, BertTokenizerFast, AutoModelForSequenceClassification
from sklearn.metrics import classification_report, accuracy_score, recall_score, f1_score
from tqdm import tqdm
# Set seed for reproducibility
import pandas as pd
import os
from sklearn.model_selection import train_test_split
import numpy as np
做实验时需要固定随机种子,方便实验的可重复性
# 设置种子
seed = 42
random.seed(seed)
torch.manual_seed(seed)
os.environ["CUDA_VISIBLE_DEVICES"] = '0' # 设置GPU型号
# 设置训练装置为GPU或CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
在这里设置GPU或CPU,如果你的机器存在多个GPU,则可以修改以下代码
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
修改为
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1,2,3'
在情感分析中,一般情况存在三种标签:消极、中性、积极。如果是更细粒度的标签,比如电商中对于评论分析有一星到五星的标签,则根据标签修改字典即可。
text_lst = []
label_lst = []
num = 0
label2id = {
"消极": 0, "中性": 1, "积极": 2}
数据集的读取
读取数据集,并确保文本与标签数量相同。读者可根据自己实际情况进行修改该部分。
# 读取"消极"类别数据集
with open('negative.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for idx, ele in enumerate(lines):
ele = ele.strip('\n')
text_lst.append(ele)
label_lst.append(label2id['消极'])
# 读取"中性"类别数据集
with open('neutral.txt', 'r', encoding='utf-8'