
능동 학습은 우리의 훈련 방식을 변화시킵니다 AI 모델 주석을 위한 가장 가치 있는 데이터를 지능적으로 선택하여. 다음과 함께 사용할 경우 강력한 LLM 처럼 구글 제미니이를 통해 높은 데이터 품질을 유지하면서 수동 작업을 줄이는 효율적인 주석 파이프라인을 생성합니다.
이 가이드에서는 강력하지만 아직 충분히 활용되지 않고 있는 자율 데이터 라벨링 도구인 Adala 프레임워크를 사용하여 이러한 파이프라인을 구축하는 방법을 살펴봅니다.
우리는 Gemini를 활용한 의학적 증상 분류기를 구현할 것입니다.'s 체계적인 능동 학습 워크플로를 통해 역량을 강화합니다.
데이터 주석을 위한 능동 학습 이해

능동 학습은 지도 학습 의 핵심 과제인 대량의 레이블링된 데이터 확보 문제를 해결합니다 . 능동 학습 알고리즘은 주석을 달기 위해 데이터 포인트를 무작위로 선택하는 대신, 모델 개선에 가장 크게 기여할 가장 유용한 샘플을 식별합니다.
능동 학습이 중요한 이유:
Adala 프레임워크는 능동적 학습 프로세스를 간소화하는 모듈형 구성 요소를 제공하여 이러한 이점을 실제 워크플로 에 적용합니다. 구현에 들어가기 전에 Adala가 Google Gemini와 같은 최신 학습 관리 시스템(LLM)과의 통합 에 특히 적합한 이유를 살펴보겠습니다.
Adala란 무엇인가요? 프레임워크 소개

Adala(Autonomous Data Labeling Agent)는 데이터 처리를 위한 특수 에이전트 구현에 특화된 오픈 소스 프레임워크 입니다 . 기존의 주석 도구와 달리 Adala는 다음과 같은 요소들을 결합한 에이전트 기반 접근 방식을 채택합니다.
Adala의 빠른 시작 예제를 살펴보면 감정 분류 구조를 알 수 있습니다.
파이썬
import pandas as pd
from adala.agents import Agent
from adala.environments import StaticEnvironment
from adala.skills import ClassificationSkill
from adala.runtimes import OpenAIChatRuntime
from rich import print
# Train dataset
train_df = pd.DataFrame([
["It was the negative first impressions, and then it started working.", "Positive"],
["Not loud enough and doesn't turn on like it should.", "Negative"],
["I don't know what to say.", "Neutral"],
["Manager was rude, but the most important that mic shows very flat frequency response.", "Positive"],
["The phone doesn't seem to accept anything except CBR mp3s.", "Negative"],
["I tried it before, I bought this device for my son.", "Neutral"],
], columns=["text", "sentiment"])
# Test dataset
test_df = pd.DataFrame([
"All three broke within two months of use.",
"The device worked for a long time, can't say anything bad.",
"Just a random line of text."
], columns=["text"])
agent = Agent(
# connect to a dataset
environment=StaticEnvironment(df=train_df),
# define a skill
skills=ClassificationSkill(
name='sentiment',
instructions="Label text as positive, negative or neutral.",
labels=["Positive", "Negative", "Neutral"],
input_template="Text: {text}",
output_template="Sentiment: {sentiment}"
),
# define runtimes
runtimes = {
'openai': OpenAIChatRuntime(model='gpt-4o'),
},
teacher_runtimes = {
'default': OpenAIChatRuntime(model='gpt-4o'),
},
default_runtime='openai',
)
agent.learn(learning_iterations=3, accuracy_threshold=0.95)
predictions = agent.run(test_df)
의료 증상 분류 작업을 위해, 우리는 이 아키텍처를 수정하여 Google Gemini를 통합하고 맞춤형 능동 학습 전략을 구현할 것입니다.
환경 설정
하자's Adala와 필수 종속성을 설치하여 시작하세요.
파이썬
# Install Adala directly from GitHub
!pip install -q git+https://github.com/HumanSignal/Adala.git
# Verify installation
!pip list | grep adala
# Install additional dependencies
!pip install -q google-generativeai pandas matplotlib numpy
또한 구성 요소에 직접 액세스하려면 저장소를 복제해야 합니다.
파이썬
# Clone the repository for access to source files
!git clone https://github.com/HumanSignal/Adala.git
# Ensure the package is in our Python path
import sys
sys.path.append('./Adala')
# Import key components
from Adala.adala.annotators.base import BaseAnnotator
from Adala.adala.strategies.random_strategy import RandomStrategy
from Adala.adala.utils.custom_types import TextSample, LabeledSample
Google Gemini를 사용자 정의 주석 도구로 통합
기존 구현 방식은 Google Gemini를 단순히 감싸는 래퍼를 사용했지만, 이번에는 Adala의 디자인 패턴을 따르는 더욱 견고한 어노테이터를 구축할 것입니다 . 이를 통해 솔루션의 유지보수성 과 확장성을 향상시킬 수 있습니다.
먼저 Google Generative를 설정해야 합니다. AI 고객:
파이썬
import google.generativeai as genai
import os
# Set API key from environment or enter manually
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or getpass("Enter your Gemini API Key: ")
genai.configure(api_key=GEMINI_API_KEY)
이제 Adala를 확장하여 사용자 정의 주석자를 만들어 보겠습니다.'s BaseAnnotator 클래스:
파이썬
import json
import re
from typing import List, Dict, Any, Optional
class GeminiAnnotator(BaseAnnotator):
"""Custom annotator using Google Gemini for medical symptom classification."""
def __init__(self,
model_name: str = "models/gemini-2.0-flash-lite",
categories: List[str] = None,
temperature: float = 0.1):
"""Initialize the Gemini annotator.
Args:
model_name: The Gemini model to use
categories: List of valid classification categories
temperature: Controls randomness in generation (lower = more deterministic)
"""
self.model = genai.GenerativeModel(
model_name=model_name,
generation_config={"temperature": temperature}
)
self.categories = categories or ["Cardiovascular", "Respiratory",
"Gastrointestinal", "Neurological"]
def _build_prompt(self, text: str) -> str:
"""Create a structured prompt for the model.
Args:
text: The symptom text to classify
Returns:
A formatted prompt string
"""
return f"""Classify this medical symptom into one of these categories:
{', '.join(self.categories)}.
Return JSON format: {{"category": "selected_category",
"confidence": 0.XX, "explanation": "brief_reason"}}
SYMPTOM: {text}"""
def _parse_response(self, response: str) -> Dict[str, Any]:
"""Extract structured data from model response.
Args:
response: Raw text response from Gemini
Returns:
Dictionary containing parsed fields
"""
try:
# Extract JSON from response even if surrounded by text
json_match = re.search(r'(\{.*\})', response, re.DOTALL)
result = json.loads(json_match.group(1) if json_match else response)
return {
"category": result.get("category", "Unknown"),
"confidence": result.get("confidence", 0.0),
"explanation": result.get("explanation", "")
}
except Exception as e:
return {
"category": "Unknown",
"confidence": 0.0,
"explanation": f"Error parsing response: {str(e)}"
}
def annotate(self, samples: List[TextSample]) -> List[LabeledSample]:
"""Annotate a batch of text samples.
Args:
samples: List of TextSample objects
Returns:
List of LabeledSample objects with annotations
"""
results = []
for sample in samples:
prompt = self._build_prompt(sample.text)
try:
response = self.model.generate_content(prompt).text
parsed = self._parse_response(response)
# Create labeled sample with metadata
labeled_sample = LabeledSample(
text=sample.text,
labels=parsed["category"],
metadata={
"confidence": parsed["confidence"],
"explanation": parsed["explanation"]
}
)
except Exception as e:
# Graceful error handling
labeled_sample = LabeledSample(
text=sample.text,
labels="Unknown",
metadata={"error": str(e)}
)
# Store reference to original sample
labeled_sample._sample = sample
results.append(labeled_sample)
return results
이 구현은 원본에 비해 상당한 개선을 제공합니다.
- 이는 Adala의 적절한 클래스 상속을 따릅니다.'s 베이스애노테이터
- 즉각적인 빌드 및 응답 구문 분석을 위한 개인 도우미 메서드를 구현합니다.
- 구조화된 사용 오류 처리 그리고 타입 힌트
- 완전한 문서를 제공합니다
증상 분류 파이프라인 구축
분류 작업을 위해 의료 증상 데이터셋을 만들어 보겠습니다 . 기존 구현 방식과는 달리, 각 범주별로 균형 잡힌 다양성을 갖춘 데이터셋을 사용하겠습니다 .
파이썬
# Create a more comprehensive dataset
symptom_data = [
# Cardiovascular symptoms
"Chest pain radiating to left arm during exercise",
"Heart palpitations when lying down",
"Swollen ankles and shortness of breath",
"Dizziness when standing up quickly",
# Respiratory symptoms
"Persistent dry cough with occasional wheezing",
"Shortness of breath when climbing stairs",
"Coughing up yellow or green mucus",
"Rapid breathing with chest tightness",
# Gastrointestinal symptoms
"Stomach cramps and nausea after eating",
"Burning sensation in upper abdomen",
"Frequent loose stools with abdominal pain",
"Yellowing of skin and eyes",
# Neurological symptoms
"Severe headache with sensitivity to light",
"Numbness in fingers of right hand",
"Memory loss and confusion",
"Tremors in hands when reaching for objects"
]
# Convert to TextSample objects
text_samples = [TextSample(text=text) for text in symptom_data]
고급 능동 학습 전략 구현
원래 구현에서는 간단한 우선순위 점수 매기기 메커니즘을 사용했습니다. Adala를 시연하기 위해 여러 전략을 추가하여 이를 개선할 것입니다.'s 유연성:
파이썬
import numpy as np
from typing import List, Callable
class PrioritizationStrategy:
"""Base class for sample prioritization strategies."""
def score_samples(self, samples: List[TextSample]) -> np.ndarray:
"""Assign priority scores to samples.
Args:
samples: List of samples to score
Returns:
Array of scores, higher values indicate higher priority
"""
raise NotImplementedError("Subclasses must implement this method")
def select(self, samples: List[TextSample], n: int = 1) -> List[TextSample]:
"""Select the top n highest scoring samples.
Args:
samples: List of samples to select from
n: Number of samples to select
Returns:
List of selected samples
"""
if not samples:
return []
scores = self.score_samples(samples)
indices = np.argsort(-scores)[:n] # Descending order
return [samples[i] for i in indices]
class KeywordPriority(PrioritizationStrategy):
"""Prioritize samples based on medical urgency keywords."""
def __init__(self, keyword_weights: Dict[str, float]):
"""Initialize with keyword weights.
Args:
keyword_weights: Dictionary mapping keywords to priority weights
"""
self.keyword_weights = keyword_weights
def score_samples(self, samples: List[TextSample]) -> np.ndarray:
scores = np.zeros(len(samples))
for i, sample in enumerate(samples):
# Base score
scores[i] = 0.1
# Add weights for each keyword found
text_lower = sample.text.lower()
for keyword, weight in self.keyword_weights.items():
if keyword in text_lower:
scores[i] += weight
return scores
class UncertaintyPriority(PrioritizationStrategy):
"""Prioritize samples based on model uncertainty."""
def __init__(self, model_fn: Callable[[List[TextSample]], List[float]]):
"""Initialize with uncertainty model function.
Args:
model_fn: Function that returns uncertainty scores for samples
"""
self.model_fn = model_fn
def score_samples(self, samples: List[TextSample]) -> np.ndarray:
# Higher uncertainty = higher priority
return np.array(self.model_fn(samples))
# Create a combined strategy
keyword_weights = {
"chest": 0.5,
"pain": 0.4,
"breathing": 0.4,
"dizz": 0.3,
"head": 0.2,
"numb": 0.2
}
keyword_strategy = KeywordPriority(keyword_weights)
자, 하자's 향상된 능동 학습 루프를 구현하세요.
파이썬
from matplotlib import pyplot as plt
from IPython.display import clear_output
import time
def run_active_learning_loop(
samples: List[TextSample],
annotator: GeminiAnnotator,
strategy: PrioritizationStrategy,
iterations: int = 5,
batch_size: int = 1,
visualization_interval: int = 1
):
"""Run an active learning loop with visualization.
Args:
samples: Pool of unlabeled samples
annotator: Annotation system
strategy: Sample selection strategy
iterations: Number of learning iterations
batch_size: Samples to annotate per iteration
visualization_interval: How often to update visualizations
Returns:
List of labeled samples
"""
labeled_samples = []
remaining_samples = list(samples)
print("\nStarting Active Learning Loop:")
for i in range(iterations):
print(f"\n--- Iteration {i+1}/{iterations} ---")
# Filter out already labeled samples
remaining_samples = [
s for s in remaining_samples
if s not in [getattr(l, '_sample', l) for l in labeled_samples]
]
if not remaining_samples:
print("No more samples to label. Stopping.")
break
# Select most important samples
selected = strategy.select(remaining_samples, n=batch_size)
# Annotate selected samples
newly_labeled = annotator.annotate(selected)
labeled_samples.extend(newly_labeled)
# Display annotation results
for sample in newly_labeled:
print(f"Text: {sample.text}")
print(f"Category: {sample.labels}")
print(f"Confidence: {sample.metadata.get('confidence', 0):.2f}")
explanation = sample.metadata.get('explanation', '')
print(f"Explanation: {explanation[:100]}..." if len(explanation) > 100 else explanation)
print()
# Visualize results periodically
if (i + 1) % visualization_interval == 0:
visualize_results(labeled_samples)
return labeled_samples
def visualize_results(labeled_samples: List[LabeledSample]):
"""Create visualizations of annotation results.
Args:
labeled_samples: List of labeled samples to visualize
"""
if not labeled_samples:
return
# Extract data
categories = [s.labels for s in labeled_samples]
confidence = [s.metadata.get("confidence", 0) for s in labeled_samples]
texts = [s.text[:30] + "..." for s in labeled_samples]
# Set up plots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Plot 1: Confidence by category
category_counts = {}
category_confidence = {}
for cat, conf in zip(categories, confidence):
if cat not in category_counts:
category_counts[cat] = 0
category_confidence[cat] = 0
category_counts[cat] += 1
category_confidence[cat] += conf
for cat in category_confidence:
category_confidence[cat] /= category_counts[cat]
cats = list(category_counts.keys())
counts = list(category_counts.values())
avg_conf = list(category_confidence.values())
x = np.arange(len(cats))
width = 0.35
ax1.bar(x - width/2, counts, width, label='Count')
ax1.bar(x + width/2, avg_conf, width, label='Avg Confidence')
ax1.set_xticks(x)
ax1.set_xticklabels(cats, rotation=45)
ax1.set_title('Category Distribution and Confidence')
ax1.legend()
# Plot 2: Individual sample confidence
sorted_indices = np.argsort(confidence)
ax2.barh(range(len(texts)), [confidence[i] for i in sorted_indices])
ax2.set_yticks(range(len(texts)))
ax2.set_yticklabels([texts[i] for i in sorted_indices])
ax2.set_title('Sample Confidence')
ax2.set_xlabel('Confidence')
plt.tight_layout()
plt.show()
엔드투엔드 파이프라인 실행
이제 우리는 완전한 능동 학습 파이프라인을 실행할 수 있습니다.
파이썬
# Initialize components
categories = ["Cardiovascular", "Respiratory", "Gastrointestinal", "Neurological"]
annotator = GeminiAnnotator(categories=categories)
strategy = keyword_strategy
# Run the active learning loop
labeled_data = run_active_learning_loop(
samples=text_samples,
annotator=annotator,
strategy=strategy,
iterations=5,
visualization_interval=2
)
# Final visualization and analysis
visualize_results(labeled_data)
# Print summary statistics
print("\nAnnotation Summary:")
print(f"Total samples annotated: {len(labeled_data)}")
categories = [s.labels for s in labeled_data]
unique_categories = set(categories)
print(f"Categories found: {len(unique_categories)}")
for category in unique_categories:
count = categories.count(category)
print(f" - {category}: {count} samples ({count/len(labeled_data):.1%})")
avg_confidence = sum(s.metadata.get("confidence", 0) for s in labeled_data) / len(labeled_data)
print(f"Average confidence: {avg_confidence:.2f}")
실용적인 응용 프로그램 및 확장
이 파이프라인은 의학적 증상 분류 외에도 수많은 실용적 응용 분야를 가지고 있습니다.
1. 콘텐츠 조정
2. 고객 피드백 분석
3. 임상시험 문서 처리
다음을 통해 이 구현을 확장할 수 있습니다.
AiMojo 추천:
맺음말
Adala와 Google Gemini의 통합은 지능형 주석 파이프라인 구축을 위한 강력한 프레임워크를 제공합니다. 능동 학습 전략을 활용함으로써 , 고품질 주석을 유지하면서 필요한 수동 작업을 획기적으로 줄일 수 있습니다.
이 튜토리얼에서 보여주는 모듈형 설계 패턴을 사용하면 다양한 도메인 및 주석 작업에 쉽게 적용 할 수 있습니다.
더 자세히 알아보고 싶은 분들을 위해 Adala GitHub 저장소에서는 이러한 개념을 보다 복잡한 주석 시나리오 로 확장하는 데 도움이 되는 추가 예제와 문서를 제공합니다.


