Benchmarking Scikit-Ollama vs. Groq-Backed Scikit-LLM: Speed, Cost, and Accuracy
TL;DR · AI 摘要
Benchmarking Scikit-Ollama vs. Groq-Backed Scikit-LLM: Speed, Cost, and Accuracy - MachineLearningMastery.com Benchmarki...
核心要点
- 主题聚焦:Benchmarking Scikit-Ollama vs. Groq-Backed Sciki
- 来源:Machine Learning Mastery,建议结合原文判断细节。
- AI 分析暂不可用,本条为保底评分与摘要。
对比 Scikit-Ollama 与 Groq 支持的 Scikit-LLM:速度、成本和准确性 - MachineLearningMastery.com
对比 Scikit-Ollama 与 Groq 支持的 Scikit-LLM:速度、成本和准确性
作者: Iván Palomares Carrascosa
日期: 2026年11月9日
分类: 语言模型
0
分享
在本文中,你将学习如何使用 Scikit-Ollama 和 Groq 支持的 Scikit-LLM 管道构建本地和云端 LLM 分类器的并排基准测试。
我们将涵盖的主题包括:
- 如何设置 Ollama、Scikit-Ollama 和 Scikit-LLM,以及如何创建用于测试的小型情感数据集。
- 如何编写一个可重用的辅助函数,用于测量零样本分类器的执行时间和准确性。
- 如何通过本地和 Groq API 运行相同的基准测试,以及在延迟、成本、设置和隐私方面的权衡。
引言
在相同的应用场景中寻找两个 LLM 解决方案(本地 vs 云端)的实际并排比较?本文展示了两种不同解决方案的直接对比基准测试:
- 一个基于本地 Ollama 的机器学习管道,使用 Scikit-Ollama 构建。
- 一个云端 LLM 等效方案,具体为 Groq 支持的 Scikit-LLM 管道,与第一个本地 LLM 场景具有相同目的。
对于目标任务,该比较将量化速度、准确性和实际(或潜在)成本等维度的真实权衡。
环境设置与数据创建
流程的第一步是安装所需的 Python 库,主要是 scikit-llm 和 scikit-ollama。如果你想在笔记本中运行代码,还需要安装 Ollama 引擎以本地下载和使用开源 LLM。如果你在本地使用 IDE,请确保从其官网单独安装 Ollama 并拉取(下载)本地 llama3 模型。无论哪种方式,代码都包含在后台启动 Ollama 服务器并拉取模型的指令。
import subprocess
import time
# 1. 安装包装库
!pip install -q scikit-llm scikit-ollama
# 2. 安装 Ollama(如果使用本地 IDE 并已安装则不需要)
# 并启动后台服务器
!apt-get update -qq && apt-get install -y -qq zstd
!curl -fsSL https://ollama.com/install.sh | sh
print("Starting Ollama server...")
process = subprocess.Popen(["ollama", "serve"])
time.sleep(5)
# 3. 拉取 Llama3 模型
print("Downloading Llama 3...")
!ollama pull llama3
print("Environment is ready!")1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import subprocess
time
# 1. 安装包装库
!pip install -q scikit-llm scikit-ollama
# 2. 安装 Ollama(如果使用本地 IDE 并已安装则不需要)
# 并启动后台服务器
apt-get update -qq && apt-get install -y -qq zstd
curl -fsSL https://ollama.com/install.sh | sh
print("Starting Ollama server...")
process = subprocess.Popen(["ollama", "serve"])
time.sleep(5)
# 3. 拉取 Llama3 模型
print("Downloading Llama 3...")
ollama pull llama3
print("Environment is ready!")如果设置过程顺利,我们就可以进入下一步:创建数据集并定义辅助基准函数。这个阶段基本上分为以下几个步骤:
首先,让我们创建一个包含文本及其对应真实情感标签(y_true)的小型虚拟数据集:
import time import numpy as np from sklearn.metrics import accuracy_score texts = [ "I absolutely loved the new update, everything is so fast!", "The customer service was terrible and unhelpful.", "Works exactly as described, highly recommend.", "My screen broke after two days of use.", "It's okay, nothing special but it does the job." ] y_true = ["Positive", "Negative", "Positive", "Negative", "Positive"] candidate_labels = ["Positive", "Negative"]
numpy
as
np
from
sklearn
metrics
accuracy_score
texts
"I absolutely loved the new update, everything is so fast!"
"The customer service was terrible and unhelpful."
"Works exactly as described, highly recommend."
"My screen broke after two days of use."
"It's okay, nothing special but it does the job."
y_true
"Positive"
"Negative"
candidate_labels
其次,为了使我们的代码可重用且易于扩展到新的比较场景,并在统一的测试逻辑下运行,我们将定义一个名为 benchmark_estimator 的“通用”辅助函数。该函数负责处理管道的 fit() 和 predict() 方法。正如你稍后将看到的,我们实例化的本地和云端估计器都会通过相同的函数进行处理,从而公平地衡量准确性、执行时间等指标。
def benchmark_estimator(name, clf, texts, y_true, candidate_labels, cost_note=""): print(f"--- Running Benchmark: {name} ---") start_time = time.perf_counter() clf.fit(None, candidate_labels) predictions = clf.predict(texts) elapsed_time = time.perf_counter() - start_time accuracy = accuracy_score(y_true, predictions) print(f"Time Elapsed : {elapsed_time:.2f} seconds") print(f"Accuracy : {accuracy * 100:.1f}%") print(f"Predictions : {list(predictions)}") print(f"Cost : {cost_note}\n")
def
benchmark_estimator
name
clf
cost_note
""
f
"--- Running Benchmark: {name} ---"
start_time
perf_counter
fit
None
predictions
predict
elapsed_time
accuracy
"Time Elapsed : {elapsed_time:.2f} seconds"
"Accuracy : {accuracy * 100:.1f}%"
"Predictions : {list(predictions)}"
"Cost : {cost_note}\n"
场景 1:使用 Scikit-Ollama 进行本地零样本分类
在我们的基准测试首次运行时,我们将从 Scikit-Ollama 初始化一个 ZeroShotOllamaClassifier,目标是之前下载的 Llama3 模型。
之后我们运行基准测试。如何运行?其实比听起来简单,因为我们已经有了辅助函数来完成这个任务!我们只需要仔细向函数传递正确的参数:这个基准估计器的描述性名称、刚刚定义的零样本分类器实例、数据、真实标签以及问题中已有的类别标签,存储在 candidate_labels 中。
总之,我们正在测试零样本分类管道的本地部分,证明模型如何能够在本地机器(或 Google Colab 会话)上完全独立地对文本进行分类,而无需依赖外部服务器,从而保证绝对的数据隐私并避免 API 成本。
from skollama.models.ollama.classification.zero_shot import ZeroShotOllamaClassifier # 初始化本地估计器 local_clf = ZeroShotOllamaClassifier(model="llama3") # 执行本地基准测试 benchmark_estimator( name="Local: scikit-ollama (Llama 3)", clf=local_clf, texts=texts, y_true=y_true, candidate_labels=candidate_labels, cost_note="$0.00 (Local Hardware)" )
skollama
models
classification
zero_shot
ZeroShotOllamaClassifier
初始化本地估计器
local_clf
model
"llama3"
执行本地基准测试
"本地: scikit-ollama (Llama 3)"
"$0.00 (本地硬件)"
结果:
耗时 : 80.71 秒 准确率 : 80.0% 预测结果 : [np.str_('Positive'), np.str_('Negative'), np.str_('Positive'), np.str_('Negative'), np.str_('Negative')] 成本 : $0.00 (本地硬件)
耗时
80.71
秒
80.0
%
str_
'Positive'
'Negative'
成本
$
0.00
本地
硬件
由于我们使用 Ollama 运行免费开源的本地模型,因此成本本质上为 $0。虽然模型在 5 个样本中正确预测了 4 个(80%),但请注意,为了更真实的评估,我们应使用比 5 个示例更大的数据集。我们保持数据集最小规模以确保任何人运行时的流畅性和可访问性,但如有需要,可以自由添加额外数据示例(及其对应的真标签)。
场景 2:基于云的零样本分类(使用 Scikit-LLM 和 Groq)
为进行对比,现在我们将借助 Scikit-LLM 定义另一个零样本分类器。为此,我们使用 SKLLMConfig.set_gpt_url() 将 Scikit-LLM 原生的 ZeroShotGPTClassifier 路由到通过自定义 URL 前缀连接的兼容云端点。通过使用 Groq 等免费云模型,这种方法避免了账户配额限制,使基准测试完全免费。
您可能需要先安装 Scikit-LLM:
!pip install -q --upgrade scikit-llm
--
upgrade
另外,请确保从 Groq 官网获取 API 密钥,并将其添加到 Google Colab 的名为 GROQ_API_KEY 的秘密变量中。
然后使用以下代码执行基准测试演示的第二个“参与者”:
from google.colab import userdata from skllm.config import SKLLMConfig from skllm.models.gpt.classification.zero_shot import ZeroShotGPTClassifier try: # 1. 从 Colab Secrets 获取免费 Groq API 密钥 GROQ_API_KEY = userdata.get('GROQ_API_KEY') # 2. 配置 skllm 通过自定义 URL 路由流量到 Groq 而非 OpenAI SKLLMConfig.set_openai_key(GROQ_API_KEY) SKLLMConfig.set_gpt_url("https://api.groq.com/openai/v1/") # 3. 使用活动模型初始化真正的 scikit-llm 分类器 # "custom_url::" 前缀指示 scikit-llm 使用上述提供的 URL cloud_clf = ZeroShotGPTClassifier(model="custom_url::openai/gpt-oss-20b") # 使用通用辅助工具执行云基准测试 benchmark_estimator( name="Cloud: scikit-llm via Groq API (gpt-oss-20b)", clf=cloud_clf, texts=texts, y_true=y_true, candidate_labels=candidate_labels, cost_note="$0.00 (Free Cloud Tier)" ) except userdata.SecretNotFoundError: print("请将免费的 'GROQ_API_KEY'(来自 console.groq.com)添加到您的 Google Colab Secrets。") except Exception as e: print(f"API 调用期间发生错误: {e}")
21
22
23
24
25
26
27
28
29
colab
userdata
skllm
config
SKLLMConfig
gpt
ZeroShotGPTClassifier
try
1. 从 Colab Secrets 获取免费 Groq API 密钥
GROQ_API_KEY
'GROQ_API_KEY'
2. 配置 skllm 通过自定义 URL 路由流量到 Groq 而非 OpenAI
set_openai_key
set_gpt_url
"https://api.groq.com/openai/v1/"
3. 使用活动模型初始化真正的 scikit-llm 分类器
"custom_url::" 前缀指示 scikit-llm 使用上述提供的 URL
cloud_clf
"custom_url::openai/gpt-oss-20b"
使用通用辅助工具执行云基准测试
"Cloud: scikit-llm via Groq API (gpt-oss-20b)"
"$0.00 (Free Cloud Tier)"
except
SecretNotFoundError
"请将免费的 'GROQ_API_KEY'(来自 console.groq.com)添加到您的 Google Colab Secrets。"
Exception
e
"在API调用期间发生错误:{e}"
耗时:2.02秒 准确率:100.0% 预测结果:[np.str_('Positive'), np.str_('Negative'), np.str_('Positive'), np.str_('Negative'), np.str_('Positive')] 成本:$0.00(免费云层级)
2.02
100.0
免费
云
层级
显然,由于Groq API在撰写时也是免费使用的,因此成本仍然是静态输出的$0。虽然此处的实验为了节省空间而规模较小,且并未尝试在如此小的数据集上比较准确性,但如果我们扩展实验,可以得出一些适用的结论:
- 延迟主要受本地Ollama解决方案的GPU显存和令牌生成速度限制,而云解决方案由于拥有专用的推理引擎,几乎是即时的。
- 我们使用的两种方案都是免费的,但如果您切换到其他云服务提供商(如OpenAI),每次推理调用可能会产生小额费用。
- 云解决方案的设置开销也更低。
- Ollama本地模型的最大优势在于完全的数据隐私,敏感数据可能永远不会离开本地内存。
总结
本文逐步演示了如何在本地推理和云推理之间构建一个公平、标准化的基准测试,用于LLM驱动的流水线,并在零样本分类场景中进行了说明。这两种方法分别使用Scikit-Ollama和Scikit-LLM,均遵循传统机器学习流水线中scikit-learn的经典.fit()和.predict()方法。
更多相关内容
- 提示缓存与微调:成本和延迟…
- 提示压缩用于LLM生成优化…
- 不作为的真实成本:孤岛如何造成伤害…
- 机器学习的数据工程:优化成本效率
- 不平衡分类的成本敏感学习
- 如何开发成本敏感的神经网络…