jpskill.com
🛠️ 開発・MCP コミュニティ

kaggle-finetune

Kaggleのデータセットを活用し、チャットボットや特定分野に特化したAIアシスタントを構築するために、データセットの検索からダウンロード、会話形式への前処理、PEFT/LoRAによる学習までを効率的に行うSkill。

📜 元の英語説明(参考)

End-to-end workflow for fine-tuning LLMs using Kaggle datasets. Use when downloading datasets from Kaggle for model training, preparing conversation/customer service data for chatbot fine-tuning, or building domain-specific AI assistants. Covers dataset discovery, download, preprocessing into chat format, and integration with PEFT/LoRA training.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Kaggleのデータセットを活用し、チャットボットや特定分野に特化したAIアシスタントを構築するために、データセットの検索からダウンロード、会話形式への前処理、PEFT/LoRAによる学習までを効率的に行うSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o kaggle-finetune.zip https://jpskill.com/download/15035.zip && unzip -o kaggle-finetune.zip && rm kaggle-finetune.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15035.zip -OutFile "$d\kaggle-finetune.zip"; Expand-Archive "$d\kaggle-finetune.zip" -DestinationPath $d -Force; ri "$d\kaggle-finetune.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して kaggle-finetune.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → kaggle-finetune フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Kaggle ファイン・チューニング・ワークフロー

概要

Kaggle データセットのダウンロードと LLM のファイン・チューニングのための完全なパイプラインです。データセットの発見、Kaggle CLI を介したダウンロード、HuggingFace チャット形式への前処理、およびメモリ効率の良いファイン・チューニングのための PEFT/LoRA を使用したトレーニングを処理します。

前提条件

pip install kaggle peft transformers accelerate bitsandbytes datasets trl

Kaggle API トークンを設定します:

export KAGGLE_API_TOKEN=KGAT_xxxxx

手順

ステップ 1: データセットの検索とダウンロード

# 関連するデータセットを検索
kaggle datasets list -s "customer service conversation" --sort-by votes

# 特定のデータセットをダウンロード
kaggle datasets download -d bitext/bitext-gen-ai-chatbot-customer-support-dataset -p ./data --unzip

チャットボットに推奨されるデータセット:

データセット ユースケース
bitext/bitext-gen-ai-chatbot-customer-support-dataset カスタマーサポート
kreeshrajani/3k-conversations-dataset-for-chatbot 一般的なチャット
oleksiymaliovanyy/call-center-transcripts-dataset コールセンター
narendrageek/mental-health-faq-for-chatbot FAQ 形式

ステップ 2: チャット形式への前処理

データを HuggingFace メッセージ形式に変換します:

import pandas as pd
import json

def convert_to_chat_format(input_path, output_path, user_col, assistant_col, system_prompt=None):
    df = pd.read_csv(input_path)
    records = []

    for _, row in df.iterrows():
        messages = []
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        messages.append({"role": "user", "content": str(row[user_col])})
        messages.append({"role": "assistant", "content": str(row[assistant_col])})
        records.append({"messages": messages})

    with open(output_path, 'w') as f:
        for record in records:
            f.write(json.dumps(record) + '\n')

    return len(records)

# 使用例
convert_to_chat_format(
    "data/customer_support.csv", "data/train.jsonl",
    user_col="instruction", assistant_col="response",
    system_prompt="You are a helpful customer service assistant."
)

ステップ 3: LoRA を使用したファイン・チューニング

from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, TaskType
from trl import SFTTrainer, SFTConfig
import torch

# VRAM によるモデル選択: 8GB→1.5B, 16GB→7B(4-bit), 24GB→8B
model_name = "Qwen/Qwen2.5-3B-Instruct"

# メモリ効率のための 4-bit 量子化
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

model = AutoModelForCausalLM.from_pretrained(
    model_name, quantization_config=bnb_config, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token

lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM, r=16, lora_alpha=32, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
)

dataset = load_dataset("json", data_files="data/train.jsonl", split="train")

trainer = SFTTrainer(
    model=model,
    args=SFTConfig(
        output_dir="./model-finetune", num_train_epochs=3,
        per_device_train_batch_size=2, gradient_accumulation_steps=8,
        learning_rate=2e-4, fp16=True, max_seq_length=512,
    ),
    train_dataset=dataset,
    peft_config=lora_config,
    tokenizer=tokenizer,
)
trainer.train()
trainer.save_model("./model-lora")

ステップ 4: テストとデプロイ

from peft import PeftModel

model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
model = PeftModel.from_pretrained(model, "./model-lora")

messages = [{"role": "user", "content": "How can I reset my password?"}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

例 1: Kaggle データセットからカスタマーサービス・チャットボットをファイン・チューニングする

ユーザープロンプト: "Kaggle から Bitext カスタマーサポート・データセットをダウンロードし、LoRA を使用して Qwen2.5-3B-Instruct をファイン・チューニングします。16GB の GPU があります。"

エージェントは以下を行います:

  1. Kaggle CLI がインストールされ、KAGGLE_API_TOKEN が設定されていることを確認します。
  2. kaggle datasets download -d bitext/bitext-gen-ai-chatbot-customer-support-dataset -p ./data --unzip を実行して、データセットを取得します。
  3. CSV カラムを調べて、ユーザー入力フィールドとアシスタント応答フィールドを特定します。
  4. CSV を JSONL チャット形式に変換する前処理スクリプトを、"You are a helpful customer service assistant." のようなシステムプロンプトとともに作成して実行します。
  5. r=16、4-bit 量子化、バッチサイズ 2 と勾配累積 8 を使用して LoRA ファイン・チューニングを構成し、3 エポックトレーニングします。
  6. LoRA アダプターを ./model-lora/ に保存し、"How do I reset my password?" のようなサンプルプロンプトでテスト推論を実行します。

例 2: Kaggle メンタルヘルスデータから医療 FAQ チャットボットを構築する

ユーザープロンプト: "Kaggle でメンタルヘルス FAQ データセットを見つけて、ファイン・チューニングの準備をします。CPU しかないので、小さなモデルを選んでください。"

エージェントは以下を行います:

  1. kaggle datasets list -s "mental health FAQ" --sort-by votes で Kaggle を検索し、適切なデータセットを選択します。
  2. データセットをダウンロードして ./data/ に解凍します。
  3. FAQ ペアを、メンタルヘルスサポートに適したシステムプロンプトとともに JSONL チャット形式に変換します。
  4. CPU フレンドリーなモデルとして Qwen2.5-1.5B-Instruct を選択し、load_in_4bit=True、バッチサイズ 1、勾配累積 16、およびメモリに収まるように max_seq_length=256 でトレーニングを構成します。
  5. トレーニングを開始し、損失を監視します。CPU では数時間かかることに注意してください。

ガイドライン

  • ダウンロードを試みる前に、Kaggle API トークンが KAGGLE_API_TOKEN として設定されていることを常に確認してください。CLI は、設定されていない場合、何も表示せずに失敗するか、不可解なエラーが発生します。
  • 利用可能な VRAM に基づいてベースモデルを選択してください:

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Kaggle Fine-Tuning Workflow

Overview

Complete pipeline for downloading Kaggle datasets and fine-tuning LLMs. Handles dataset discovery, download via Kaggle CLI, preprocessing into HuggingFace chat format, and training with PEFT/LoRA for memory-efficient fine-tuning.

Prerequisites

pip install kaggle peft transformers accelerate bitsandbytes datasets trl

Set Kaggle API token:

export KAGGLE_API_TOKEN=KGAT_xxxxx

Instructions

Step 1: Search and download datasets

# Search for relevant datasets
kaggle datasets list -s "customer service conversation" --sort-by votes

# Download specific dataset
kaggle datasets download -d bitext/bitext-gen-ai-chatbot-customer-support-dataset -p ./data --unzip

Recommended datasets for chatbots:

Dataset Use Case
bitext/bitext-gen-ai-chatbot-customer-support-dataset Customer support
kreeshrajani/3k-conversations-dataset-for-chatbot General chat
oleksiymaliovanyy/call-center-transcripts-dataset Call center
narendrageek/mental-health-faq-for-chatbot FAQ format

Step 2: Preprocess into chat format

Convert data to HuggingFace messages format:

import pandas as pd
import json

def convert_to_chat_format(input_path, output_path, user_col, assistant_col, system_prompt=None):
    df = pd.read_csv(input_path)
    records = []

    for _, row in df.iterrows():
        messages = []
        if system_prompt:
            messages.append({"role": "system", "content": system_prompt})
        messages.append({"role": "user", "content": str(row[user_col])})
        messages.append({"role": "assistant", "content": str(row[assistant_col])})
        records.append({"messages": messages})

    with open(output_path, 'w') as f:
        for record in records:
            f.write(json.dumps(record) + '\n')

    return len(records)

# Example usage
convert_to_chat_format(
    "data/customer_support.csv", "data/train.jsonl",
    user_col="instruction", assistant_col="response",
    system_prompt="You are a helpful customer service assistant."
)

Step 3: Fine-tune with LoRA

from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, TaskType
from trl import SFTTrainer, SFTConfig
import torch

# Model selection by VRAM: 8GB→1.5B, 16GB→7B(4-bit), 24GB→8B
model_name = "Qwen/Qwen2.5-3B-Instruct"

# 4-bit quantization for memory efficiency
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

model = AutoModelForCausalLM.from_pretrained(
    model_name, quantization_config=bnb_config, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token

lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM, r=16, lora_alpha=32, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
)

dataset = load_dataset("json", data_files="data/train.jsonl", split="train")

trainer = SFTTrainer(
    model=model,
    args=SFTConfig(
        output_dir="./model-finetune", num_train_epochs=3,
        per_device_train_batch_size=2, gradient_accumulation_steps=8,
        learning_rate=2e-4, fp16=True, max_seq_length=512,
    ),
    train_dataset=dataset,
    peft_config=lora_config,
    tokenizer=tokenizer,
)
trainer.train()
trainer.save_model("./model-lora")

Step 4: Test and deploy

from peft import PeftModel

model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
model = PeftModel.from_pretrained(model, "./model-lora")

messages = [{"role": "user", "content": "How can I reset my password?"}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

Examples

Example 1: Fine-tune a customer service chatbot from a Kaggle dataset

User prompt: "Download the Bitext customer support dataset from Kaggle and fine-tune Qwen2.5-3B-Instruct on it using LoRA. I have a 16GB GPU."

The agent will:

  1. Verify the Kaggle CLI is installed and KAGGLE_API_TOKEN is set.
  2. Run kaggle datasets download -d bitext/bitext-gen-ai-chatbot-customer-support-dataset -p ./data --unzip to fetch the dataset.
  3. Inspect the CSV columns to identify the user input and assistant response fields.
  4. Write and execute a preprocessing script that converts the CSV into JSONL chat format with a system prompt like "You are a helpful customer service assistant."
  5. Configure a LoRA fine-tune with r=16, 4-bit quantization, batch size 2 with gradient accumulation of 8, and train for 3 epochs.
  6. Save the LoRA adapter to ./model-lora/ and run a test inference with a sample prompt like "How do I reset my password?"

Example 2: Build a medical FAQ chatbot from Kaggle mental health data

User prompt: "Find a mental health FAQ dataset on Kaggle and prepare it for fine-tuning. I only have a CPU, so pick a small model."

The agent will:

  1. Search Kaggle with kaggle datasets list -s "mental health FAQ" --sort-by votes and select an appropriate dataset.
  2. Download and unzip the dataset to ./data/.
  3. Convert the FAQ pairs into JSONL chat format with a system prompt suited to mental health support.
  4. Select Qwen2.5-1.5B-Instruct as a CPU-friendly model and configure training with load_in_4bit=True, batch size 1, gradient accumulation 16, and max_seq_length=256 to fit in memory.
  5. Start training and monitor loss, noting it will take several hours on CPU.

Guidelines

  • Always verify the Kaggle API token is set as KAGGLE_API_TOKEN before attempting downloads; the CLI will fail silently or with cryptic errors without it.
  • Choose your base model based on available VRAM: 1.5B parameters for 8GB, 3B-7B (4-bit) for 16GB, and 8B for 24GB.
  • If you encounter out-of-memory errors during training, reduce per_device_train_batch_size to 1 and increase gradient_accumulation_steps to compensate before reducing model size.
  • Inspect the raw CSV data before preprocessing to verify column names and data quality; missing values or mismatched columns will silently produce poor training data.
  • Start with 3 training epochs and LoRA rank r=16; increase epochs to 5 and rank to 32-64 only if evaluation shows the model is underfitting.
  • Enable fp16=True (or bf16=True on Ampere+ GPUs) to halve memory usage and speed up training with minimal accuracy impact.