{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Transformers 설치 방법\n", "! pip install transformers datasets\n", "# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n", "# ! pip install git+https://github.com/huggingface/transformers.git" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 토큰 분류[[token-classification]]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "hide_input": true }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#@title\n", "from IPython.display import HTML\n", "\n", "HTML('')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "토큰 분류는 문장의 개별 토큰에 레이블을 할당합니다. 가장 일반적인 토큰 분류 작업 중 하나는 개체명 인식(Named Entity Recognition, NER)입니다. 개체명 인식은 문장에서 사람, 위치 또는 조직과 같은 각 개체의 레이블을 찾으려고 시도합니다.\n", "\n", "이 가이드에서 학습할 내용은:\n", "\n", "1. [WNUT 17](https://huggingface.co/datasets/wnut_17) 데이터 세트에서 [DistilBERT](https://huggingface.co/distilbert-base-uncased)를 파인 튜닝하여 새로운 개체를 탐지합니다.\n", "2. 추론을 위해 파인 튜닝 모델을 사용합니다.\n", "\n", "\n", "이 튜토리얼에서 설명하는 작업은 다음 모델 아키텍처에 의해 지원됩니다:\n", "\n", "\n", "\n", "[ALBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/albert), [BERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/bert), [BigBird](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/big_bird), [BioGpt](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/biogpt), [BLOOM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/bloom), [CamemBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/camembert), [CANINE](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/canine), [ConvBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/convbert), [Data2VecText](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/data2vec-text), [DeBERTa](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/deberta), [DeBERTa-v2](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/deberta-v2), [DistilBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/distilbert), [ELECTRA](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/electra), [ERNIE](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/ernie), [ErnieM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/ernie_m), [ESM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/esm), [FlauBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/flaubert), [FNet](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/fnet), [Funnel Transformer](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/funnel), [GPT-Sw3](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/gpt-sw3), [OpenAI GPT-2](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/gpt2), [GPTBigCode](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/gpt_bigcode), [I-BERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/ibert), [LayoutLM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/layoutlm), [LayoutLMv2](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/layoutlmv2), [LayoutLMv3](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/layoutlmv3), [LiLT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/lilt), [Longformer](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/longformer), [LUKE](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/luke), [MarkupLM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/markuplm), [MEGA](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/mega), [Megatron-BERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/megatron-bert), [MobileBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/mobilebert), [MPNet](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/mpnet), [Nezha](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/nezha), [Nyströmformer](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/nystromformer), [QDQBert](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/qdqbert), [RemBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/rembert), [RoBERTa](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/roberta), [RoBERTa-PreLayerNorm](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/roberta-prelayernorm), [RoCBert](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/roc_bert), [RoFormer](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/roformer), [SqueezeBERT](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/squeezebert), [XLM](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/xlm), [XLM-RoBERTa](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/xlm-roberta), [XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/xlm-roberta-xl), [XLNet](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/xlnet), [X-MOD](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/xmod), [YOSO](https://huggingface.co/docs/transformers/main/ko/tasks/../model_doc/yoso)\n", "\n", "\n", "\n", "\n", "\n", "시작하기 전에, 필요한 모든 라이브러리가 설치되어 있는지 확인하세요:\n", "\n", "```bash\n", "pip install transformers datasets evaluate seqeval\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": [ "## WNUT 17 데이터 세트 가져오기[[load-wnut-17-dataset]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "먼저 🤗 Datasets 라이브러리에서 WNUT 17 데이터 세트를 가져옵니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from datasets import load_dataset\n", "\n", "wnut = load_dataset(\"wnut_17\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "다음 예제를 살펴보세요:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'id': '0',\n", " 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],\n", " 'tokens': ['@paulwalk', 'It', \"'s\", 'the', 'view', 'from', 'where', 'I', \"'m\", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']\n", "}" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "wnut[\"train\"][0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`ner_tags`의 각 숫자는 개체를 나타냅니다. 숫자를 레이블 이름으로 변환하여 개체가 무엇인지 확인합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[\n", " \"O\",\n", " \"B-corporation\",\n", " \"I-corporation\",\n", " \"B-creative-work\",\n", " \"I-creative-work\",\n", " \"B-group\",\n", " \"I-group\",\n", " \"B-location\",\n", " \"I-location\",\n", " \"B-person\",\n", " \"I-person\",\n", " \"B-product\",\n", " \"I-product\",\n", "]" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "label_list = wnut[\"train\"].features[f\"ner_tags\"].feature.names\n", "label_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "각 `ner_tag`의 앞에 붙은 문자는 개체의 토큰 위치를 나타냅니다:\n", "\n", "- `B-`는 개체의 시작을 나타냅니다.\n", "- `I-`는 토큰이 동일한 개체 내부에 포함되어 있음을 나타냅니다(예를 들어 `State` 토큰은 `Empire State Building`와 같은 개체의 일부입니다).\n", "- `0`는 토큰이 어떤 개체에도 해당하지 않음을 나타냅니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 전처리[[preprocess]]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "hide_input": true }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#@title\n", "from IPython.display import HTML\n", "\n", "HTML('')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "다음으로 `tokens` 필드를 전처리하기 위해 DistilBERT 토크나이저를 가져옵니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "위의 예제 `tokens` 필드를 보면 입력이 이미 토큰화된 것처럼 보입니다. 그러나 실제로 입력은 아직 토큰화되지 않았으므로 단어를 하위 단어로 토큰화하기 위해 `is_split_into_words=True`를 설정해야 합니다. 예제로 확인합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['[CLS]', '@', 'paul', '##walk', 'it', \"'\", 's', 'the', 'view', 'from', 'where', 'i', \"'\", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "example = wnut[\"train\"][0]\n", "tokenized_input = tokenizer(example[\"tokens\"], is_split_into_words=True)\n", "tokens = tokenizer.convert_ids_to_tokens(tokenized_input[\"input_ids\"])\n", "tokens" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "그러나 이로 인해 `[CLS]`과 `[SEP]`라는 특수 토큰이 추가되고, 하위 단어 토큰화로 인해 입력과 레이블 간에 불일치가 발생합니다. 하나의 레이블에 해당하는 단일 단어는 이제 두 개의 하위 단어로 분할될 수 있습니다. 토큰과 레이블을 다음과 같이 재정렬해야 합니다:\n", "\n", "1. [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) 메소드로 모든 토큰을 해당 단어에 매핑합니다.\n", "2. 특수 토큰 `[CLS]`와 `[SEP]`에 `-100` 레이블을 할당하여, PyTorch 손실 함수가 해당 토큰을 무시하도록 합니다.\n", "3. 주어진 단어의 첫 번째 토큰에만 레이블을 지정합니다. 같은 단어의 다른 하위 토큰에 `-100`을 할당합니다.\n", "\n", "다음은 토큰과 레이블을 재정렬하고 DistilBERT의 최대 입력 길이보다 길지 않도록 시퀀스를 잘라내는 함수를 만드는 방법입니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def tokenize_and_align_labels(examples):\n", " tokenized_inputs = tokenizer(examples[\"tokens\"], truncation=True, is_split_into_words=True)\n", "\n", " labels = []\n", " for i, label in enumerate(examples[f\"ner_tags\"]):\n", " word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.\n", " previous_word_idx = None\n", " label_ids = []\n", " for word_idx in word_ids: # Set the special tokens to -100.\n", " if word_idx is None:\n", " label_ids.append(-100)\n", " elif word_idx != previous_word_idx: # Only label the first token of a given word.\n", " label_ids.append(label[word_idx])\n", " else:\n", " label_ids.append(-100)\n", " previous_word_idx = word_idx\n", " labels.append(label_ids)\n", "\n", " tokenized_inputs[\"labels\"] = labels\n", " return tokenized_inputs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "전체 데이터 세트에 전처리 함수를 적용하려면, 🤗 Datasets `map` 함수를 사용하세요. `batched=True`로 설정하여 데이터 세트의 여러 요소를 한 번에 처리하면 `map` 함수의 속도를 높일 수 있습니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이제 `DataCollatorWithPadding`를 사용하여 예제 배치를 만들어봅시다. 데이터 세트 전체를 최대 길이로 패딩하는 대신, *동적 패딩*을 사용하여 배치에서 가장 긴 길이에 맞게 문장을 패딩하는 것이 효율적입니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import DataCollatorForTokenClassification\n", "\n", "data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import DataCollatorForTokenClassification\n", "\n", "data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors=\"tf\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 평가[[evaluation]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련 중 모델의 성능을 평가하기 위해 평가 지표를 포함하는 것이 유용합니다. 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 라이브러리를 사용하여 빠르게 평가 방법을 가져올 수 있습니다. 이 작업에서는 [seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) 평가 지표를 가져옵니다. (평가 지표를 가져오고 계산하는 방법에 대해서는 🤗 Evaluate [빠른 둘러보기](https://huggingface.co/docs/evaluate/a_quick_tour)를 참조하세요). Seqeval은 실제로 정밀도, 재현률, F1 및 정확도와 같은 여러 점수를 산출합니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import evaluate\n", "\n", "seqeval = evaluate.load(\"seqeval\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "먼저 NER 레이블을 가져온 다음, `compute`에 실제 예측과 실제 레이블을 전달하여 점수를 계산하는 함수를 만듭니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "labels = [label_list[i] for i in example[f\"ner_tags\"]]\n", "\n", "\n", "def compute_metrics(p):\n", " predictions, labels = p\n", " predictions = np.argmax(predictions, axis=2)\n", "\n", " true_predictions = [\n", " [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n", " for prediction, label in zip(predictions, labels)\n", " ]\n", " true_labels = [\n", " [label_list[l] for (p, l) in zip(prediction, label) if l != -100]\n", " for prediction, label in zip(predictions, labels)\n", " ]\n", "\n", " results = seqeval.compute(predictions=true_predictions, references=true_labels)\n", " return {\n", " \"precision\": results[\"overall_precision\"],\n", " \"recall\": results[\"overall_recall\"],\n", " \"f1\": results[\"overall_f1\"],\n", " \"accuracy\": results[\"overall_accuracy\"],\n", " }" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이제 `compute_metrics` 함수를 사용할 준비가 되었으며, 훈련을 설정하면 이 함수로 되돌아올 것입니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 훈련[[train]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "모델을 훈련하기 전에, `id2label`와 `label2id`를 사용하여 예상되는 id와 레이블의 맵을 생성하세요:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "id2label = {\n", " 0: \"O\",\n", " 1: \"B-corporation\",\n", " 2: \"I-corporation\",\n", " 3: \"B-creative-work\",\n", " 4: \"I-creative-work\",\n", " 5: \"B-group\",\n", " 6: \"I-group\",\n", " 7: \"B-location\",\n", " 8: \"I-location\",\n", " 9: \"B-person\",\n", " 10: \"I-person\",\n", " 11: \"B-product\",\n", " 12: \"I-product\",\n", "}\n", "label2id = {\n", " \"O\": 0,\n", " \"B-corporation\": 1,\n", " \"I-corporation\": 2,\n", " \"B-creative-work\": 3,\n", " \"I-creative-work\": 4,\n", " \"B-group\": 5,\n", " \"I-group\": 6,\n", " \"B-location\": 7,\n", " \"I-location\": 8,\n", " \"B-person\": 9,\n", " \"I-person\": 10,\n", " \"B-product\": 11,\n", " \"I-product\": 12,\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "`Trainer`를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](https://huggingface.co/docs/transformers/main/ko/tasks/../training#train-with-pytorch-trainer)에서 기본 튜토리얼을 확인하세요!\n", "\n", "\n", "\n", "이제 모델을 훈련시킬 준비가 되었습니다! `AutoModelForSequenceClassification`로 DistilBERT를 가져오고 예상되는 레이블 수와 레이블 매핑을 지정하세요:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer\n", "\n", "model = AutoModelForTokenClassification.from_pretrained(\n", " \"distilbert-base-uncased\", num_labels=13, id2label=id2label, label2id=label2id\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "이제 세 단계만 거치면 끝입니다:\n", "\n", "1. `TrainingArguments`에서 하이퍼파라미터를 정의하세요. `output_dir`는 모델을 저장할 위치를 지정하는 유일한 매개변수입니다. 이 모델을 허브에 업로드하기 위해 `push_to_hub=True`를 설정합니다(모델을 업로드하기 위해 Hugging Face에 로그인해야합니다.) 각 에폭이 끝날 때마다, `Trainer`는 seqeval 점수를 평가하고 훈련 체크포인트를 저장합니다.\n", "2. `Trainer`에 훈련 인수와 모델, 데이터 세트, 토크나이저, 데이터 콜레이터 및 `compute_metrics` 함수를 전달하세요.\n", "3. `train()`를 호출하여 모델을 파인 튜닝하세요." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_args = TrainingArguments(\n", " output_dir=\"my_awesome_wnut_model\",\n", " learning_rate=2e-5,\n", " per_device_train_batch_size=16,\n", " per_device_eval_batch_size=16,\n", " num_train_epochs=2,\n", " weight_decay=0.01,\n", " evaluation_strategy=\"epoch\",\n", " save_strategy=\"epoch\",\n", " load_best_model_at_end=True,\n", " push_to_hub=True,\n", ")\n", "\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=tokenized_wnut[\"train\"],\n", " eval_dataset=tokenized_wnut[\"test\"],\n", " tokenizer=tokenizer,\n", " data_collator=data_collator,\n", " compute_metrics=compute_metrics,\n", ")\n", "\n", "trainer.train()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련이 완료되면, `push_to_hub()` 메소드를 사용하여 모델을 허브에 공유할 수 있습니다." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trainer.push_to_hub()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Keras를 사용하여 모델을 파인 튜닝하는 방법에 익숙하지 않은 경우, [여기](https://huggingface.co/docs/transformers/main/ko/tasks/../training#train-a-tensorflow-model-with-keras)의 기본 튜토리얼을 확인하세요!\n", "\n", "\n", "TensorFlow에서 모델을 파인 튜닝하려면, 먼저 옵티마이저 함수와 학습률 스케쥴, 그리고 일부 훈련 하이퍼파라미터를 설정해야 합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import create_optimizer\n", "\n", "batch_size = 16\n", "num_train_epochs = 3\n", "num_train_steps = (len(tokenized_wnut[\"train\"]) // batch_size) * num_train_epochs\n", "optimizer, lr_schedule = create_optimizer(\n", " init_lr=2e-5,\n", " num_train_steps=num_train_steps,\n", " weight_decay_rate=0.01,\n", " num_warmup_steps=0,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "그런 다음 `TFAutoModelForSequenceClassification`을 사용하여 DistilBERT를 가져오고, 예상되는 레이블 수와 레이블 매핑을 지정합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import TFAutoModelForTokenClassification\n", "\n", "model = TFAutoModelForTokenClassification.from_pretrained(\n", " \"distilbert-base-uncased\", num_labels=13, id2label=id2label, label2id=label2id\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`prepare_tf_dataset()`을 사용하여 데이터 세트를 `tf.data.Dataset` 형식으로 변환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tf_train_set = model.prepare_tf_dataset(\n", " tokenized_wnut[\"train\"],\n", " shuffle=True,\n", " batch_size=16,\n", " collate_fn=data_collator,\n", ")\n", "\n", "tf_validation_set = model.prepare_tf_dataset(\n", " tokenized_wnut[\"validation\"],\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)를 사용하여 훈련할 모델을 구성합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import tensorflow as tf\n", "\n", "model.compile(optimizer=optimizer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련을 시작하기 전에 설정해야할 마지막 두 가지는 예측에서 seqeval 점수를 계산하고, 모델을 허브에 업로드할 방법을 제공하는 것입니다. 모두 [Keras callbacks](https://huggingface.co/docs/transformers/main/ko/tasks/../main_classes/keras_callbacks)를 사용하여 수행됩니다.\n", "\n", "`KerasMetricCallback`에 `compute_metrics` 함수를 전달하세요:" ] }, { "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`에서 모델과 토크나이저를 업로드할 위치를 지정합니다:" ] }, { "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_wnut_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_validation_set, epochs=3, callbacks=callbacks)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련이 완료되면, 모델이 자동으로 허브에 업로드되어 누구나 사용할 수 있습니다!\n", "\n", "\n", "\n", "토큰 분류를 위한 모델을 파인 튜닝하는 자세한 예제는 다음 \n", "[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb) \n", "또는 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)를 참조하세요.\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 추론[[inference]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "좋아요, 이제 모델을 파인 튜닝했으니 추론에 사용할 수 있습니다!\n", "\n", "추론을 수행하고자 하는 텍스트를 가져와봅시다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = \"The Golden State Warriors are an American professional basketball team based in San Francisco.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "파인 튜닝된 모델로 추론을 시도하는 가장 간단한 방법은 `pipeline()`를 사용하는 것입니다. 모델로 NER의 `pipeline`을 인스턴스화하고, 텍스트를 전달해보세요:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'entity': 'B-location',\n", " 'score': 0.42658573,\n", " 'index': 2,\n", " 'word': 'golden',\n", " 'start': 4,\n", " 'end': 10},\n", " {'entity': 'I-location',\n", " 'score': 0.35856336,\n", " 'index': 3,\n", " 'word': 'state',\n", " 'start': 11,\n", " 'end': 16},\n", " {'entity': 'B-group',\n", " 'score': 0.3064001,\n", " 'index': 4,\n", " 'word': 'warriors',\n", " 'start': 17,\n", " 'end': 25},\n", " {'entity': 'B-location',\n", " 'score': 0.65523505,\n", " 'index': 13,\n", " 'word': 'san',\n", " 'start': 80,\n", " 'end': 83},\n", " {'entity': 'B-location',\n", " 'score': 0.4668663,\n", " 'index': 14,\n", " 'word': 'francisco',\n", " 'start': 84,\n", " 'end': 93}]" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from transformers import pipeline\n", "\n", "classifier = pipeline(\"ner\", model=\"stevhliu/my_awesome_wnut_model\")\n", "classifier(text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "원한다면, `pipeline`의 결과를 수동으로 복제할 수도 있습니다:\n", "\n", "텍스트를 토큰화하고 PyTorch 텐서를 반환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n", "inputs = tokenizer(text, return_tensors=\"pt\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "입력을 모델에 전달하고 `logits`을 반환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModelForTokenClassification\n", "\n", "model = AutoModelForTokenClassification.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n", "with torch.no_grad():\n", " logits = model(**inputs).logits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['O',\n", " 'O',\n", " 'B-location',\n", " 'I-location',\n", " 'B-group',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'B-location',\n", " 'B-location',\n", " 'O',\n", " 'O']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "predictions = torch.argmax(logits, dim=2)\n", "predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]\n", "predicted_token_class" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "텍스트를 토큰화하고 TensorFlow 텐서를 반환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n", "inputs = tokenizer(text, return_tensors=\"tf\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "입력값을 모델에 전달하고 `logits`을 반환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import TFAutoModelForTokenClassification\n", "\n", "model = TFAutoModelForTokenClassification.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n", "logits = model(**inputs).logits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "가장 높은 확률을 가진 클래스를 모델의 `id2label` 매핑을 사용하여 텍스트 레이블로 변환합니다:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['O',\n", " 'O',\n", " 'B-location',\n", " 'I-location',\n", " 'B-group',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'O',\n", " 'B-location',\n", " 'B-location',\n", " 'O',\n", " 'O']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "predicted_token_class_ids = tf.math.argmax(logits, axis=-1)\n", "predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]\n", "predicted_token_class" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 4 }