データアノテーションのためのアクティブラーニング:Gemini + Adala ガイド

Adalaフレームワーク - データアノテーションのためのアクティブラーニング

アクティブラーニングはトレーニング方法を変える AI モデル 最も価値のあるデータをインテリジェントに選択することで、アノテーションを作成します。 強力なLLM ような Google ジェミニ高いデータ品質を維持しながら手作業の労力を削減する効率的な注釈パイプラインを作成します。

このガイドでは、自律的なデータラベリングのための強力でありながら十分に活用されていないツールであるAdalaフレームワークを使用して、そのようなパイプラインを構築する方法について解説します。

Geminiを活用した医療症状分類器を実装します's 構造化されたアクティブラーニングワークフローを通じて能力を育成します。

データアノテーションのためのアクティブラーニングの理解

データアノテーションのためのアクティブラーニングの理解

アクティブラーニングは、教師あり学習における主要な課題である、大量のラベル付きデータの取得に取り組みます。アクティブラーニングアルゴリズムは、アノテーションのためにデータポイントをランダムに選択するのではなく、モデルの改善に最も貢献する、最も情報量の多いサンプルを特定します。

アクティブラーニングが重要な理由:

最も重要な部分に人的労力を集中させることで注釈付けのコストを削減します。
改善する モデルの精度 ラベル付けされた例が少なくなります。
代表性の低いカテゴリを優先することで、階級の不均衡に対処します。
モデルと 注釈者.

Adalaフレームワークは、アクティブラーニングのプロセスを効率化するモジュール式のコンポーネントを提供することで、これらのメリットを実際のワークフローにもたらします。実装に入る前に、AdalaがGoogle Geminiのような最新のLLMとの統合に特に適している理由を見ていきましょう。

Adalaとは?フレームワークの紹介

Adala(自律型データラベリングエージェント)は、データ処理のための専用エージェントを実装するために特別に設計されたオープンソースフレームワークです。従来の注釈ツールとは異なり、Adalaはエージェントベースのアプローチを採用しており、以下の要素を組み合わせています。

スキルベースのアーキテクチャ: アノテーションエージェントに必要な特定の機能を定義します。
実行時の柔軟性: 異なる LLM またはカスタム ランタイム間で切り替えます。
環境接続: さまざまなデータ ソースと対話します。
学習ループを内蔵: エージェントをトレーニングして、時間をかけて改善します。

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

この実装により、オリジナルに比べて大幅な改善がもたらされます。

  1. これはAdalaからの適切なクラス継承に従います's ベースアノテーター
  2. プロンプトの構築とレスポンスの解析のためのプライベートヘルパーメソッドを実装します
  3. 構造化された エラー処理 および入力ヒント
  4. 完全なドキュメントを提供する

症状分類パイプラインの構築

分類タスクのために、医療症状のデータセットを作成しましょう。元の実装とは異なり、カテゴリ間でバランスの取れた、より多様なデータセットを使用します。

パイソン

# 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. 臨床試験文書処理

有害事象レポートの抽出
分類します 患者報告アウトカム
安全信号を優先する

この実装は次のように拡張できます。

アノテーターの改善のためのフィードバックループの追加
異なる選択戦略(多様性、 クラスタリング)
人間による検証のためのWebインターフェースの作成
有効にします マルチラベル分類 複雑な症状の場合

結論

AdalaとGoogle Geminiの統合により、インテリジェントなアノテーションパイプラインを構築するための強力なフレームワークが提供されます。アクティブラーニング戦略を活用することで、高品質なアノテーションを維持しながら、必要な手作業を大幅に削減できます。

このチュートリアルで紹介するモジュール設計パターンは、さまざまな分野や注釈付けタスクへの容易な適応を可能にします。

さらに詳しく知りたい方は、AdalaのGitHubリポジトリに、これらの概念をより複雑な注釈シナリオに拡張するための追加の例とドキュメントが用意されています。

コメント送信

あなたのメールアドレスは公開されません。必須項目には*印が付いています。

プログラムに参加する(英語) Aimojo 部族!

毎週 76,000 人以上のメンバーがインサイダー情報を提供します。 
???? ボーナス: 200ドルの「AI 登録すると「マスタリーツールキット」が無料になります!

トレンド AI ツール
シャッターストック

ストック素材とAIを活用して、ライセンス取得済みのキャンペーンビジュアルをより迅速に作成しましょう。 ライセンスされたストックと生成が出会う AI ツール。 広告、ブログ、ソーシャルメディアキャンペーン用の、すぐに公開できる画像を制作します。

ボイスモッド

ライブでの会話を記憶に残るパフォーマンスに変えましょう AI 声 生の声と、サウンドボードからの即座の反応。 ゲーム、ストリーミング、ロールプレイ、そして楽しいグループチャットのために作られました。

Otter.ai

すべての会議を検索可能な意思決定と責任ある次のステップへとつなげましょう。 リアルタイムの文字起こし、要約、そしてより効果的なフォローアップ。 AI 多忙な共同作業チーム向けに作成された会議議事録。

Netlify

従来のサーバーインフラストラクチャを管理することなく、本番環境のウェブサイトをより迅速に立ち上げることができます。 AI エージェント、Gitデプロイメント、グローバル配信。 最新のフルスタックアプリケーション向け開発者ホスティングプラットフォーム。

Undress.app

リアルな大人を創造する AI 柔軟な編集ツールを備えたビジュアル。 Undressアニメーション化して、顔を入れ替える。 An AI 画像・動画制作を行うコンテンツスタジオ。

© 著作権 2023 - 2026 | 登録する AI プロ | ♥で作られました