transformers_doc/ja/translation.ipynb (836 lines of code) (raw):
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Translation"
]
},
{
"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/1JvfrvZgi6c?rel=0&controls=0&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/1JvfrvZgi6c?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"翻訳では、一連のテキストをある言語から別の言語に変換します。これは、シーケンス間問題として定式化できるいくつかのタスクの 1 つであり、翻訳や要約など、入力から何らかの出力を返すための強力なフレームワークです。翻訳システムは通常、異なる言語のテキスト間の翻訳に使用されますが、音声、またはテキストから音声への変換や音声からテキストへの変換など、音声間の組み合わせにも使用できます。\n",
"\n",
"このガイドでは、次の方法を説明します。\n",
"\n",
"1. [OPUS Books](https://huggingface.co/datasets/opus_books) データセットの英語-フランス語サブセットの [T5](https://huggingface.co/google-t5/t5-small) を微調整して、英語のテキストを次の形式に翻訳します。フランス語。\n",
"2. 微調整されたモデルを推論に使用します。\n",
"\n",
"<Tip>\n",
"\n",
"このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、[タスクページ](https://huggingface.co/tasks/translation) を確認することをお勧めします。\n",
"\n",
"</Tip>\n",
"\n",
"始める前に、必要なライブラリがすべてインストールされていることを確認してください。\n",
"\n",
"```bash\n",
"pip install transformers datasets evaluate sacrebleu\n",
"```\n",
"\n",
"モデルをアップロードしてコミュニティと共有できるように、Hugging Face アカウントにログインすることをお勧めします。プロンプトが表示されたら、トークンを入力してログインします。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from huggingface_hub import notebook_login\n",
"\n",
"notebook_login()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load OPUS Books dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"まず、🤗 データセット ライブラリから [OPUS Books](https://huggingface.co/datasets/opus_books) データセットの英語とフランス語のサブセットを読み込みます。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"\n",
"books = load_dataset(\"opus_books\", \"en-fr\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`train_test_split` メソッドを使用して、データセットをトレイン セットとテスト セットに分割します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"books = books[\"train\"].train_test_split(test_size=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に、例を見てみましょう。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'id': '90560',\n",
" 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.',\n",
" 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientôt nous fûmes rentrés dans notre élément.'}}"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"books[\"train\"][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`translation`: テキストの英語とフランス語の翻訳。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preprocess"
]
},
{
"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/XAR8jnZZuUs?rel=0&controls=0&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/XAR8jnZZuUs?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次のステップでは、T5 トークナイザーをロードして英語とフランス語の言語ペアを処理します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"checkpoint = \"google-t5/t5-small\"\n",
"tokenizer = AutoTokenizer.from_pretrained(checkpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"作成する前処理関数は次のことを行う必要があります。\n",
"\n",
"1. T5 がこれが翻訳タスクであることを認識できるように、入力の前にプロンプトを付けます。複数の NLP タスクが可能な一部のモデルでは、特定のタスクのプロンプトが必要です。\n",
"2. 英語の語彙で事前トレーニングされたトークナイザーを使用してフランス語のテキストをトークン化することはできないため、入力 (英語) とターゲット (フランス語) を別々にトークン化します。\n",
"3. `max_length`パラメータで設定された最大長を超えないようにシーケンスを切り詰めます。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"source_lang = \"en\"\n",
"target_lang = \"fr\"\n",
"prefix = \"translate English to French: \"\n",
"\n",
"\n",
"def preprocess_function(examples):\n",
" inputs = [prefix + example[source_lang] for example in examples[\"translation\"]]\n",
" targets = [example[target_lang] for example in examples[\"translation\"]]\n",
" model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)\n",
" return model_inputs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"データセット全体に前処理関数を適用するには、🤗 Datasets `map` メソッドを使用します。 `batched=True` を設定してデータセットの複数の要素を一度に処理することで、`map` 関数を高速化できます。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tokenized_books = books.map(preprocess_function, batched=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に、`DataCollatorForSeq2Seq` を使用してサンプルのバッチを作成します。データセット全体を最大長までパディングするのではなく、照合中にバッチ内の最長の長さまで文を *動的にパディング* する方が効率的です。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import DataCollatorForSeq2Seq\n",
"\n",
"data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import DataCollatorForSeq2Seq\n",
"\n",
"data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors=\"tf\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"トレーニング中にメトリクスを含めると、多くの場合、モデルのパフォーマンスを評価するのに役立ちます。 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) ライブラリを使用して、評価メソッドをすばやくロードできます。このタスクでは、[SacreBLEU](https://huggingface.co/spaces/evaluate-metric/sacrebleu) メトリクスをロードします (🤗 Evaluate [クイック ツアー](https://huggingface.co/docs/evaluate/a_quick_tour) を参照してください) ) メトリクスの読み込みと計算方法の詳細については、次を参照してください)。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import evaluate\n",
"\n",
"metric = evaluate.load(\"sacrebleu\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に、予測とラベルを `compute` に渡して SacreBLEU スコアを計算する関数を作成します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"\n",
"def postprocess_text(preds, labels):\n",
" preds = [pred.strip() for pred in preds]\n",
" labels = [[label.strip()] for label in labels]\n",
"\n",
" return preds, labels\n",
"\n",
"\n",
"def compute_metrics(eval_preds):\n",
" preds, labels = eval_preds\n",
" if isinstance(preds, tuple):\n",
" preds = preds[0]\n",
" decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n",
"\n",
" labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n",
" decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n",
"\n",
" decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)\n",
"\n",
" result = metric.compute(predictions=decoded_preds, references=decoded_labels)\n",
" result = {\"bleu\": result[\"score\"]}\n",
"\n",
" prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]\n",
" result[\"gen_len\"] = np.mean(prediction_lens)\n",
" result = {k: round(v, 4) for k, v in result.items()}\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"これで`compute_metrics`関数の準備が整いました。トレーニングをセットアップするときにこの関数に戻ります。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer) を使用したモデルの微調整に慣れていない場合は、[ここ](https://huggingface.co/docs/transformers/main/ja/tasks/../training#train-with-pytorch-trainer) の基本的なチュートリアルをご覧ください。\n",
"\n",
"</Tip>\n",
"\n",
"これでモデルのトレーニングを開始する準備が整いました。 [AutoModelForSeq2SeqLM](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForSeq2SeqLM) を使用して T5 をロードします。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer\n",
"\n",
"model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"この時点で残っているステップは 3 つだけです。\n",
"\n",
"1. [Seq2SeqTrainingArguments](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Seq2SeqTrainingArguments) でトレーニング ハイパーパラメータを定義します。唯一の必須パラメータは、モデルの保存場所を指定する `output_dir` です。 `push_to_hub=True`を設定して、このモデルをハブにプッシュします (モデルをアップロードするには、Hugging Face にサインインする必要があります)。各エポックの終了時に、[Trainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer) は SacreBLEU メトリクスを評価し、トレーニング チェックポイントを保存します。\n",
"2. トレーニング引数をモデル、データセット、トークナイザー、データ照合器、および `compute_metrics` 関数とともに [Seq2SeqTrainer](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Seq2SeqTrainer) に渡します。\n",
"3. [train()](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer.train) を呼び出してモデルを微調整します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"training_args = Seq2SeqTrainingArguments(\n",
" output_dir=\"my_awesome_opus_books_model\",\n",
" eval_strategy=\"epoch\",\n",
" learning_rate=2e-5,\n",
" per_device_train_batch_size=16,\n",
" per_device_eval_batch_size=16,\n",
" weight_decay=0.01,\n",
" save_total_limit=3,\n",
" num_train_epochs=2,\n",
" predict_with_generate=True,\n",
" fp16=True,\n",
" push_to_hub=True,\n",
")\n",
"\n",
"trainer = Seq2SeqTrainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=tokenized_books[\"train\"],\n",
" eval_dataset=tokenized_books[\"test\"],\n",
" processing_class=tokenizer,\n",
" data_collator=data_collator,\n",
" compute_metrics=compute_metrics,\n",
")\n",
"\n",
"trainer.train()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"トレーニングが完了したら、 [push_to_hub()](https://huggingface.co/docs/transformers/main/ja/main_classes/trainer#transformers.Trainer.push_to_hub) メソッドを使用してモデルをハブに共有し、誰もがモデルを使用できるようにします。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer.push_to_hub()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"Keras を使用したモデルの微調整に慣れていない場合は、[こちら](https://huggingface.co/docs/transformers/main/ja/tasks/../training#train-a-tensorflow-model-with-keras) の基本的なチュートリアルをご覧ください。\n",
"\n",
"</Tip>\n",
"TensorFlow でモデルを微調整するには、オプティマイザー関数、学習率スケジュール、およびいくつかのトレーニング ハイパーパラメーターをセットアップすることから始めます。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AdamWeightDecay\n",
"\n",
"optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に、[TFAutoModelForSeq2SeqLM](https://huggingface.co/docs/transformers/main/ja/model_doc/auto#transformers.TFAutoModelForSeq2SeqLM) を使用して T5 をロードできます。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import TFAutoModelForSeq2SeqLM\n",
"\n",
"model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[prepare_tf_dataset()](https://huggingface.co/docs/transformers/main/ja/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset) を使用して、データセットを `tf.data.Dataset` 形式に変換します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tf_train_set = model.prepare_tf_dataset(\n",
" tokenized_books[\"train\"],\n",
" shuffle=True,\n",
" batch_size=16,\n",
" collate_fn=data_collator,\n",
")\n",
"\n",
"tf_test_set = model.prepare_tf_dataset(\n",
" tokenized_books[\"test\"],\n",
" shuffle=False,\n",
" batch_size=16,\n",
" collate_fn=data_collator,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[`compile`](https://keras.io/api/models/model_training_apis/#compile-method) を使用してトレーニング用のモデルを設定します。 Transformers モデルにはすべてデフォルトのタスク関連の損失関数があるため、次の場合を除き、損失関数を指定する必要はないことに注意してください。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"\n",
"model.compile(optimizer=optimizer) # No loss argument!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"トレーニングを開始する前にセットアップする最後の 2 つのことは、予測から SacreBLEU メトリクスを計算し、モデルをハブにプッシュする方法を提供することです。どちらも [Keras コールバック](https://huggingface.co/docs/transformers/main/ja/tasks/../main_classes/keras_callbacks) を使用して行われます。\n",
"\n",
"`compute_metrics` 関数を [KerasMetricCallback](https://huggingface.co/docs/transformers/main/ja/main_classes/keras_callbacks#transformers.KerasMetricCallback) に渡します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers.keras_callbacks import KerasMetricCallback\n",
"\n",
"metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[PushToHubCallback](https://huggingface.co/docs/transformers/main/ja/main_classes/keras_callbacks#transformers.PushToHubCallback) でモデルとトークナイザーをプッシュする場所を指定します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers.keras_callbacks import PushToHubCallback\n",
"\n",
"push_to_hub_callback = PushToHubCallback(\n",
" output_dir=\"my_awesome_opus_books_model\",\n",
" tokenizer=tokenizer,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に、コールバックをまとめてバンドルします。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"callbacks = [metric_callback, push_to_hub_callback]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ついに、モデルのトレーニングを開始する準備が整いました。トレーニングおよび検証データセット、エポック数、コールバックを指定して [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) を呼び出し、モデルを微調整します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"トレーニングが完了すると、モデルは自動的にハブにアップロードされ、誰でも使用できるようになります。\n",
"\n",
"\n",
"<Tip>\n",
"\n",
"翻訳用にモデルを微調整する方法の詳細な例については、対応するドキュメントを参照してください。\n",
"[PyTorch ノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb)\n",
"または [TensorFlow ノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)。\n",
"\n",
"</Tip>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"モデルを微調整したので、それを推論に使用できるようになりました。\n",
"\n",
"別の言語に翻訳したいテキストを考え出します。 T5 の場合、作業中のタスクに応じて入力に接頭辞を付ける必要があります。英語からフランス語に翻訳する場合は、以下に示すように入力に接頭辞を付ける必要があります。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text = \"translate English to French: Legumes share resources with nitrogen-fixing bacteria.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"推論用に微調整されたモデルを試す最も簡単な方法は、それを [pipeline()](https://huggingface.co/docs/transformers/main/ja/main_classes/pipelines#transformers.pipeline) で使用することです。モデルを使用して翻訳用の`pipeline`をインスタンス化し、テキストをそれに渡します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"# Change `xx` to the language of the input and `yy` to the language of the desired output.\n",
"# Examples: \"en\" for English, \"fr\" for French, \"de\" for German, \"es\" for Spanish, \"zh\" for Chinese, etc; translation_en_to_fr translates English to French\n",
"# You can view all the lists of languages here - https://huggingface.co/languages"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from transformers import pipeline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}]"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"translator = pipeline(\"translation_xx_to_yy\", model=\"my_awesome_opus_books_model\")\n",
"translator(text)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"必要に応じて、`pipeline`の結果を手動で複製することもできます。\n",
"\n",
"\n",
"テキストをトークン化し、`input_ids` を PyTorch テンソルとして返します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"my_awesome_opus_books_model\")\n",
"inputs = tokenizer(text, return_tensors=\"pt\").input_ids"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[generate()](https://huggingface.co/docs/transformers/main/ja/main_classes/text_generation#transformers.GenerationMixin.generate) メソッドを使用して翻訳を作成します。さまざまなテキスト生成戦略と生成を制御するためのパラメーターの詳細については、[Text Generation](https://huggingface.co/docs/transformers/main/ja/tasks/../main_classes/text_generation) API を確認してください。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSeq2SeqLM\n",
"\n",
"model = AutoModelForSeq2SeqLM.from_pretrained(\"my_awesome_opus_books_model\")\n",
"outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"生成されたトークン ID をデコードしてテキストに戻します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Les lignées partagent des ressources avec des bactéries enfixant l'azote.'"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokenizer.decode(outputs[0], skip_special_tokens=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`input_ids`を TensorFlow テンソルとして返します。 tensors:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"my_awesome_opus_books_model\")\n",
"inputs = tokenizer(text, return_tensors=\"tf\").input_ids"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`~transformers.generation_tf_utils.TFGenerationMixin.generate` メソッドを使用して翻訳を作成します。さまざまなテキスト生成戦略と生成を制御するためのパラメーターの詳細については、[Text Generation](https://huggingface.co/docs/transformers/main/ja/tasks/../main_classes/text_generation) API を確認してください。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import TFAutoModelForSeq2SeqLM\n",
"\n",
"model = TFAutoModelForSeq2SeqLM.from_pretrained(\"my_awesome_opus_books_model\")\n",
"outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"生成されたトークン ID をデコードしてテキストに戻します。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.'"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokenizer.decode(outputs[0], skip_special_tokens=True)"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}