AI Sparkup

최신 AI 쉽게 깊게 따라잡기⚡

Scikit-LLM 튜토리얼 – Ollama로 오픈소스 LLM 무료 텍스트 분류하기

Scikit-LLM은 기본적으로 OpenAI API를 사용하지만, Ollama의 OpenAI 호환 엔드포인트와 연결하면 로컬 오픈소스 LLM으로 API 비용 없이 텍스트 분류를 수행할 수 있다. 이 튜토리얼에서는 Ollama에 Llama 3를 설치하고 ZeroShotGPTClassifier로 고객 리뷰를 분류하는 전체 흐름을 다룬다.

사전 준비

1. Ollama 설치 및 모델 다운로드

Ollama 공식 사이트에서 설치 후 원하는 모델을 pull한다:

# Llama 3 (가장 인기 있는 선택)
ollama run llama3

# 또는 Mistral
ollama run mistral

# 또는 Google Gemma
ollama run gemma

2. Python 패키지 설치

pip install scikit-learn pandas scikit-llm

전체 코드

import pandas as pd
from sklearn.model_selection import train_test_split
from skllm.config import SKLLMConfig
from skllm.models.gpt.classification.zero_shot import ZeroShotGPTClassifier

# Ollama 로컬 엔드포인트로 라우팅 설정
SKLLMConfig.set_gpt_url("http://localhost:11434/v1")
# Ollama는 로컬·무료이므로 실제 키가 필요하지 않음 (내부 검증용 더미 값)
SKLLMConfig.set_openai_key("local-ollama-is-free")

# 샘플 데이터셋 구성
data = {
    "review": [
        "The new macOS update is fantastic and runs smoothly.",
        "My battery is draining incredibly fast after the patch.",
        "I need help resetting my account password.",
        "The display on this monitor is breathtakingly crisp.",
        "Customer support hung up on me, very disappointing.",
    ],
    "tag": [
        "Positive Feedback",
        "Bug Report",
        "Support Request",
        "Positive Feedback",
        "Support Request",
    ]
}

df = pd.DataFrame(data)
X = df["review"]
y = df["tag"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)

# ZeroShotGPTClassifier로 Llama 3 사용
# 'custom_url::' 접두사로 위에서 설정한 Ollama 엔드포인트 사용
print("Initializing ZeroShotGPTClassifier with local Llama 3...")
clf = ZeroShotGPTClassifier(model="custom_url::llama3")

# 학습 (레이블 목록을 학습시키는 단계)
clf.fit(X_train, y_train)

# 예측
print("Sending data to Ollama for local inference...")
predictions = clf.predict(X_test)

# 결과 출력
for review, prediction in zip(X_test, predictions):
    print(f"Review Text: '{review}'")
    print(f"Predicted Tag: {prediction}")
    print("-" * 50)

실행 결과

Initializing ZeroShotGPTClassifier with local Llama 3...
Sending data to Ollama for local inference...
100%|███████████████████| 2/2 [00:12<00:00, 6.36s/it]
Review Text: 'My battery is draining incredibly fast after the patch.'
Predicted Tag: Support Request
--------------------------------------------------
Review Text: 'Customer support hung up on me, very disappointing.'
Predicted Tag: Support Request
--------------------------------------------------

핵심 포인트 정리

항목설명
SKLLMConfig.set_gpt_url()Ollama의 OpenAI 호환 엔드포인트 지정
custom_url::llama3커스텀 URL 엔드포인트 사용 시 필요한 접두사
ZeroShotGPTClassifier라벨 예시 없이 제로샷으로 분류하는 Scikit-LLM 클래스
fit()분류 레이블 목록을 전달 (실제 LLM 학습이 아님)
predict()각 텍스트에 가장 적합한 레이블을 LLM이 선택

다른 모델로 교체하기

Ollama에 설치된 다른 모델로 바꾸려면 model 인자만 변경하면 된다:

clf = ZeroShotGPTClassifier(model="custom_url::mistral")
# 또는
clf = ZeroShotGPTClassifier(model="custom_url::gemma")

관련 문서

참고 자료



AI Sparkup 구독하기

최신 게시물 요약과 더 심층적인 정보를 이메일로 받아 보세요! (무료)