import pandas as pd
import numpy as np
from tqdm import tqdm
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
数据集概述
Flipkart 客户评论数据集由两个主要列组成:
review: 客户关于产品提供的文本评论。
rating: 客户给出的数字评分(星级),范围从 1 到 5。
rating 列表示客户为产品分配的星级数量。较高的值表示更有利的评论。
标签创建
为了简化我们的分析,我们将根据 rating 创建一个新列 label:
积极:如果 rating >= 4(例如,4 星或 5 星)
消极:如果 rating < 4(例如,1 或 2 星)
中立评分(3 星) 将被排除在此分析之外。
这个预处理步骤将帮助我们专注于评论中的明确情感极性(积极和消极)。
data = pd.read_csv('data.csv')
data = data[data["rating"]!=3]
data["label"] = data["rating"].apply(lambda x: 1if x >= 4else0)
print(data["label"].value_counts())
平衡数据集
为了这个例子的目的,我们将对正类进行下采样,以匹配负类的大小。
这确保了数据集的平衡,避免了由于类别不平衡导致的模型训练偏差。
这也确保了更快的计算时间,因为我们处理的数据量更少。
### Down-sample the positive class and combine with the negative class
data = pd.concat([
data[data["label"] == 1].sample(n=len(data[data["label"] == 0]),
random_state=1),
data[data["label"] == 0]
])
### Shuffle the resulting dataset
data = data.sample(frac=1, random_state=1).reset_index(drop=True)
数据划分
我们将数据分为 80% 的训练集和 20% 的测试集。
train = data[:int(0.8*len(data))]
test = data[int(0.8*len(data)):].reset_index(drop=True)
from datasets import Dataset
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
### Add a prompt column
prompt = "Is the following review positive or negative? "
test['t5'] = prompt + test['review']
### Convert pandas DataFrame to datasets.Dataset for compatibility with Hugging Face pipeline
dataset = Dataset.from_pandas(test)
### Load model
pipe = pipeline(
task="text2text-generation",
model="google/flan-t5-small",
device=0# Set to -1 for CPU, 0 for GPU
)
### Run inference on the test set
y_pred = []
for output in tqdm(pipe(KeyDataset(dataset, key="t5"))):
generated_text = output[0]["generated_text"]
# Map textual output to numerical labels
y_pred.append(0if generated_text == "negative"else1)
print("Classification Report (Flan-T5):")
print(classification_report(y_test, y_pred))
model_path = "juliensimon/reviews-sentiment-analysis"### Load model into pipeline
pipe = pipeline(
model=model_path,
tokenizer=model_path,
device=0
)
### Run inference on the test set
y_pred = []
for output in tqdm(pipe(KeyDataset(dataset, key="review"))):
label = output["label"]
# Map textual output to numerical labels
y_pred.append(0if"0"in label else1)
print("Classification Report (Task-Specific):")
print(classification_report(y_test, y_pred))