微調整のための簡単なデータ準備と前処理

ファインチューニング

Posted by LuochuanAD on March 15, 2026 本文总阅读量

背景

プライベートLLMで最も重要なのは、プライベートデータを使ってLLMをファインチューニングすることです。本記事ではまずデータ準備と前処理の方法を解説します。

データ準備

スタンフォードのAlpacaトレーニングで使用されているデータセットをダウンロードすると、次のような形式のJSONファイルが得られます:
alpaca_data.json

[
    {
        "instruction": "Give three tips for staying healthy.",
        "input": "",
        "output": "1.Eat a balanced diet and make sure to include plenty of fruits and vegetables. \n2. Exercise regularly to keep your body active and strong. \n3. Get enough sleep and maintain a consistent sleep schedule."
    },
.......
    {
        "instruction": "What are the three primary colors?",
        "input": "",
        "output": "The three primary colors are red, blue, and yellow."
    }
]

データ前処理

ファインチューニングで要求されるデータ形式(基本的なSFTデータ構造)は以下の通りです:

{
	"messages":[
		{
			"role": "user",
			"content": "xxxx_question_1"
		},
		{
			"role": "assistant",
			"content": "xxxx_answer_1"
		}
	]
}

Pythonスクリプトを使って、alpaca_data.json のデータ形式をファインチューニングに必要な形式に変換します。
また、変換後のデータは訓練データセット検証データセットの2種類を用意します。(訓練:検証 = 7:3)

import json
import random

def load_data():
    with open('alpaca_data.json','r',encoding='utf-8') as f:
        data=json.load(f)
    return data

def conversion_to_jsonl(data):

    random.shuffle(data)

    split=int(len(data)*0.7)

    train=data[:split]
    valid=data[split:]

    def convert(item):
        return {
            "messages":[
                {
                    "role":"user",
                    "content":item["instruction"]+"\n"+item.get("input","")
                },
                {
                    "role":"assistant",
                    "content":item["output"]
                }
            ]
        }

    with open("train.jsonl","w",encoding="utf-8") as f:
        for item in train:
            f.write(json.dumps(convert(item),ensure_ascii=False)+"\n")

    with open("valid.jsonl","w",encoding="utf-8") as f:
        for item in valid:
            f.write(json.dumps(convert(item),ensure_ascii=False)+"\n")

if __name__ == "__main__":
    original_data = load_data()
    conversion_to_jsonl(original_data)

完全なコードは以下のリンクから参照できます:

https://github.com/LuochuanAD/Fine-tuning-Learn

参考

データソース:

スタンフォードのAlpacaトレーニングで使用されたデータセット:

https://raw.githubusercontent.com/tatsu-lab/stanford_alpaca/refs/heads/main/alpaca_data.json