transformers_doc/ja/pytorch/quicktour.ipynb (894 lines of code) (raw):

{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Quick tour" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "🤗 Transformersを使い始めましょう! 開発者であろうと、日常的なユーザーであろうと、このクイックツアーは\n", "初めて始めるのを支援し、[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)を使った推論方法、[AutoClass](https://huggingface.co/docs/transformers/main/ja/./model_doc/auto)で事前学習済みモデルとプリプロセッサをロードする方法、\n", "そしてPyTorchまたはTensorFlowで素早くモデルをトレーニングする方法を示します。 初心者の場合、ここで紹介されたコンセプトの詳細な説明を提供する\n", "チュートリアルまたは[コース](https://huggingface.co/course/chapter1/1)を次に参照することをお勧めします。\n", "\n", "始める前に、必要なライブラリがすべてインストールされていることを確認してください:\n", "\n", "```bash\n", "!pip install transformers datasets evaluate accelerate\n", "```\n", "\n", "あなたはまた、好きな機械学習フレームワークをインストールする必要があります:\n", "\n", "\n", "```bash\n", "pip install torch\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "hide_input": true }, "outputs": [ { "data": { "text/html": [ "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/tiZFewofSLM?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#@title\n", "from IPython.display import HTML\n", "\n", "HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/tiZFewofSLM?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) は、事前学習済みモデルを推論に最も簡単で高速な方法です。\n", "[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) を使用することで、さまざまなモダリティにわたる多くのタスクに対して即座に使用できます。\n", "いくつかのタスクは以下の表に示されています:\n", "\n", "<Tip>\n", "\n", "使用可能なタスクの完全な一覧については、[pipeline API リファレンス](https://huggingface.co/docs/transformers/main/ja/./main_classes/pipelines)を確認してください。\n", "\n", "</Tip>\n", "\n", "| **タスク** | **説明** | **モダリティ** | **パイプライン識別子** |\n", "|------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|-----------------------------------------------|\n", "| テキスト分類 | テキストのシーケンスにラベルを割り当てる | NLP | pipeline(task=\"sentiment-analysis\") |\n", "| テキスト生成 | プロンプトを指定してテキストを生成する | NLP | pipeline(task=\"text-generation\") |\n", "| 要約 | テキストまたはドキュメントの要約を生成する | NLP | pipeline(task=\"summarization\") |\n", "| 画像分類 | 画像にラベルを割り当てる | コンピュータビジョン | pipeline(task=\"image-classification\") |\n", "| 画像セグメンテーション | 画像の各個別のピクセルにラベルを割り当てる(セマンティック、パノプティック、およびインスタンスセグメンテーションをサポート) | コンピュータビジョン | pipeline(task=\"image-segmentation\") |\n", "| オブジェクト検出 | 画像内のオブジェクトの境界ボックスとクラスを予測する | コンピュータビジョン | pipeline(task=\"object-detection\") |\n", "| オーディオ分類 | オーディオデータにラベルを割り当てる | オーディオ | pipeline(task=\"audio-classification\") |\n", "| 自動音声認識 | 音声をテキストに変換する | オーディオ | pipeline(task=\"automatic-speech-recognition\") |\n", "| ビジュアルクエスチョン応答 | 画像と質問が与えられた場合に、画像に関する質問に回答する | マルチモーダル | pipeline(task=\"vqa\") |\n", "| ドキュメントクエスチョン応答 | ドキュメントと質問が与えられた場合に、ドキュメントに関する質問に回答する | マルチモーダル | pipeline(task=\"document-question-answering\") |\n", "| 画像キャプショニング | 与えられた画像にキャプションを生成する | マルチモーダル | pipeline(task=\"image-to-text\") |\n", "\n", "まず、[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) のインスタンスを作成し、使用したいタスクを指定します。\n", "このガイドでは、センチメント分析のために [pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) を使用する例を示します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import pipeline\n", "\n", "classifier = pipeline(\"sentiment-analysis\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)は、感情分析のためのデフォルトの[事前学習済みモデル](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english)とトークナイザをダウンロードしてキャッシュし、使用できるようになります。\n", "これで、`classifier`を対象のテキストに使用できます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'label': 'POSITIVE', 'score': 0.9998}]" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "classifier(\"私たちは🤗 Transformersライブラリをお見せできてとても嬉しいです。\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "複数の入力がある場合は、[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)に入力をリストとして渡して、辞書のリストを返します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "label: POSITIVE, スコア: 0.9998\n", "label: NEGATIVE, スコア: 0.5309" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results = classifier([\"🤗 Transformersライブラリをご紹介できて非常に嬉しいです。\", \"嫌いにならないでほしいです。\"])\n", "for result in results:\n", " print(f\"label: {result['label']}, スコア: {round(result['score'], 4)}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)は、任意のタスクに対してデータセット全体を繰り返し処理することもできます。この例では、自動音声認識をタスクとして選びましょう:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import pipeline\n", "\n", "speech_recognizer = pipeline(\"automatic-speech-recognition\", model=\"facebook/wav2vec2-base-960h\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "オーディオデータセットをロードします(詳細については🤗 Datasets [クイックスタート](https://huggingface.co/docs/datasets/quickstart#audio)を参照してください)。\n", "たとえば、[MInDS-14](https://huggingface.co/datasets/PolyAI/minds14)データセットをロードします:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from datasets import load_dataset, Audio\n", "\n", "dataset = load_dataset(\"PolyAI/minds14\", name=\"en-US\", split=\"train\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "データセットのサンプリングレートが[`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h)がトレーニングされたサンプリングレートと一致することを確認してください:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"audio\"列を呼び出すと、オーディオファイルは自動的にロードされ、リサンプリングされます。最初の4つのサンプルから生の波形配列を抽出し、それをパイプラインにリストとして渡します。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', \"FONDERING HOW I'D SET UP A JOIN TO HELL T WITH MY WIFE AND WHERE THE AP MIGHT BE\", \"I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE APSO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AN I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS\", 'HOW DO I FURN A JOINA COUT']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result = speech_recognizer(dataset[:4][\"audio\"])\n", "print([d[\"text\"] for d in result])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "大規模なデータセットで、入力が大きい場合(音声や画像など)、すべての入力をメモリに読み込む代わりに、リストではなくジェネレータを渡すことがお勧めです。詳細については[パイプラインAPIリファレンス](https://huggingface.co/docs/transformers/main/ja/./main_classes/pipelines)を参照してください。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Use another model and tokenizer in the pipeline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)は[Hub](https://huggingface.co/models)からの任意のモデルを収容でき、他のユースケースに[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)を適応させることが容易です。たとえば、フランス語のテキストを処理できるモデルが必要な場合、Hubのタグを使用して適切なモデルをフィルタリングできます。トップのフィルタリングされた結果は、フランス語のテキストに使用できる感情分析用に調整された多言語の[BERTモデル](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment)を返します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForSequenceClassification)と[AutoTokenizer](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer)を使用して事前学習済みモデルとそれに関連するトークナイザをロードします(次のセクションで`AutoClass`について詳しく説明します):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer, AutoModelForSequenceClassification\n", "\n", "model = AutoModelForSequenceClassification.from_pretrained(model_name)\n", "tokenizer = AutoTokenizer.from_pretrained(model_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "指定したモデルとトークナイザを[pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline)に設定し、今度はフランス語のテキストに`classifier`を適用できます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'label': '5 stars', 'score': 0.7273}]" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "classifier = pipeline(\"sentiment-analysis\", model=model, tokenizer=tokenizer)\n", "classifier(\"Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "もし、あなたのユースケースに適したモデルが見つからない場合、事前学習済みモデルをあなたのデータでファインチューニングする必要があります。\n", "ファインチューニングの方法については、[ファインチューニングのチュートリアル](https://huggingface.co/docs/transformers/main/ja/./training)をご覧ください。\n", "最後に、ファインチューニングした事前学習済みモデルを共有し、コミュニティと共有ハブで共有することを検討してください。これにより、機械学習を民主化する手助けができます! 🤗" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AutoClass" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "hide_input": true }, "outputs": [ { "data": { "text/html": [ "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/AhChOFRegn4?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>" ], "text/plain": [ "<IPython.core.display.HTML object>" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#@title\n", "from IPython.display import HTML\n", "\n", "HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/AhChOFRegn4?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForSequenceClassification) および [AutoTokenizer](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) クラスは、上記で使用した [pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) を駆動するために協力して動作します。\n", "[AutoClass](https://huggingface.co/docs/transformers/main/ja/./model_doc/auto) は、事前学習済みモデルのアーキテクチャをその名前またはパスから自動的に取得するショートカットです。\n", "適切な `AutoClass` を選択し、それに関連する前処理クラスを選択するだけで済みます。\n", "\n", "前のセクションからの例に戻り、`AutoClass` を使用して [pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) の結果を再現する方法を見てみましょう。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### AutoTokenizer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "トークナイザはテキストをモデルの入力として使用できる数値の配列に前処理する役割を果たします。\n", "トークナイゼーションプロセスには、単語をどのように分割するかや、単語をどのレベルで分割するかといった多くのルールがあります\n", "(トークナイゼーションについての詳細は [トークナイザサマリー](https://huggingface.co/docs/transformers/main/ja/./tokenizer_summary) をご覧ください)。\n", "最も重要なことは、モデルが事前学習済みになったときと同じトークナイゼーションルールを使用するために、同じモデル名でトークナイザをインスタンス化する必要があることです。\n", "\n", "[AutoTokenizer](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用してトークナイザをロードします:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\"\n", "tokenizer = AutoTokenizer.from_pretrained(model_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pass your text to the tokenizer:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],\n", " 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", " 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "encoding = tokenizer(\"私たちは🤗 Transformersライブラリをお見せできてとても嬉しいです。\")\n", "print(encoding)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "トークナイザは、次の情報を含む辞書を返します:\n", "\n", "- [input_ids](https://huggingface.co/docs/transformers/main/ja/./glossary#input-ids): トークンの数値表現。\n", "- [attention_mask](https://huggingface.co/docs/transformers/main/ja/.glossary#attention-mask): どのトークンにアテンションを向けるかを示します。\n", "\n", "トークナイザはまた、入力のリストを受け入れ、一様な長さのバッチを返すためにテキストをパディングおよび切り詰めることができます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pt_batch = tokenizer(\n", " [\"🤗 Transformersライブラリをお見せできて非常に嬉しいです。\", \"嫌いではないことを願っています。\"],\n", " padding=True,\n", " truncation=True,\n", " max_length=512,\n", " return_tensors=\"pt\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<Tip>\n", "\n", "[前処理](https://huggingface.co/docs/transformers/main/ja/./preprocessing)チュートリアルをご覧いただき、トークナイゼーションの詳細や、[AutoImageProcessor](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoImageProcessor)、[AutoFeatureExtractor](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoFeatureExtractor)、[AutoProcessor](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoProcessor)を使用して画像、オーディオ、およびマルチモーダル入力を前処理する方法について詳しく説明されているページもご覧ください。\n", "\n", "</Tip>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### AutoModel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "🤗 Transformersは事前学習済みインスタンスを簡単に統一的にロードする方法を提供します。\n", "これは、[AutoTokenizer](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer)をロードするのと同じように[AutoModel](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)をロードできることを意味します。\n", "タスクに適した[AutoModel](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)を選択する以外の違いはありません。\n", "テキスト(またはシーケンス)分類の場合、[AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForSequenceClassification)をロードする必要があります:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModelForSequenceClassification\n", "\n", "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\"\n", "pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<Tip>\n", "\n", "[AutoModel](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)クラスでサポートされているタスクに関する詳細については、[タスクの概要](https://huggingface.co/docs/transformers/main/ja/./task_summary)を参照してください。\n", "\n", "</Tip>\n", "\n", "今、前処理済みのバッチを直接モデルに渡します。辞書を展開するだけで、`**`を追加する必要があります:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pt_outputs = pt_model(**pt_batch)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "モデルは、`logits`属性に最終的なアクティベーションを出力します。 `logits`にsoftmax関数を適用して確率を取得します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],\n", " [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=<SoftmaxBackward0>)" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from torch import nn\n", "\n", "pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)\n", "print(pt_predictions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<Tip>\n", "\n", "🤗 Transformersのすべてのモデル(PyTorchまたはTensorFlow)は、最終的な活性化関数(softmaxなど)*前*のテンソルを出力します。\n", "最終的な活性化関数は、しばしば損失と結合されているためです。モデルの出力は特別なデータクラスであり、その属性はIDEで自動補完されます。\n", "モデルの出力は、タプルまたは辞書のように動作します(整数、スライス、または文字列でインデックスを付けることができます)。\n", "この場合、Noneである属性は無視されます。\n", "\n", "</Tip>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Save a Model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "モデルをファインチューニングしたら、[PreTrainedModel.save_pretrained()](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.save_pretrained)を使用してトークナイザと共に保存できます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pt_save_directory = \"./pt_save_pretrained\"\n", "tokenizer.save_pretrained(pt_save_directory)\n", "pt_model.save_pretrained(pt_save_directory)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "再びモデルを使用する準備ができたら、[PreTrainedModel.from_pretrained()](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained)を使用して再度ロードします:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pt_model = AutoModelForSequenceClassification.from_pretrained(\"./pt_save_pretrained\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "🤗 Transformersの特に素晴らしい機能の一つは、モデルを保存し、それをPyTorchモデルまたはTensorFlowモデルとして再ロードできることです。 `from_pt`または`from_tf`パラメータを使用してモデルをフレームワーク間で変換できます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModel\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)\n", "pt_model = AutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Custom model builds" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "モデルを構築方法を変更するには、モデルの設定クラスを変更できます。設定はモデルの属性を指定します。例えば、隠れ層の数やアテンションヘッドの数などがこれに含まれます。カスタム設定クラスからモデルを初期化する際には、ゼロから始めます。モデルの属性はランダムに初期化され、有意義な結果を得るためにモデルをトレーニングする必要があります。\n", "\n", "最初に[AutoConfig](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoConfig)をインポートし、変更したい事前学習済みモデルをロードします。[AutoConfig.from_pretrained()](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoConfig.from_pretrained)内で、変更したい属性(例:アテンションヘッドの数)を指定できます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoConfig\n", "\n", "my_config = AutoConfig.from_pretrained(\"distilbert/distilbert-base-uncased\", n_heads=12)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[AutoModel.from_config()](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel.from_config)を使用してカスタム設定からモデルを作成します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModel\n", "\n", "my_model = AutoModel.from_config(my_config)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[カスタムアーキテクチャを作成](https://huggingface.co/docs/transformers/main/ja/./create_a_model)ガイドを参照して、カスタム構成の詳細情報を確認してください。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Trainer - PyTorch向けの最適化されたトレーニングループ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "すべてのモデルは標準の[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)であるため、通常のトレーニングループで使用できます。\n", "独自のトレーニングループを作成できますが、🤗 TransformersはPyTorch向けに[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)クラスを提供しており、基本的なトレーニングループに加えて、\n", "分散トレーニング、混合精度などの機能の追加を行っています。\n", "\n", "タスクに応じて、通常は[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)に以下のパラメータを渡します:\n", "\n", "1. [PreTrainedModel](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel)または[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)から始めます:\n", "\n", " ```py\n", " >>> from transformers import AutoModelForSequenceClassification\n", "\n", " >>> model = AutoModelForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n", " ```\n", "\n", "2. [TrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments)には、変更できるモデルのハイパーパラメータが含まれており、学習率、バッチサイズ、トレーニングエポック数などが変更できます。指定しない場合、デフォルト値が使用されます:\n", "\n", " ```py\n", " >>> from transformers import TrainingArguments\n", "\n", " >>> training_args = TrainingArguments(\n", " ... output_dir=\"path/to/save/folder/\",\n", " ... learning_rate=2e-5,\n", " ... per_device_train_batch_size=8,\n", " ... per_device_eval_batch_size=8,\n", " ... num_train_epochs=2,\n", " ... )\n", " ```\n", "\n", "3. トークナイザ、画像プロセッサ、特徴量抽出器、またはプロセッサのような前処理クラスをロードします:\n", "\n", " ```py\n", " >>> from transformers import AutoTokenizer\n", "\n", " >>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n", " ```\n", "\n", "4. データセットをロードする:\n", "\n", " ```py\n", " >>> from datasets import load_dataset\n", "\n", " >>> dataset = load_dataset(\"rotten_tomatoes\") # doctest: +IGNORE_RESULT\n", " ```\n", "\n", "5. データセットをトークン化するための関数を作成します:\n", "\n", " ```python\n", " >>> def tokenize_dataset(dataset):\n", " ... return tokenizer(dataset[\"text\"])\n", " ```\n", "\n", " その後、`map`を使用してデータセット全体に適用します:\n", "\n", " ```python\n", " >>> dataset = dataset.map(tokenize_dataset, batched=True)\n", " ```\n", "\n", "6. データセットからの例のバッチを作成するための [DataCollatorWithPadding](https://huggingface.co/docs/transformers/main/ja/main_classes/data_collator#transformers.DataCollatorWithPadding):\n", "\n", " ```py\n", " >>> from transformers import DataCollatorWithPadding\n", "\n", " >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)\n", " ```\n", "\n", "次に、これらのクラスを[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)にまとめます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import Trainer\n", "\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=dataset[\"train\"],\n", " eval_dataset=dataset[\"test\"],\n", " processing_class=tokenizer,\n", " data_collator=data_collator,\n", ") # doctest: +SKIP" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "訓練を開始する準備ができたら、[train()](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer.train)を呼び出してトレーニングを開始します:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trainer.train()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "<Tip>\n", "\n", "翻訳や要約など、シーケンス間モデルを使用するタスクには、代わりに[Seq2SeqTrainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Seq2SeqTrainer)と[Seq2SeqTrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Seq2SeqTrainingArguments)クラスを使用してください。\n", "\n", "</Tip>\n", "\n", "[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)内のメソッドをサブクラス化することで、トレーニングループの動作をカスタマイズできます。これにより、損失関数、オプティマイザ、スケジューラなどの機能をカスタマイズできます。サブクラス化できるメソッドの一覧については、[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)リファレンスをご覧ください。\n", "\n", "トレーニングループをカスタマイズする別の方法は、[Callbacks](https://huggingface.co/docs/transformers/main/ja/./main_classes/callback)を使用することです。コールバックを使用して他のライブラリと統合し、トレーニングループを監視して進捗状況を報告したり、トレーニングを早期に停止したりできます。コールバックはトレーニングループ自体には何も変更を加えません。損失関数などのカスタマイズを行う場合は、[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer)をサブクラス化する必要があります。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train with TensorFlow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "すべてのモデルは標準の[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)であるため、[Keras](https://keras.io/) APIを使用してTensorFlowでトレーニングできます。\n", "🤗 Transformersは、データセットを`tf.data.Dataset`として簡単にロードできるようにする[prepare_tf_dataset()](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset)メソッドを提供しており、Kerasの[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)および[`fit`](https://keras.io/api/models/model_training_apis/#fit-method)メソッドを使用してトレーニングをすぐに開始できます。\n", "\n", "1. [TFPreTrainedModel](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.TFPreTrainedModel)または[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)から始めます:\n", "\n", " ```py\n", " >>> from transformers import TFAutoModelForSequenceClassification\n", "\n", " >>> model = TFAutoModelForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n", " ```\n", "\n", "2. トークナイザ、画像プロセッサ、特徴量抽出器、またはプロセッサのような前処理クラスをロードします:\n", "\n", " ```py\n", " >>> from transformers import AutoTokenizer\n", "\n", " >>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n", " ```\n", "\n", "3. データセットをトークナイズするための関数を作成します:\n", "\n", " ```python\n", " >>> def tokenize_dataset(dataset):\n", " ... return tokenizer(dataset[\"text\"]) # doctest: +SKIP\n", " ```\n", "\n", "4. `map`を使用してデータセット全体にトークナイザを適用し、データセットとトークナイザを[prepare_tf_dataset()](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset)に渡します。バッチサイズを変更し、データセットをシャッフルすることもできます。\n", "\n", " ```python\n", " >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP\n", " >>> tf_dataset = model.prepare_tf_dataset(\n", " ... dataset[\"train\"], batch_size=16, shuffle=True, tokenizer=tokenizer\n", " ... ) # doctest: +SKIP\n", " ```\n", "\n", "5. 準備ができたら、`compile`と`fit`を呼び出してトレーニングを開始できます。 Transformersモデルはすべてデフォルトのタスクに関連する損失関数を持っているため、指定しない限り、損失関数を指定する必要はありません。\n", "\n", " ```python\n", " >>> from tensorflow.keras.optimizers import Adam\n", "\n", " >>> model.compile(optimizer=Adam(3e-5)) # 損失関数の引数は不要です!\n", " >>> model.fit(tf\n", " ```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What's next?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "🤗 Transformersのクイックツアーを完了したら、ガイドをチェックして、カスタムモデルの作成、タスクのためのファインチューニング、スクリプトを使用したモデルのトレーニングなど、より具体的なことを学ぶことができます。🤗 Transformersのコアコンセプトについてもっと詳しく知りたい場合は、コンセプチュアルガイドを読んでみてください!" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 4 }