告别复杂流程!500行IMDB数据搞定LLM情感分类

admin 2026-08-14 06:14:12 网络安全文章 来源:ZONE.CI 全球网 0 阅读模式

文章总结: 本文介绍使用Scikit-LLM与GroqAPI构建IMDB情感分类Pipeline的方案。该方案省去传统ML特征提取,可在scikit-learn框架内直接调用Llama模型做零样本推理,500条样本测试准确率达0.95。建议开发者以此经典语法快速接入LLM处理分类任务,并控制请求量规避配额限制。 综合评分: 76 文章分类: AI安全


cover_image

告别复杂流程!500行IMDB数据搞定LLM情感分类

数据派THU

2026年7月24日 17:00 北京

在小说阅读器读本章

去阅读

来源:DeepHub IMBA

本文约2000字,建议阅读5分钟

本文介绍了用Scikit-LLM和Groq构建IMDB情感分析pipeline。

传统的机器学习(Machine Learning)pipeline 在处理文本分类等预测任务时,通常依赖从原始文本中提取结构化的数值特征——例如 TF-IDF 频率或 token embedding——再输入逻辑回归、集成方法或支持向量机等经典模型。

大语言模型的兴起改变了这套流程:现在可以在机器学习框架里,直接调用预训练模型做零样本或少样本(few-shot)推理来完成语言任务。Scikit-LLM 就是一个这样的Python 库,它把经典机器学习和现代 LLM API 调用接到了一起。本文结合 Scikit-LLM 与 Groq 后端模型,构建一个端到端的情感分析(sentiment analysis)pipeline——情感分析是文本分类的一个细分场景——用开源模型跑出较快的推理速度。整个流程会用到一个规模较大、贴近真实场景的数据集:IMDB 电影评论数据集,从预处理一直做到推理。

#

前提条件、环境搭建与数据集获取

#

跑通本教程的代码,需要先装好 Scikit-LLM 库:

 pip install scikit-llm

装好之后,第一步是配置 API 凭证,把 Scikit-LLM 接到一个 LLM API 服务的端点(endpoint)上,这里用的是 Groq。先在 Groq 官网注册并生成一个 API key,然后填到下面代码里:

 from skllm.config import SKLLMConfig# 1. 指向 Groq 兼容的端点SKLLMConfig.set_gpt_url("https://api.groq.com/openai/v1")# 2. 设置你的免费 Groq API key# 在 https://console.groq.com/keys 获取你的 key SKLLMConfig.set_openai_key("YOUR-API-KEY-GOES-HERE")

set_gpt_url 这个端点函数默认兼容 OpenAI;这里把它路由到自定义的 Groq URL

接下来导入 IMDB 电影评论数据集——约 5 万条实例——并做好准备工作。每条实例是一段文本评论加一个情感标签,标签为 positive 或 negative,这是一个二分类问题,用逻辑回归之类的模型就能解决。

数据集可以直接从 GitHub 上一个公开仓库的 CSV 文件里读取:

 import pandas as pdfrom sklearn.model_selection import train_test_split# 获取一个大规模、具有现实规模的数据集(IMDB 电影评论 - 50,000 行)# 为方便起见,我们从一个公开    的原始 CSV 文件中读取数据url = "https://raw.githubusercontent.com/Ankit152/IMDB-sentiment-analysis/master/IMDB-Dataset.csv"print("Downloading dataset...")df = pd.read_csv(url)print(f"Total dataset size: {df.shape[0]} rows")# 在使用免费套餐 API 的实际 LLM pipeline 中,发送 50,000 次请求# 很可能会触发配额限制。因此,这里用 500 行数据来演示 pipeline 的执行流程。# 如果你有付费 API 权限,可以自由使用更多数据。df_sampled = df.sample(n=500, random_state=42)# IMDB 数据集包含 HTML 标签和格式噪声:这正好可以用来测试我们的清洗函数X = df_sampled["review"]y = df_sampled["sentiment"] # 标签为 'positive' 或 'negative'# 划分训练集(用于初始化零样本标签)与测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

这里只取了 500 行做演示,计算资源不够的话,样本量大了推理会很慢。这个 n=500 可以按需调整。

构建情感分析 Pipeline

#

一个数据科学 pipeline,说到底就是预处理、清洗、数据准备,加上模型搭建、推理和评估这几步。文本类的预测任务,预处理主要是清洗和规范化文本。Scikit-learn 的 FunctionTransformer 类可以把自定义函数封装成 pipeline 里的一个处理步骤:

&nbsp;from&nbsp;sklearn.preprocessing&nbsp;import&nbsp;FunctionTransformerdef&nbsp;clean_text_data(texts):&nbsp; &nbsp;&nbsp;"""Cleans raw text inputs by removing HTML tags and stripping whitespace."""&nbsp; &nbsp; series = pd.Series(texts).astype(str)&nbsp; &nbsp;&nbsp;# Remove HTML tags like <br />&nbsp; &nbsp; cleaned = series.str.replace(r'<[^>]+>',&nbsp;' ', regex=True)&nbsp; &nbsp;&nbsp;# Remove extra spaces&nbsp; &nbsp; cleaned = cleaned.str.strip().str.replace(r'\s+',&nbsp;' ', regex=True)&nbsp; &nbsp;&nbsp;return&nbsp;cleaned.tolist()# 将清洗函数封装起来,以便在 Pipeline 对象中使用&nbsp;text_cleaner = FunctionTransformer(clean_text_data)

把这个预处理对象和模型实例组合起来,就是完整的 Pipeline;训练和推理阶段的数据准备与模型调用都由它统筹。这里虽然用了”训练”这个说法,但实际不涉及任何权重训练,用的是 Groq 提供的预训练模型做零样本分类,对模型做 fit 操作,只是把要用的分类标签传给它。

&nbsp;from&nbsp;sklearn.pipeline&nbsp;import&nbsp;Pipelinefrom&nbsp;skllm.models.gpt.classification.zero_shot&nbsp;import&nbsp;ZeroShotGPTClassifier# 定义端到端 pipelinesentiment_pipeline = Pipeline([&nbsp; &nbsp; ("cleaner", text_cleaner),&nbsp; &nbsp;&nbsp;# 已更新为使用 Groq 当前可用的 Llama 3.1 8B 模型&nbsp; &nbsp; ("llm_classifier", ZeroShotGPTClassifier(model="custom_url::llama-3.1-8b-instant"))])# 拟合(fit)该 pipeline# 注意:对于零样本分类,fit() 并不会训练 LLM。# 它只是注册 'y_train' 中出现的唯一标签(positive、negative)。print("Fitting the pipeline...")&nbsp;sentiment_pipeline.fit(X_train, y_train)

模型拟合完成后,再用它做推理,两步都是熟悉的 scikit-learn 语法。除了评估 pipeline 的性能,下面也展示几条预测示例:

&nbsp;from&nbsp;sklearn.metrics&nbsp;import&nbsp;classification_reportprint(f"Running predictions on&nbsp;{len(X_test)}&nbsp;test samples...")# 通过 pipeline 运行预测predictions = sentiment_pipeline.predict(X_test)# 在真实数据上评估 pipeline 的性能print("\n--- Classification Report ---")print(classification_report(y_test, predictions))# 并排显示几个示例print("\n--- Sample Predictions ---")for&nbsp;review, actual, predicted&nbsp;in&nbsp;zip(X_test[:3], y_test[:3], predictions[:3]):&nbsp; &nbsp;&nbsp;# 为方便展示,截断评论文本&nbsp; &nbsp; short_review = review[:100] +&nbsp;"..."&nbsp;&nbsp; &nbsp;&nbsp;print(f"Review:&nbsp;{short_review}")&nbsp; &nbsp; &nbsp;print(f"Actual:&nbsp;{actual}&nbsp;| Predicted:&nbsp;{predicted}\n")

执行上述代码可能需要几分钟,以下是详细输出:

&nbsp;--- Classification Report ---&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; precision &nbsp; &nbsp;recall &nbsp;f1-score &nbsp; support&nbsp; &nbsp; negative &nbsp; &nbsp; &nbsp; 0.95 &nbsp; &nbsp; &nbsp;0.97 &nbsp; &nbsp; &nbsp;0.96 &nbsp; &nbsp; &nbsp; &nbsp;60&nbsp; &nbsp; positive &nbsp; &nbsp; &nbsp; 0.95 &nbsp; &nbsp; &nbsp;0.93 &nbsp; &nbsp; &nbsp;0.94 &nbsp; &nbsp; &nbsp; &nbsp;40&nbsp; &nbsp; accuracy &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0.95 &nbsp; &nbsp; &nbsp; 100&nbsp; &nbsp;macro avg &nbsp; &nbsp; &nbsp; 0.95 &nbsp; &nbsp; &nbsp;0.95 &nbsp; &nbsp; &nbsp;0.95 &nbsp; &nbsp; &nbsp; 100weighted avg &nbsp; &nbsp; &nbsp; 0.95 &nbsp; &nbsp; &nbsp;0.95 &nbsp; &nbsp; &nbsp;0.95 &nbsp; &nbsp; &nbsp; 100--- Sample Predictions ---Review: I saw mommy...well, she wasn't exactly kissing Santa Clause; he has his hand on her thigh and wicked...Actual: negative | Predicted: negativeReview: This entry is certainly interesting for series fans (like myself), but yet it is mostly incomprehens...Actual: negative | Predicted: negativeReview: Ingrid Bergman (Cleo Dulaine) has never been so beautiful. Gary Cooper as "Cleent" so perfectly cast...&nbsp;Actual: positive | Predicted: positive

这个 pipeline 在情感分类上的表现相当不错。

总结

#

本文用 Scikit-LLM 搭配 Groq 等 API 端点上免费提供的开源预训练 LLM,走通了一遍情感分类的端到端 pipeline。用经典的 scikit-learn 语法去做 LLM 驱动的机器学习任务,是个值得一试的路子。

编辑:于腾凯

校对:林亦霖

关于我们

数据派THU作为数据科学类公众号,背靠清华大学大数据研究中心,分享前沿数据科学与大数据技术创新研究动态、持续传播数据科学知识,努力建设数据人才聚集平台、打造中国大数据最强集团军。

新浪微博:@数据派THU

微信视频号:数据派THU****

今日头条:数据派THU


免责声明:

本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。

任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。

本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我

本文转载自:数据派THU 《告别复杂流程!500行IMDB数据搞定LLM情感分类》

评论:0   参与:  0