传统的机器学习(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 pd
from 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 里的一个处理步骤:
from sklearn.preprocessing import FunctionTransformer
def clean_text_data(texts):
"""Cleans raw text inputs by removing HTML tags and stripping whitespace."""
series = pd.Series(texts).astype(str)
# Remove HTML tags like <br />
cleaned = series.str.replace(r'<[^>]+>', ' ', regex=True)
# Remove extra spaces
cleaned = cleaned.str.strip().str.replace(r'\s+', ' ', regex=True)
return cleaned.tolist()
# 将清洗函数封装起来,以便在 Pipeline 对象中使用
text_cleaner = FunctionTransformer(clean_text_data)
把这个预处理对象和模型实例组合起来,就是完整的 Pipeline;训练和推理阶段的数据准备与模型调用都由它统筹。这里虽然用了"训练"这个说法,但实际不涉及任何权重训练,用的是 Groq 提供的预训练模型做零样本分类,对模型做 fit 操作,只是把要用的分类标签传给它。
from sklearn.pipeline import Pipeline
from skllm.models.gpt.classification.zero_shot import ZeroShotGPTClassifier
# 定义端到端 pipeline
sentiment_pipeline = Pipeline([
("cleaner", text_cleaner),
# 已更新为使用 Groq 当前可用的 Llama 3.1 8B 模型
("llm_classifier", ZeroShotGPTClassifier(model="custom_url::llama-3.1-8b-instant"))
])
# 拟合(fit)该 pipeline
# 注意:对于零样本分类,fit() 并不会训练 LLM。
# 它只是注册 'y_train' 中出现的唯一标签(positive、negative)。
print("Fitting the pipeline...")
sentiment_pipeline.fit(X_train, y_train)
模型拟合完成后,再用它做推理,两步都是熟悉的 scikit-learn 语法。除了评估 pipeline 的性能,下面也展示几条预测示例:
from sklearn.metrics import classification_report
print(f"Running predictions on {len(X_test)} 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 review, actual, predicted in zip(X_test[:3], y_test[:3], predictions[:3]):
# 为方便展示,截断评论文本
short_review = review[:100] + "..."
print(f"Review: {short_review}")
print(f"Actual: {actual} | Predicted: {predicted}\n")
执行上述代码可能需要几分钟,以下是详细输出:
--- Classification Report ---
precision recall f1-score support
negative 0.95 0.97 0.96 60
positive 0.95 0.93 0.94 40
accuracy 0.95 100
macro avg 0.95 0.95 0.95 100
weighted avg 0.95 0.95 0.95 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: negative
Review: This entry is certainly interesting for series fans (like myself), but yet it is mostly incomprehens...
Actual: negative | Predicted: negative
Review: Ingrid Bergman (Cleo Dulaine) has never been so beautiful. Gary Cooper as "Cleent" so perfectly cast...
Actual: positive | Predicted: positive
这个 pipeline 在情感分类上的表现相当不错。
总结
本文用 Scikit-LLM 搭配 Groq 等 API 端点上免费提供的开源预训练 LLM,走通了一遍情感分类的端到端 pipeline。用经典的 scikit-learn 语法去做 LLM 驱动的机器学习任务,是个值得一试的路子。
https://avoid.overfit.cn/post/86f896f1280a440caed1d48b83a82466