seokwoo97 commited on
Commit ·
b730e5e
0
Parent(s):
Initial commit after clean up
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +36 -0
- .nfs000000008874146400000004 +0 -0
- .vscode/extensions.json +5 -0
- 1장 허깅페이스 알아보기/예제 1.01 파이토치 GPU 가속 확인.ipynb +58 -0
- 1장 허깅페이스 알아보기/예제 1.02 MPS 가속 확인.ipynb +49 -0
- 1장 허깅페이스 알아보기/예제 1.03 파이토치 GPU 가속 확인.ipynb +38 -0
- 1장 허깅페이스 알아보기/예제 1.04 resnet-18 샘플 코드.ipynb +52 -0
- 1장 허깅페이스 알아보기/예제 1.05 push_to_hub 메서드 업로드.ipynb +80 -0
- 2장 허깅페이스 트랜스포머/예제 2.01 PretrainedConfig 클래스.ipynb +48 -0
- 2장 허깅페이스 트랜스포머/예제 2.02 PretrainedConfig 클래스의 from_pretrained 메서드.ipynb +42 -0
- 2장 허깅페이스 트랜스포머/예제 2.03 BertConfig 클래스.ipynb +42 -0
- 2장 허깅페이스 트랜스포머/예제 2.04 BertTokenizer 클래스.ipynb +42 -0
- 2장 허깅페이스 트랜스포머/예제 2.05 BertModel 클래스.ipynb +44 -0
- 2장 허깅페이스 트랜스포머/예제 2.06 BertForMaskedLM 클래스.ipynb +54 -0
- 2장 허깅페이스 트랜스포머/예제 2.07 CLIPFeatureExtractor 클래스.ipynb +52 -0
- 2장 허깅페이스 트랜스포머/예제 2.08 Wav2Vec2FeatureExtractor 클래스.ipynb +61 -0
- 2장 허깅페이스 트랜스포머/예제 2.09 CLIPImageProcessor 클래스.ipynb +51 -0
- 2장 허깅페이스 트랜스포머/예제 2.10 오토 클래스로 자연어 처리 모델 불러오기.ipynb +45 -0
- 2장 허깅페이스 트랜스포머/예제 2.11 오토 클래스로 컴퓨터 비전 모델 불러오기.ipynb +49 -0
- 2장 허깅페이스 트랜스포머/예제 2.12 오토 클래스로 오디오 모델 불러오기.ipynb +45 -0
- 2장 허깅페이스 트랜스포머/예제 2.13 자연어 처리 파이프라인 예시 (1).ipynb +69 -0
- 2장 허깅페이스 트랜스포머/예제 2.14 자연어 처리 파이프라인 예시 (2).ipynb +47 -0
- 2장 허깅페이스 트랜스포머/예제 2.15 자연어 처리 파이프라인.ipynb +46 -0
- 2장 허깅페이스 트랜스포머/예제 2.16 컴퓨터 비전 파이프라인.ipynb +49 -0
- 2장 허깅페이스 트랜스포머/예제 2.17 데이터세트 불러오기 (1).ipynb +41 -0
- 2장 허깅페이스 트랜스포머/예제 2.18 데이터세트 불러오기 (2).ipynb +43 -0
- 2장 허깅페이스 트랜스포머/예제 2.19 데이터세트 선택, 분리, 병합.ipynb +48 -0
- 2장 허깅페이스 트랜스포머/예제 2.20 데이터세트 filter와 map 메서드.ipynb +69 -0
- 2장 허깅페이스 트랜스포머/예제 2.21 데이터세트 업로드.ipynb +62 -0
- 2장 허깅페이스 트랜스포머/예제 2.22 ~ 2.26 개체명 인식 모델.ipynb +150 -0
- 2장 허깅페이스 트랜스포머/예제 2.27 이미지 모델 평가 수행.ipynb +80 -0
- 2장 허깅페이스 트랜스포머/예제 2.28 레이더 차트 시각화.ipynb +50 -0
- 3장 자연어 처리/예제 3.01 BERT 토크나이저를 이용한 토큰화.ipynb +49 -0
- 3장 자연어 처리/예제 3.02 BERT 모델 구조.ipynb +50 -0
- 3장 자연어 처리/예제 3.03 ~ 3.07 텍스트 분류 모델.ipynb +169 -0
- 3장 자연어 처리/예제 3.08 ~ 3.09 BART 구조.ipynb +69 -0
- 3장 자연어 처리/예제 3.10 ~ 3.14 요약문 생성 모델.ipynb +222 -0
- 3장 자연어 처리/예제 3.15 ~ 3.18 추출 질의 응답 모델.ipynb +177 -0
- 3장 자연어 처리/예제 3.19 ~ 3.22 기계 번역 모델 copy.ipynb +169 -0
- 3장 자연어 처리/예제 3.23 ~ 3.26 LLaMA-3.1 실습.ipynb +175 -0
- 3장 자연어 처리/예제 3.27 ~ 3.30 LLaMA-3.1 미세 조정.ipynb +170 -0
- 4장 컴퓨터 비전/예제 4.01 ~ 4.03 제로샷 이미지 분류.ipynb +124 -0
- 4장 컴퓨터 비전/예제 4.04 ~ 4.11 제로샷 객체 검출.ipynb +290 -0
- 4장 컴퓨터 비전/예제 4.12 ~ 4.17 이미지 세그먼테이션.ipynb +314 -0
- 5장 멀티모달/예제 5.01 ~ 5.02 BLIP-2 모델 구조.ipynb +60 -0
- 5장 멀티모달/예제 5.03 ~ 5.05 BLIP-2 모델 작동 방식.ipynb +120 -0
- 5장 멀티모달/예제 5.06 ~ 5.07 이미지 캡셔닝.ipynb +76 -0
- 5장 멀티모달/예제 5.08 ~ 5.09 LayoutLMv3 모델 구조.ipynb +68 -0
- 5장 멀티모달/예제 5.10 ~ 5.15 문서 시각 질의 응답.ipynb +343 -0
- 5장 멀티모달/예제 5.16 ~ 5.17 ViLT 모델 구조 copy.ipynb +60 -0
.gitattributes
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
images/*.jpg filter=lfs diff=lfs merge=lfs -text
|
.nfs000000008874146400000004
ADDED
|
Binary file (12.3 kB). View file
|
|
|
.vscode/extensions.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"recommendations": [
|
| 3 |
+
"ms-python.black-formatter"
|
| 4 |
+
]
|
| 5 |
+
}
|
1장 허깅페이스 알아보기/예제 1.01 파이토치 GPU 가속 확인.ipynb
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 2,
|
| 6 |
+
"id": "95ff9559-b7e7-401f-9b73-8c7a68eed848",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"2.7.1+cu118\n",
|
| 14 |
+
"True\n",
|
| 15 |
+
"파이썬 경로: /home/ufslab223/anaconda3/envs/hface/bin/python\n",
|
| 16 |
+
"파이토치 버전: 2.7.1+cu118\n",
|
| 17 |
+
"파이토치 설치 경로: /home/ufslab223/anaconda3/envs/hface/lib/python3.11/site-packages/torch/__init__.py\n"
|
| 18 |
+
]
|
| 19 |
+
}
|
| 20 |
+
],
|
| 21 |
+
"source": [
|
| 22 |
+
"import torch\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(torch.__version__)\n",
|
| 25 |
+
"print(torch.cuda.is_available())\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"import sys\n",
|
| 29 |
+
"import torch\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"print(f\"파이썬 경로: {sys.executable}\")\n",
|
| 32 |
+
"print(f\"파이토치 버전: {torch.__version__}\")\n",
|
| 33 |
+
"print(f\"파이토치 설치 경로: {torch.__file__}\")"
|
| 34 |
+
]
|
| 35 |
+
}
|
| 36 |
+
],
|
| 37 |
+
"metadata": {
|
| 38 |
+
"kernelspec": {
|
| 39 |
+
"display_name": "hface",
|
| 40 |
+
"language": "python",
|
| 41 |
+
"name": "python3"
|
| 42 |
+
},
|
| 43 |
+
"language_info": {
|
| 44 |
+
"codemirror_mode": {
|
| 45 |
+
"name": "ipython",
|
| 46 |
+
"version": 3
|
| 47 |
+
},
|
| 48 |
+
"file_extension": ".py",
|
| 49 |
+
"mimetype": "text/x-python",
|
| 50 |
+
"name": "python",
|
| 51 |
+
"nbconvert_exporter": "python",
|
| 52 |
+
"pygments_lexer": "ipython3",
|
| 53 |
+
"version": "3.11.15"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"nbformat": 4,
|
| 57 |
+
"nbformat_minor": 5
|
| 58 |
+
}
|
1장 허깅페이스 알아보기/예제 1.02 MPS 가속 확인.ipynb
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 3,
|
| 6 |
+
"id": "95ff9559-b7e7-401f-9b73-8c7a68eed848",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"2.5.1\n",
|
| 14 |
+
"False\n",
|
| 15 |
+
"False\n"
|
| 16 |
+
]
|
| 17 |
+
}
|
| 18 |
+
],
|
| 19 |
+
"source": [
|
| 20 |
+
"import torch\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"print(torch.__version__)\n",
|
| 23 |
+
"print(torch.backends.mps.is_built())\n",
|
| 24 |
+
"print(torch.backends.mps.is_available())"
|
| 25 |
+
]
|
| 26 |
+
}
|
| 27 |
+
],
|
| 28 |
+
"metadata": {
|
| 29 |
+
"kernelspec": {
|
| 30 |
+
"display_name": "hface",
|
| 31 |
+
"language": "python",
|
| 32 |
+
"name": "python3"
|
| 33 |
+
},
|
| 34 |
+
"language_info": {
|
| 35 |
+
"codemirror_mode": {
|
| 36 |
+
"name": "ipython",
|
| 37 |
+
"version": 3
|
| 38 |
+
},
|
| 39 |
+
"file_extension": ".py",
|
| 40 |
+
"mimetype": "text/x-python",
|
| 41 |
+
"name": "python",
|
| 42 |
+
"nbconvert_exporter": "python",
|
| 43 |
+
"pygments_lexer": "ipython3",
|
| 44 |
+
"version": "3.11.15"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"nbformat": 4,
|
| 48 |
+
"nbformat_minor": 5
|
| 49 |
+
}
|
1장 허깅페이스 알아보기/예제 1.03 파이토치 GPU 가속 확인.ipynb
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "95ff9559-b7e7-401f-9b73-8c7a68eed848",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(torch.__version__)\n",
|
| 13 |
+
"print(torch.cuda.is_available())"
|
| 14 |
+
]
|
| 15 |
+
}
|
| 16 |
+
],
|
| 17 |
+
"metadata": {
|
| 18 |
+
"kernelspec": {
|
| 19 |
+
"display_name": "Python 3 (ipykernel)",
|
| 20 |
+
"language": "python",
|
| 21 |
+
"name": "python3"
|
| 22 |
+
},
|
| 23 |
+
"language_info": {
|
| 24 |
+
"codemirror_mode": {
|
| 25 |
+
"name": "ipython",
|
| 26 |
+
"version": 3
|
| 27 |
+
},
|
| 28 |
+
"file_extension": ".py",
|
| 29 |
+
"mimetype": "text/x-python",
|
| 30 |
+
"name": "python",
|
| 31 |
+
"nbconvert_exporter": "python",
|
| 32 |
+
"pygments_lexer": "ipython3",
|
| 33 |
+
"version": "3.9.13"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"nbformat": 4,
|
| 37 |
+
"nbformat_minor": 5
|
| 38 |
+
}
|
1장 허깅페이스 알아보기/예제 1.04 resnet-18 샘플 코드.ipynb
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "95ff9559-b7e7-401f-9b73-8c7a68eed848",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import AutoImageProcessor, AutoModelForImageClassification\n",
|
| 11 |
+
"import torch\n",
|
| 12 |
+
"from datasets import load_dataset\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"dataset = load_dataset(\"huggingface/cats-image\", trust_remote_code=True)\n",
|
| 15 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"image_processor = AutoImageProcessor.from_pretrained(\"microsoft/resnet-18\")\n",
|
| 18 |
+
"model = AutoModelForImageClassification.from_pretrained(\"microsoft/resnet-18\")\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"inputs = image_processor(image, return_tensors=\"pt\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"with torch.no_grad():\n",
|
| 23 |
+
" logits = model(**inputs).logits\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"# model predicts one of the 1000 ImageNet classes\n",
|
| 26 |
+
"predicted_label = logits.argmax(-1).item()\n",
|
| 27 |
+
"print(model.config.id2label[predicted_label])"
|
| 28 |
+
]
|
| 29 |
+
}
|
| 30 |
+
],
|
| 31 |
+
"metadata": {
|
| 32 |
+
"kernelspec": {
|
| 33 |
+
"display_name": "Python 3 (ipykernel)",
|
| 34 |
+
"language": "python",
|
| 35 |
+
"name": "python3"
|
| 36 |
+
},
|
| 37 |
+
"language_info": {
|
| 38 |
+
"codemirror_mode": {
|
| 39 |
+
"name": "ipython",
|
| 40 |
+
"version": 3
|
| 41 |
+
},
|
| 42 |
+
"file_extension": ".py",
|
| 43 |
+
"mimetype": "text/x-python",
|
| 44 |
+
"name": "python",
|
| 45 |
+
"nbconvert_exporter": "python",
|
| 46 |
+
"pygments_lexer": "ipython3",
|
| 47 |
+
"version": "3.9.13"
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
+
"nbformat": 4,
|
| 51 |
+
"nbformat_minor": 5
|
| 52 |
+
}
|
1장 허깅페이스 알아보기/예제 1.05 push_to_hub 메서드 업로드.ipynb
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "95ff9559-b7e7-401f-9b73-8c7a68eed848",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import AutoImageProcessor, AutoModelForImageClassification\n",
|
| 11 |
+
"import torch\n",
|
| 12 |
+
"from datasets import load_dataset\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"dataset = load_dataset(\"huggingface/cats-image\", trust_remote_code=True)\n",
|
| 15 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"image_processor = AutoImageProcessor.from_pretrained(\"microsoft/resnet-18\")\n",
|
| 18 |
+
"model = AutoModelForImageClassification.from_pretrained(\"microsoft/resnet-18\")\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"inputs = image_processor(image, return_tensors=\"pt\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"with torch.no_grad():\n",
|
| 23 |
+
" logits = model(**inputs).logits\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"# model predicts one of the 1000 ImageNet classes\n",
|
| 26 |
+
"predicted_label = logits.argmax(-1).item()\n",
|
| 27 |
+
"print(model.config.id2label[predicted_label])"
|
| 28 |
+
]
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"id": "fb8c6599",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"outputs": [],
|
| 36 |
+
"source": [
|
| 37 |
+
"REPO_ID = \"모델 리포지터리 이름 입력\" # resnet-18\n",
|
| 38 |
+
"TOKEN = \"토큰 이름 입력\" # hf_..."
|
| 39 |
+
]
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"id": "4d95cf8a",
|
| 45 |
+
"metadata": {},
|
| 46 |
+
"outputs": [],
|
| 47 |
+
"source": [
|
| 48 |
+
"image_processor.push_to_hub(\n",
|
| 49 |
+
" repo_id=REPO_ID,\n",
|
| 50 |
+
" token=TOKEN\n",
|
| 51 |
+
")\n",
|
| 52 |
+
"model.push_to_hub(\n",
|
| 53 |
+
" repo_id=REPO_ID,\n",
|
| 54 |
+
" token=TOKEN\n",
|
| 55 |
+
")"
|
| 56 |
+
]
|
| 57 |
+
}
|
| 58 |
+
],
|
| 59 |
+
"metadata": {
|
| 60 |
+
"kernelspec": {
|
| 61 |
+
"display_name": "Python 3 (ipykernel)",
|
| 62 |
+
"language": "python",
|
| 63 |
+
"name": "python3"
|
| 64 |
+
},
|
| 65 |
+
"language_info": {
|
| 66 |
+
"codemirror_mode": {
|
| 67 |
+
"name": "ipython",
|
| 68 |
+
"version": 3
|
| 69 |
+
},
|
| 70 |
+
"file_extension": ".py",
|
| 71 |
+
"mimetype": "text/x-python",
|
| 72 |
+
"name": "python",
|
| 73 |
+
"nbconvert_exporter": "python",
|
| 74 |
+
"pygments_lexer": "ipython3",
|
| 75 |
+
"version": "3.9.13"
|
| 76 |
+
}
|
| 77 |
+
},
|
| 78 |
+
"nbformat": 4,
|
| 79 |
+
"nbformat_minor": 5
|
| 80 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.01 PretrainedConfig 클래스.ipynb
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import PretrainedConfig\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"config = PretrainedConfig(\n",
|
| 13 |
+
" model_type=\"bert\",\n",
|
| 14 |
+
" vocab_size=30522,\n",
|
| 15 |
+
" hidden_size=768,\n",
|
| 16 |
+
" num_attention_heads=12,\n",
|
| 17 |
+
" num_hidden_layers=12,\n",
|
| 18 |
+
" intermediate_size=3072,\n",
|
| 19 |
+
" hidden_act=\"gelu\",\n",
|
| 20 |
+
" hidden_dropout_prob=0.1,\n",
|
| 21 |
+
" initializer_range=0.02\n",
|
| 22 |
+
")\n",
|
| 23 |
+
"print(config)"
|
| 24 |
+
]
|
| 25 |
+
}
|
| 26 |
+
],
|
| 27 |
+
"metadata": {
|
| 28 |
+
"kernelspec": {
|
| 29 |
+
"display_name": "Python 3 (ipykernel)",
|
| 30 |
+
"language": "python",
|
| 31 |
+
"name": "python3"
|
| 32 |
+
},
|
| 33 |
+
"language_info": {
|
| 34 |
+
"codemirror_mode": {
|
| 35 |
+
"name": "ipython",
|
| 36 |
+
"version": 3
|
| 37 |
+
},
|
| 38 |
+
"file_extension": ".py",
|
| 39 |
+
"mimetype": "text/x-python",
|
| 40 |
+
"name": "python",
|
| 41 |
+
"nbconvert_exporter": "python",
|
| 42 |
+
"pygments_lexer": "ipython3",
|
| 43 |
+
"version": "3.9.13"
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
"nbformat": 4,
|
| 47 |
+
"nbformat_minor": 5
|
| 48 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.02 PretrainedConfig 클래스의 from_pretrained 메서드.ipynb
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import PretrainedConfig\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"config = PretrainedConfig.from_pretrained(\n",
|
| 13 |
+
" pretrained_model_name_or_path=\"google-bert/bert-base-uncased\",\n",
|
| 14 |
+
" hidden_act=\"swish\"\n",
|
| 15 |
+
")\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(config)"
|
| 18 |
+
]
|
| 19 |
+
}
|
| 20 |
+
],
|
| 21 |
+
"metadata": {
|
| 22 |
+
"kernelspec": {
|
| 23 |
+
"display_name": "Python 3 (ipykernel)",
|
| 24 |
+
"language": "python",
|
| 25 |
+
"name": "python3"
|
| 26 |
+
},
|
| 27 |
+
"language_info": {
|
| 28 |
+
"codemirror_mode": {
|
| 29 |
+
"name": "ipython",
|
| 30 |
+
"version": 3
|
| 31 |
+
},
|
| 32 |
+
"file_extension": ".py",
|
| 33 |
+
"mimetype": "text/x-python",
|
| 34 |
+
"name": "python",
|
| 35 |
+
"nbconvert_exporter": "python",
|
| 36 |
+
"pygments_lexer": "ipython3",
|
| 37 |
+
"version": "3.9.13"
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"nbformat": 4,
|
| 41 |
+
"nbformat_minor": 5
|
| 42 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.03 BertConfig 클래스.ipynb
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import BertConfig\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"config = BertConfig(\n",
|
| 13 |
+
" num_hidden_layers=12, \n",
|
| 14 |
+
" num_attention_heads=12\n",
|
| 15 |
+
")\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(config)"
|
| 18 |
+
]
|
| 19 |
+
}
|
| 20 |
+
],
|
| 21 |
+
"metadata": {
|
| 22 |
+
"kernelspec": {
|
| 23 |
+
"display_name": "Python 3 (ipykernel)",
|
| 24 |
+
"language": "python",
|
| 25 |
+
"name": "python3"
|
| 26 |
+
},
|
| 27 |
+
"language_info": {
|
| 28 |
+
"codemirror_mode": {
|
| 29 |
+
"name": "ipython",
|
| 30 |
+
"version": 3
|
| 31 |
+
},
|
| 32 |
+
"file_extension": ".py",
|
| 33 |
+
"mimetype": "text/x-python",
|
| 34 |
+
"name": "python",
|
| 35 |
+
"nbconvert_exporter": "python",
|
| 36 |
+
"pygments_lexer": "ipython3",
|
| 37 |
+
"version": "3.9.13"
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"nbformat": 4,
|
| 41 |
+
"nbformat_minor": 5
|
| 42 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.04 BertTokenizer 클래스.ipynb
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import BertTokenizer\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n",
|
| 13 |
+
"text = \"I am learning about tokenizers.\"\n",
|
| 14 |
+
"encoded = tokenizer.encode(text, add_special_tokens=True)\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"print(encoded)\n",
|
| 17 |
+
"print(tokenizer.decode(encoded))"
|
| 18 |
+
]
|
| 19 |
+
}
|
| 20 |
+
],
|
| 21 |
+
"metadata": {
|
| 22 |
+
"kernelspec": {
|
| 23 |
+
"display_name": "Python 3 (ipykernel)",
|
| 24 |
+
"language": "python",
|
| 25 |
+
"name": "python3"
|
| 26 |
+
},
|
| 27 |
+
"language_info": {
|
| 28 |
+
"codemirror_mode": {
|
| 29 |
+
"name": "ipython",
|
| 30 |
+
"version": 3
|
| 31 |
+
},
|
| 32 |
+
"file_extension": ".py",
|
| 33 |
+
"mimetype": "text/x-python",
|
| 34 |
+
"name": "python",
|
| 35 |
+
"nbconvert_exporter": "python",
|
| 36 |
+
"pygments_lexer": "ipython3",
|
| 37 |
+
"version": "3.9.13"
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"nbformat": 4,
|
| 41 |
+
"nbformat_minor": 5
|
| 42 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.05 BertModel 클래스.ipynb
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import BertTokenizer, BertModel\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n",
|
| 13 |
+
"text = \"I am learning about tokenizers.\"\n",
|
| 14 |
+
"input = tokenizer(text, return_tensors=\"pt\")\n",
|
| 15 |
+
"print(input)\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"model = BertModel.from_pretrained(\"bert-base-uncased\")\n",
|
| 18 |
+
"output = model(**input)\n",
|
| 19 |
+
"print(output.last_hidden_state.shape)"
|
| 20 |
+
]
|
| 21 |
+
}
|
| 22 |
+
],
|
| 23 |
+
"metadata": {
|
| 24 |
+
"kernelspec": {
|
| 25 |
+
"display_name": "Python 3 (ipykernel)",
|
| 26 |
+
"language": "python",
|
| 27 |
+
"name": "python3"
|
| 28 |
+
},
|
| 29 |
+
"language_info": {
|
| 30 |
+
"codemirror_mode": {
|
| 31 |
+
"name": "ipython",
|
| 32 |
+
"version": 3
|
| 33 |
+
},
|
| 34 |
+
"file_extension": ".py",
|
| 35 |
+
"mimetype": "text/x-python",
|
| 36 |
+
"name": "python",
|
| 37 |
+
"nbconvert_exporter": "python",
|
| 38 |
+
"pygments_lexer": "ipython3",
|
| 39 |
+
"version": "3.9.13"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"nbformat": 4,
|
| 43 |
+
"nbformat_minor": 5
|
| 44 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.06 BertForMaskedLM 클래스.ipynb
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"from torch.nn import functional as F\n",
|
| 12 |
+
"from transformers import BertTokenizer, BertForMaskedLM\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n",
|
| 15 |
+
"model = BertForMaskedLM.from_pretrained(\"bert-base-uncased\", return_dict=True)\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"text = f\"I {tokenizer.mask_token} learning about tokenizers.\"\n",
|
| 18 |
+
"input = tokenizer(text, return_tensors=\"pt\")\n",
|
| 19 |
+
"output = model(**input)\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"mask_index = torch.where(input[\"input_ids\"][0] == tokenizer.mask_token_id)\n",
|
| 22 |
+
"softmax = F.softmax(output.logits, dim=-1)\n",
|
| 23 |
+
"mask_word = softmax[0, mask_index, :]\n",
|
| 24 |
+
"top10 = torch.topk(mask_word, 10, dim=1)[1][0]\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"for token in top10:\n",
|
| 27 |
+
" word = tokenizer.decode([token])\n",
|
| 28 |
+
" sentence = text.replace(tokenizer.mask_token, word)\n",
|
| 29 |
+
" print(sentence)"
|
| 30 |
+
]
|
| 31 |
+
}
|
| 32 |
+
],
|
| 33 |
+
"metadata": {
|
| 34 |
+
"kernelspec": {
|
| 35 |
+
"display_name": "Python 3 (ipykernel)",
|
| 36 |
+
"language": "python",
|
| 37 |
+
"name": "python3"
|
| 38 |
+
},
|
| 39 |
+
"language_info": {
|
| 40 |
+
"codemirror_mode": {
|
| 41 |
+
"name": "ipython",
|
| 42 |
+
"version": 3
|
| 43 |
+
},
|
| 44 |
+
"file_extension": ".py",
|
| 45 |
+
"mimetype": "text/x-python",
|
| 46 |
+
"name": "python",
|
| 47 |
+
"nbconvert_exporter": "python",
|
| 48 |
+
"pygments_lexer": "ipython3",
|
| 49 |
+
"version": "3.9.13"
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"nbformat": 4,
|
| 53 |
+
"nbformat_minor": 5
|
| 54 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.07 CLIPFeatureExtractor 클래스.ipynb
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import CLIPFeatureExtractor\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 14 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"feature_extractor = CLIPFeatureExtractor.from_pretrained(\"openai/clip-vit-base-patch32\")\n",
|
| 17 |
+
"inputs = feature_extractor(\n",
|
| 18 |
+
" images=image,\n",
|
| 19 |
+
" do_resize=True,\n",
|
| 20 |
+
" size=512,\n",
|
| 21 |
+
" do_center_crop=True,\n",
|
| 22 |
+
" crop_size=512,\n",
|
| 23 |
+
" return_tensors=\"pt\"\n",
|
| 24 |
+
")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(inputs[\"pixel_values\"].shape)\n",
|
| 27 |
+
"print(inputs)"
|
| 28 |
+
]
|
| 29 |
+
}
|
| 30 |
+
],
|
| 31 |
+
"metadata": {
|
| 32 |
+
"kernelspec": {
|
| 33 |
+
"display_name": "Python 3 (ipykernel)",
|
| 34 |
+
"language": "python",
|
| 35 |
+
"name": "python3"
|
| 36 |
+
},
|
| 37 |
+
"language_info": {
|
| 38 |
+
"codemirror_mode": {
|
| 39 |
+
"name": "ipython",
|
| 40 |
+
"version": 3
|
| 41 |
+
},
|
| 42 |
+
"file_extension": ".py",
|
| 43 |
+
"mimetype": "text/x-python",
|
| 44 |
+
"name": "python",
|
| 45 |
+
"nbconvert_exporter": "python",
|
| 46 |
+
"pygments_lexer": "ipython3",
|
| 47 |
+
"version": "3.9.13"
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
+
"nbformat": 4,
|
| 51 |
+
"nbformat_minor": 5
|
| 52 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.08 Wav2Vec2FeatureExtractor 클래스.ipynb
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "76155e63",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"!pip install soundfile librosa"
|
| 11 |
+
]
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"cell_type": "code",
|
| 15 |
+
"execution_count": null,
|
| 16 |
+
"id": "39d707db",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"outputs": [],
|
| 19 |
+
"source": [
|
| 20 |
+
"from datasets import load_dataset\n",
|
| 21 |
+
"from transformers import Wav2Vec2FeatureExtractor\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"dataset = load_dataset(\"PolyAI/minds14\", \"ko-KR\", split=\"train\", trust_remote_code=True)\n",
|
| 24 |
+
"audios = [audio[\"array\"] for audio in dataset[\"audio\"][:2]]\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(\"facebook/wav2vec2-base-960h\")\n",
|
| 27 |
+
"inputs = feature_extractor(\n",
|
| 28 |
+
" raw_speech=audios,\n",
|
| 29 |
+
" padding=True,\n",
|
| 30 |
+
" return_attention_mask=True,\n",
|
| 31 |
+
" return_tensors=\"pt\"\n",
|
| 32 |
+
")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(inputs[\"input_values\"][0].shape)\n",
|
| 35 |
+
"print(inputs[\"input_values\"][1].shape)\n",
|
| 36 |
+
"print(inputs)"
|
| 37 |
+
]
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
"metadata": {
|
| 41 |
+
"kernelspec": {
|
| 42 |
+
"display_name": "Python 3 (ipykernel)",
|
| 43 |
+
"language": "python",
|
| 44 |
+
"name": "python3"
|
| 45 |
+
},
|
| 46 |
+
"language_info": {
|
| 47 |
+
"codemirror_mode": {
|
| 48 |
+
"name": "ipython",
|
| 49 |
+
"version": 3
|
| 50 |
+
},
|
| 51 |
+
"file_extension": ".py",
|
| 52 |
+
"mimetype": "text/x-python",
|
| 53 |
+
"name": "python",
|
| 54 |
+
"nbconvert_exporter": "python",
|
| 55 |
+
"pygments_lexer": "ipython3",
|
| 56 |
+
"version": "3.9.13"
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"nbformat": 4,
|
| 60 |
+
"nbformat_minor": 5
|
| 61 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.09 CLIPImageProcessor 클래스.ipynb
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import CLIPImageProcessor\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 14 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"image_processor = CLIPImageProcessor.from_pretrained(\"openai/clip-vit-base-patch32\")\n",
|
| 17 |
+
"pixel_values = image_processor(\n",
|
| 18 |
+
" images=image,\n",
|
| 19 |
+
" image_mean=[0.48145466, 0.4578275, 0.40821073],\n",
|
| 20 |
+
" image_std=[0.26862954, 0.26130258, 0.27577711],\n",
|
| 21 |
+
" do_convert_rgb=True,\n",
|
| 22 |
+
" return_tensors=\"pt\"\n",
|
| 23 |
+
")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"print(pixel_values[\"pixel_values\"].shape)\n",
|
| 26 |
+
"print(pixel_values)"
|
| 27 |
+
]
|
| 28 |
+
}
|
| 29 |
+
],
|
| 30 |
+
"metadata": {
|
| 31 |
+
"kernelspec": {
|
| 32 |
+
"display_name": "Python 3 (ipykernel)",
|
| 33 |
+
"language": "python",
|
| 34 |
+
"name": "python3"
|
| 35 |
+
},
|
| 36 |
+
"language_info": {
|
| 37 |
+
"codemirror_mode": {
|
| 38 |
+
"name": "ipython",
|
| 39 |
+
"version": 3
|
| 40 |
+
},
|
| 41 |
+
"file_extension": ".py",
|
| 42 |
+
"mimetype": "text/x-python",
|
| 43 |
+
"name": "python",
|
| 44 |
+
"nbconvert_exporter": "python",
|
| 45 |
+
"pygments_lexer": "ipython3",
|
| 46 |
+
"version": "3.9.13"
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"nbformat": 4,
|
| 50 |
+
"nbformat_minor": 5
|
| 51 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.10 오토 클래스로 자연어 처리 모델 불러오기.ipynb
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import AutoModel, AutoTokenizer\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"model_name = \"bert-base-uncased\"\n",
|
| 13 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
|
| 14 |
+
"model = AutoModel.from_pretrained(model_name)\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"text = \"I am learning about tokenizers.\"\n",
|
| 17 |
+
"input = tokenizer(text, return_tensors=\"pt\")\n",
|
| 18 |
+
"output = model(**input)\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"print(output.last_hidden_state.shape)"
|
| 21 |
+
]
|
| 22 |
+
}
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"kernelspec": {
|
| 26 |
+
"display_name": "Python 3 (ipykernel)",
|
| 27 |
+
"language": "python",
|
| 28 |
+
"name": "python3"
|
| 29 |
+
},
|
| 30 |
+
"language_info": {
|
| 31 |
+
"codemirror_mode": {
|
| 32 |
+
"name": "ipython",
|
| 33 |
+
"version": 3
|
| 34 |
+
},
|
| 35 |
+
"file_extension": ".py",
|
| 36 |
+
"mimetype": "text/x-python",
|
| 37 |
+
"name": "python",
|
| 38 |
+
"nbconvert_exporter": "python",
|
| 39 |
+
"pygments_lexer": "ipython3",
|
| 40 |
+
"version": "3.9.13"
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
"nbformat": 4,
|
| 44 |
+
"nbformat_minor": 5
|
| 45 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.11 오토 클래스로 컴퓨터 비전 모델 불러오기.ipynb
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from PIL import Image\n",
|
| 11 |
+
"from datasets import load_dataset\n",
|
| 12 |
+
"from transformers import AutoImageProcessor, AutoModel\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"model_name = \"microsoft/resnet-18\" # \"google/vit-base-patch16-224-in21k\"\n",
|
| 15 |
+
"image_processor = AutoImageProcessor.from_pretrained(model_name)\n",
|
| 16 |
+
"model = AutoModel.from_pretrained(model_name)\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 19 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"inputs = image_processor(images=image, return_tensors=\"pt\")\n",
|
| 22 |
+
"outputs = model(**inputs)\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(outputs.last_hidden_state.shape)"
|
| 25 |
+
]
|
| 26 |
+
}
|
| 27 |
+
],
|
| 28 |
+
"metadata": {
|
| 29 |
+
"kernelspec": {
|
| 30 |
+
"display_name": "Python 3 (ipykernel)",
|
| 31 |
+
"language": "python",
|
| 32 |
+
"name": "python3"
|
| 33 |
+
},
|
| 34 |
+
"language_info": {
|
| 35 |
+
"codemirror_mode": {
|
| 36 |
+
"name": "ipython",
|
| 37 |
+
"version": 3
|
| 38 |
+
},
|
| 39 |
+
"file_extension": ".py",
|
| 40 |
+
"mimetype": "text/x-python",
|
| 41 |
+
"name": "python",
|
| 42 |
+
"nbconvert_exporter": "python",
|
| 43 |
+
"pygments_lexer": "ipython3",
|
| 44 |
+
"version": "3.9.13"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"nbformat": 4,
|
| 48 |
+
"nbformat_minor": 5
|
| 49 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.12 오토 클래스로 오디오 모델 불러오기.ipynb
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import AutoFeatureExtractor\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"model_name = \"facebook/wav2vec2-base-960h\" # \"openai/whisper-tiny\"\n",
|
| 14 |
+
"feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"dataset = load_dataset(\"PolyAI/minds14\", \"ko-KR\", split=\"train\")\n",
|
| 17 |
+
"audios = [audio[\"array\"] for audio in dataset[\"audio\"][:2]]\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"inputs = feature_extractor(raw_speech=audios, padding=True, return_tensors=\"pt\")\n",
|
| 20 |
+
"print(inputs.keys())"
|
| 21 |
+
]
|
| 22 |
+
}
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"kernelspec": {
|
| 26 |
+
"display_name": "Python 3 (ipykernel)",
|
| 27 |
+
"language": "python",
|
| 28 |
+
"name": "python3"
|
| 29 |
+
},
|
| 30 |
+
"language_info": {
|
| 31 |
+
"codemirror_mode": {
|
| 32 |
+
"name": "ipython",
|
| 33 |
+
"version": 3
|
| 34 |
+
},
|
| 35 |
+
"file_extension": ".py",
|
| 36 |
+
"mimetype": "text/x-python",
|
| 37 |
+
"name": "python",
|
| 38 |
+
"nbconvert_exporter": "python",
|
| 39 |
+
"pygments_lexer": "ipython3",
|
| 40 |
+
"version": "3.9.13"
|
| 41 |
+
}
|
| 42 |
+
},
|
| 43 |
+
"nbformat": 4,
|
| 44 |
+
"nbformat_minor": 5
|
| 45 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.13 자연어 처리 파이프라인 예시 (1).ipynb
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"import torch.nn.functional as F\n",
|
| 12 |
+
"from transformers import pipeline\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"pipe = pipeline(\n",
|
| 15 |
+
" task=\"text-classification\",\n",
|
| 16 |
+
" model=\"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n",
|
| 17 |
+
")\n",
|
| 18 |
+
"raw_text = [\n",
|
| 19 |
+
" \"I love you.\",\n",
|
| 20 |
+
" \"I hate you.\",\n",
|
| 21 |
+
" \"I meet with you.\"\n",
|
| 22 |
+
"]\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"inputs = pipe.tokenizer(raw_text, padding=True, return_tensors=\"pt\")\n",
|
| 25 |
+
"outputs = pipe.model(inputs[\"input_ids\"])\n",
|
| 26 |
+
"probabilities = F.softmax(outputs.logits, dim=1)\n",
|
| 27 |
+
"prediction = []\n",
|
| 28 |
+
"for prob in probabilities:\n",
|
| 29 |
+
" max_idx = torch.argmax(prob).item()\n",
|
| 30 |
+
" class_name = pipe.model.config.id2label[max_idx]\n",
|
| 31 |
+
" score = prob[max_idx].item()\n",
|
| 32 |
+
" prediction.append({\"label\": class_name, \"score\": score})\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(\"- raw text:\")\n",
|
| 35 |
+
"print(raw_text)\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(\"- input_ids:\")\n",
|
| 38 |
+
"print(inputs[\"input_ids\"])\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(\"- logits:\")\n",
|
| 41 |
+
"print(outputs[\"logits\"])\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"print(\"- prediction:\")\n",
|
| 44 |
+
"print(prediction)"
|
| 45 |
+
]
|
| 46 |
+
}
|
| 47 |
+
],
|
| 48 |
+
"metadata": {
|
| 49 |
+
"kernelspec": {
|
| 50 |
+
"display_name": "Python 3 (ipykernel)",
|
| 51 |
+
"language": "python",
|
| 52 |
+
"name": "python3"
|
| 53 |
+
},
|
| 54 |
+
"language_info": {
|
| 55 |
+
"codemirror_mode": {
|
| 56 |
+
"name": "ipython",
|
| 57 |
+
"version": 3
|
| 58 |
+
},
|
| 59 |
+
"file_extension": ".py",
|
| 60 |
+
"mimetype": "text/x-python",
|
| 61 |
+
"name": "python",
|
| 62 |
+
"nbconvert_exporter": "python",
|
| 63 |
+
"pygments_lexer": "ipython3",
|
| 64 |
+
"version": "3.9.13"
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
"nbformat": 4,
|
| 68 |
+
"nbformat_minor": 5
|
| 69 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.14 자연어 처리 파이프라인 예시 (2).ipynb
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import pipeline\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"pipe = pipeline(\n",
|
| 13 |
+
" task=\"text-classification\",\n",
|
| 14 |
+
" model=\"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n",
|
| 15 |
+
")\n",
|
| 16 |
+
"raw_text = [\n",
|
| 17 |
+
" \"I love you.\",\n",
|
| 18 |
+
" \"I hate you.\",\n",
|
| 19 |
+
" \"I meet with you.\"\n",
|
| 20 |
+
"]\n",
|
| 21 |
+
"prediction = pipe(raw_text)\n",
|
| 22 |
+
"print(prediction)"
|
| 23 |
+
]
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
"metadata": {
|
| 27 |
+
"kernelspec": {
|
| 28 |
+
"display_name": "Python 3 (ipykernel)",
|
| 29 |
+
"language": "python",
|
| 30 |
+
"name": "python3"
|
| 31 |
+
},
|
| 32 |
+
"language_info": {
|
| 33 |
+
"codemirror_mode": {
|
| 34 |
+
"name": "ipython",
|
| 35 |
+
"version": 3
|
| 36 |
+
},
|
| 37 |
+
"file_extension": ".py",
|
| 38 |
+
"mimetype": "text/x-python",
|
| 39 |
+
"name": "python",
|
| 40 |
+
"nbconvert_exporter": "python",
|
| 41 |
+
"pygments_lexer": "ipython3",
|
| 42 |
+
"version": "3.9.13"
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
"nbformat": 4,
|
| 46 |
+
"nbformat_minor": 5
|
| 47 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.15 자연어 처리 파이프라인.ipynb
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"from transformers import pipeline\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"pipe = pipeline(\n",
|
| 14 |
+
" task=\"text-generation\",\n",
|
| 15 |
+
" model=\"openai-community/gpt2\", # google-bert/bert-base-uncased\n",
|
| 16 |
+
" device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n",
|
| 17 |
+
" torch_dtype=torch.bfloat16\n",
|
| 18 |
+
")\n",
|
| 19 |
+
"inputs = \"I am learning about tokenizers.\"\n",
|
| 20 |
+
"outputs = pipe(inputs)\n",
|
| 21 |
+
"print(outputs)"
|
| 22 |
+
]
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"metadata": {
|
| 26 |
+
"kernelspec": {
|
| 27 |
+
"display_name": "Python 3 (ipykernel)",
|
| 28 |
+
"language": "python",
|
| 29 |
+
"name": "python3"
|
| 30 |
+
},
|
| 31 |
+
"language_info": {
|
| 32 |
+
"codemirror_mode": {
|
| 33 |
+
"name": "ipython",
|
| 34 |
+
"version": 3
|
| 35 |
+
},
|
| 36 |
+
"file_extension": ".py",
|
| 37 |
+
"mimetype": "text/x-python",
|
| 38 |
+
"name": "python",
|
| 39 |
+
"nbconvert_exporter": "python",
|
| 40 |
+
"pygments_lexer": "ipython3",
|
| 41 |
+
"version": "3.9.13"
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"nbformat": 4,
|
| 45 |
+
"nbformat_minor": 5
|
| 46 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.16 컴퓨터 비전 파이프라인.ipynb
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import pipeline\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"pipe = pipeline(\n",
|
| 14 |
+
" task=\"image-classification\",\n",
|
| 15 |
+
" model=\"google/vit-base-patch16-224\",\n",
|
| 16 |
+
" model_kwargs={\n",
|
| 17 |
+
" \"hidden_act\": \"gelu\" # relu\n",
|
| 18 |
+
" }\n",
|
| 19 |
+
")\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 22 |
+
"inputs = dataset[\"test\"][\"image\"][0]\n",
|
| 23 |
+
"outputs = pipe(inputs)\n",
|
| 24 |
+
"print(outputs)"
|
| 25 |
+
]
|
| 26 |
+
}
|
| 27 |
+
],
|
| 28 |
+
"metadata": {
|
| 29 |
+
"kernelspec": {
|
| 30 |
+
"display_name": "Python 3 (ipykernel)",
|
| 31 |
+
"language": "python",
|
| 32 |
+
"name": "python3"
|
| 33 |
+
},
|
| 34 |
+
"language_info": {
|
| 35 |
+
"codemirror_mode": {
|
| 36 |
+
"name": "ipython",
|
| 37 |
+
"version": 3
|
| 38 |
+
},
|
| 39 |
+
"file_extension": ".py",
|
| 40 |
+
"mimetype": "text/x-python",
|
| 41 |
+
"name": "python",
|
| 42 |
+
"nbconvert_exporter": "python",
|
| 43 |
+
"pygments_lexer": "ipython3",
|
| 44 |
+
"version": "3.9.13"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"nbformat": 4,
|
| 48 |
+
"nbformat_minor": 5
|
| 49 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.17 데이터세트 불러오기 (1).ipynb
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"dataset1 = load_dataset(path=\"squad\")\n",
|
| 13 |
+
"dataset2 = load_dataset(path=\"squad\", split=\"train[:10]+validation[:10]\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"print(dataset1)\n",
|
| 16 |
+
"print(dataset2)"
|
| 17 |
+
]
|
| 18 |
+
}
|
| 19 |
+
],
|
| 20 |
+
"metadata": {
|
| 21 |
+
"kernelspec": {
|
| 22 |
+
"display_name": "Python 3 (ipykernel)",
|
| 23 |
+
"language": "python",
|
| 24 |
+
"name": "python3"
|
| 25 |
+
},
|
| 26 |
+
"language_info": {
|
| 27 |
+
"codemirror_mode": {
|
| 28 |
+
"name": "ipython",
|
| 29 |
+
"version": 3
|
| 30 |
+
},
|
| 31 |
+
"file_extension": ".py",
|
| 32 |
+
"mimetype": "text/x-python",
|
| 33 |
+
"name": "python",
|
| 34 |
+
"nbconvert_exporter": "python",
|
| 35 |
+
"pygments_lexer": "ipython3",
|
| 36 |
+
"version": "3.9.13"
|
| 37 |
+
}
|
| 38 |
+
},
|
| 39 |
+
"nbformat": 4,
|
| 40 |
+
"nbformat_minor": 5
|
| 41 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.18 데이터세트 불러오기 (2).ipynb
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"dataset1 = load_dataset(path=\"../datasets\")\n",
|
| 13 |
+
"dataset2 = load_dataset(path=\"json\", data_dir=\"../datasets\")\n",
|
| 14 |
+
"dataset3 = load_dataset(path=\"json\", data_files={\"train\": \"../datasets/train.jsonl\", \"validation\": \"../datasets/val.jsonl\"})\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"print(dataset1[\"train\"][0])\n",
|
| 17 |
+
"print(dataset2[\"train\"][0])\n",
|
| 18 |
+
"print(dataset3[\"train\"][0])"
|
| 19 |
+
]
|
| 20 |
+
}
|
| 21 |
+
],
|
| 22 |
+
"metadata": {
|
| 23 |
+
"kernelspec": {
|
| 24 |
+
"display_name": "Python 3 (ipykernel)",
|
| 25 |
+
"language": "python",
|
| 26 |
+
"name": "python3"
|
| 27 |
+
},
|
| 28 |
+
"language_info": {
|
| 29 |
+
"codemirror_mode": {
|
| 30 |
+
"name": "ipython",
|
| 31 |
+
"version": 3
|
| 32 |
+
},
|
| 33 |
+
"file_extension": ".py",
|
| 34 |
+
"mimetype": "text/x-python",
|
| 35 |
+
"name": "python",
|
| 36 |
+
"nbconvert_exporter": "python",
|
| 37 |
+
"pygments_lexer": "ipython3",
|
| 38 |
+
"version": "3.9.13"
|
| 39 |
+
}
|
| 40 |
+
},
|
| 41 |
+
"nbformat": 4,
|
| 42 |
+
"nbformat_minor": 5
|
| 43 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.19 데이터세트 선택, 분리, 병합.ipynb
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from datasets import concatenate_datasets\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"dataset = load_dataset(\"squad\", split=\"train[:10]\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"chunk1 = dataset.select([0, 1])\n",
|
| 16 |
+
"chunk2 = dataset.shard(num_shards=2, index=0)\n",
|
| 17 |
+
"chunk3 = dataset.shard(num_shards=2, index=1)\n",
|
| 18 |
+
"concat_dataset = concatenate_datasets([chunk1, chunk2, chunk3])\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"print(len(chunk1))\n",
|
| 21 |
+
"print(len(chunk2))\n",
|
| 22 |
+
"print(len(chunk3))\n",
|
| 23 |
+
"print(len(concat_dataset))"
|
| 24 |
+
]
|
| 25 |
+
}
|
| 26 |
+
],
|
| 27 |
+
"metadata": {
|
| 28 |
+
"kernelspec": {
|
| 29 |
+
"display_name": "Python 3 (ipykernel)",
|
| 30 |
+
"language": "python",
|
| 31 |
+
"name": "python3"
|
| 32 |
+
},
|
| 33 |
+
"language_info": {
|
| 34 |
+
"codemirror_mode": {
|
| 35 |
+
"name": "ipython",
|
| 36 |
+
"version": 3
|
| 37 |
+
},
|
| 38 |
+
"file_extension": ".py",
|
| 39 |
+
"mimetype": "text/x-python",
|
| 40 |
+
"name": "python",
|
| 41 |
+
"nbconvert_exporter": "python",
|
| 42 |
+
"pygments_lexer": "ipython3",
|
| 43 |
+
"version": "3.9.13"
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
"nbformat": 4,
|
| 47 |
+
"nbformat_minor": 5
|
| 48 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.20 데이터세트 filter와 map 메서드.ipynb
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import BertTokenizer\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"def filter_short_context(data):\n",
|
| 14 |
+
" return len(data[\"context\"]) <= 1024\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"def tokenize_function(tokenizer, data):\n",
|
| 17 |
+
" inputs = [\n",
|
| 18 |
+
" f\"{question} [SEP] {context}\"\n",
|
| 19 |
+
" for question, context in zip(data[\"question\"], data[\"context\"])\n",
|
| 20 |
+
" ]\n",
|
| 21 |
+
" model_inputs = tokenizer(\n",
|
| 22 |
+
" inputs,\n",
|
| 23 |
+
" max_length=512,\n",
|
| 24 |
+
" padding=\"max_length\",\n",
|
| 25 |
+
" truncation=True,\n",
|
| 26 |
+
" return_tensors=\"pt\"\n",
|
| 27 |
+
" )\n",
|
| 28 |
+
" return model_inputs\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"dataset = load_dataset(\"squad\", split=\"train[:10]\")\n",
|
| 31 |
+
"tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"filtered_dataset = dataset.filter(filter_short_context)\n",
|
| 34 |
+
"tokenized_dataset = filtered_dataset.map(\n",
|
| 35 |
+
" lambda x: tokenize_function(tokenizer, x),\n",
|
| 36 |
+
" batched=True,\n",
|
| 37 |
+
" remove_columns=dataset.column_names\n",
|
| 38 |
+
")\n",
|
| 39 |
+
"tokenized_dataset.set_format(\n",
|
| 40 |
+
" type=\"torch\",\n",
|
| 41 |
+
" columns=[\"input_ids\", \"token_type_ids\", \"attention_mask\"]\n",
|
| 42 |
+
")\n",
|
| 43 |
+
"print(tokenized_dataset)\n",
|
| 44 |
+
"print(tokenized_dataset[0])"
|
| 45 |
+
]
|
| 46 |
+
}
|
| 47 |
+
],
|
| 48 |
+
"metadata": {
|
| 49 |
+
"kernelspec": {
|
| 50 |
+
"display_name": "Python 3 (ipykernel)",
|
| 51 |
+
"language": "python",
|
| 52 |
+
"name": "python3"
|
| 53 |
+
},
|
| 54 |
+
"language_info": {
|
| 55 |
+
"codemirror_mode": {
|
| 56 |
+
"name": "ipython",
|
| 57 |
+
"version": 3
|
| 58 |
+
},
|
| 59 |
+
"file_extension": ".py",
|
| 60 |
+
"mimetype": "text/x-python",
|
| 61 |
+
"name": "python",
|
| 62 |
+
"nbconvert_exporter": "python",
|
| 63 |
+
"pygments_lexer": "ipython3",
|
| 64 |
+
"version": "3.9.13"
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
"nbformat": 4,
|
| 68 |
+
"nbformat_minor": 5
|
| 69 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.21 데이터세트 업로드.ipynb
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import os\n",
|
| 11 |
+
"from collections import defaultdict\n",
|
| 12 |
+
"from datasets import Dataset, Image, DatasetDict\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"data = defaultdict(list)\n",
|
| 15 |
+
"folder_name = \"../images\"\n",
|
| 16 |
+
"for file_name in os.listdir(folder_name):\n",
|
| 17 |
+
" name = os.path.splitext(file_name)[0]\n",
|
| 18 |
+
" path = os.path.join(folder_name, file_name)\n",
|
| 19 |
+
"\n",
|
| 20 |
+
" data[\"name\"].append(name)\n",
|
| 21 |
+
" data[\"image\"].append(path)\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"dataset = Dataset.from_dict(data).cast_column(\"image\", Image())\n",
|
| 24 |
+
"print(data)\n",
|
| 25 |
+
"print(dataset[0])\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"datasetdict = DatasetDict(\n",
|
| 28 |
+
" {\n",
|
| 29 |
+
" \"train\": dataset.select(range(5)),\n",
|
| 30 |
+
" \"valid\": dataset.select(range(5, 10)),\n",
|
| 31 |
+
" \"test\": dataset.select(range(10, len(dataset)))\n",
|
| 32 |
+
" }\n",
|
| 33 |
+
")\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"hub_name = \"<user_name>/<repo_name>\" # 데이터세트 저장소 경로 입력\n",
|
| 36 |
+
"token = \"hf_###...\" # 토큰 입력\n",
|
| 37 |
+
"datasetdict.push_to_hub(hub_name, token=token)"
|
| 38 |
+
]
|
| 39 |
+
}
|
| 40 |
+
],
|
| 41 |
+
"metadata": {
|
| 42 |
+
"kernelspec": {
|
| 43 |
+
"display_name": "Python 3 (ipykernel)",
|
| 44 |
+
"language": "python",
|
| 45 |
+
"name": "python3"
|
| 46 |
+
},
|
| 47 |
+
"language_info": {
|
| 48 |
+
"codemirror_mode": {
|
| 49 |
+
"name": "ipython",
|
| 50 |
+
"version": 3
|
| 51 |
+
},
|
| 52 |
+
"file_extension": ".py",
|
| 53 |
+
"mimetype": "text/x-python",
|
| 54 |
+
"name": "python",
|
| 55 |
+
"nbconvert_exporter": "python",
|
| 56 |
+
"pygments_lexer": "ipython3",
|
| 57 |
+
"version": "3.9.13"
|
| 58 |
+
}
|
| 59 |
+
},
|
| 60 |
+
"nbformat": 4,
|
| 61 |
+
"nbformat_minor": 5
|
| 62 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.22 ~ 2.26 개체명 인식 모델.ipynb
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "39d707db",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import AutoModelForTokenClassification, AutoTokenizer\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"dataset = load_dataset(\"klue\", \"ner\")\n",
|
| 14 |
+
"labels = dataset[\"train\"].features[\"ner_tags\"].feature.names\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"model_name = \"Leo97/KoELECTRA-small-v3-modu-ner\"\n",
|
| 17 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
|
| 18 |
+
"model = AutoModelForTokenClassification.from_pretrained(\n",
|
| 19 |
+
" model_name,\n",
|
| 20 |
+
" num_labels=len(labels),\n",
|
| 21 |
+
" ignore_mismatched_sizes=True\n",
|
| 22 |
+
")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(dataset[\"train\"])\n",
|
| 25 |
+
"print(dataset[\"train\"][0])\n",
|
| 26 |
+
"print(labels)"
|
| 27 |
+
]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"id": "56149149",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"outputs": [],
|
| 35 |
+
"source": [
|
| 36 |
+
"def preprocess_data(example, tokenizer):\n",
|
| 37 |
+
" sentence = \"\".join(example[\"tokens\"]).replace(\"\\xa0\", \" \")\n",
|
| 38 |
+
" encoded = tokenizer(\n",
|
| 39 |
+
" sentence,\n",
|
| 40 |
+
" return_offsets_mapping=True,\n",
|
| 41 |
+
" add_special_tokens=False,\n",
|
| 42 |
+
" padding=False,\n",
|
| 43 |
+
" truncation=False\n",
|
| 44 |
+
" )\n",
|
| 45 |
+
"\n",
|
| 46 |
+
" labels = []\n",
|
| 47 |
+
" for offset in encoded.offset_mapping:\n",
|
| 48 |
+
" if offset[0] == offset[1]:\n",
|
| 49 |
+
" labels.append(-100)\n",
|
| 50 |
+
" else:\n",
|
| 51 |
+
" labels.append(example[\"ner_tags\"][offset[0]])\n",
|
| 52 |
+
" encoded[\"labels\"] = labels\n",
|
| 53 |
+
" return encoded\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"processed_dataset = dataset.map(\n",
|
| 57 |
+
" lambda example: preprocess_data(example, tokenizer),\n",
|
| 58 |
+
" batched=False,\n",
|
| 59 |
+
" remove_columns=dataset[\"train\"].column_names\n",
|
| 60 |
+
")\n",
|
| 61 |
+
"print(processed_dataset)\n",
|
| 62 |
+
"print(dataset[\"train\"][0][\"ner_tags\"])\n",
|
| 63 |
+
"print(processed_dataset[\"train\"][0][\"offset_mapping\"])\n",
|
| 64 |
+
"print(processed_dataset[\"train\"][0][\"labels\"])"
|
| 65 |
+
]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"id": "f0aac748",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"outputs": [],
|
| 73 |
+
"source": [
|
| 74 |
+
"from transformers import Trainer, TrainingArguments\n",
|
| 75 |
+
"from transformers.data.data_collator import DataCollatorForTokenClassification\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"training_args = TrainingArguments(\n",
|
| 78 |
+
" output_dir=\"token-classification\",\n",
|
| 79 |
+
" evaluation_strategy=\"epoch\",\n",
|
| 80 |
+
" per_device_train_batch_size=32,\n",
|
| 81 |
+
" per_device_eval_batch_size=32,\n",
|
| 82 |
+
" learning_rate=1e-4,\n",
|
| 83 |
+
" weight_decay=0.01,\n",
|
| 84 |
+
" num_train_epochs=5,\n",
|
| 85 |
+
" seed=42\n",
|
| 86 |
+
")\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"trainer = Trainer(\n",
|
| 89 |
+
" model=model,\n",
|
| 90 |
+
" args=training_args,\n",
|
| 91 |
+
" train_dataset=processed_dataset[\"train\"],\n",
|
| 92 |
+
" eval_dataset=processed_dataset[\"validation\"],\n",
|
| 93 |
+
" data_collator=DataCollatorForTokenClassification(tokenizer=tokenizer, padding=True)\n",
|
| 94 |
+
")\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"trainer.train()"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"id": "ab38d1e5",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"outputs": [],
|
| 105 |
+
"source": [
|
| 106 |
+
"import torch\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"model.eval()\n",
|
| 109 |
+
"text = \"위키북스의 윤대희, 김동화, 송종민 그리고 진현두는 2025년 서울에서 2시간 동안 신간 1권에 관한 논의를 진행했다.\"\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"with torch.no_grad():\n",
|
| 112 |
+
" tokenized = tokenizer(\n",
|
| 113 |
+
" text,\n",
|
| 114 |
+
" return_tensors=\"pt\",\n",
|
| 115 |
+
" padding=True,\n",
|
| 116 |
+
" truncation=True,\n",
|
| 117 |
+
" max_length=512,\n",
|
| 118 |
+
" add_special_tokens=False\n",
|
| 119 |
+
" )\n",
|
| 120 |
+
" logits = model(**tokenized.to(\"cuda\")).logits.cpu()\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"predictions = logits.argmax(dim=-1)[0].tolist()\n",
|
| 123 |
+
"tokens = tokenizer.tokenize(text)\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"print(list(zip(tokens, [labels[i] for i in predictions])))"
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
],
|
| 129 |
+
"metadata": {
|
| 130 |
+
"kernelspec": {
|
| 131 |
+
"display_name": "Python 3 (ipykernel)",
|
| 132 |
+
"language": "python",
|
| 133 |
+
"name": "python3"
|
| 134 |
+
},
|
| 135 |
+
"language_info": {
|
| 136 |
+
"codemirror_mode": {
|
| 137 |
+
"name": "ipython",
|
| 138 |
+
"version": 3
|
| 139 |
+
},
|
| 140 |
+
"file_extension": ".py",
|
| 141 |
+
"mimetype": "text/x-python",
|
| 142 |
+
"name": "python",
|
| 143 |
+
"nbconvert_exporter": "python",
|
| 144 |
+
"pygments_lexer": "ipython3",
|
| 145 |
+
"version": "3.9.13"
|
| 146 |
+
}
|
| 147 |
+
},
|
| 148 |
+
"nbformat": 4,
|
| 149 |
+
"nbformat_minor": 5
|
| 150 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.27 이미지 모델 평가 수행.ipynb
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import torch\n",
|
| 15 |
+
"import evaluate\n",
|
| 16 |
+
"import numpy as np\n",
|
| 17 |
+
"from datasets import load_dataset\n",
|
| 18 |
+
"from transformers import AutoImageProcessor, AutoModelForImageClassification\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"dataset = load_dataset(\"cifar10\", split=\"test[:1000]\")\n",
|
| 21 |
+
"model_name = \"nateraw/vit-base-patch16-224-cifar10\"\n",
|
| 22 |
+
"model = AutoModelForImageClassification.from_pretrained(model_name)\n",
|
| 23 |
+
"image_processor = AutoImageProcessor.from_pretrained(model_name)\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"model.eval()\n",
|
| 26 |
+
"batch_size = 32\n",
|
| 27 |
+
"logits, labels = [], []\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"for i in range(0, len(dataset), batch_size):\n",
|
| 30 |
+
" batch = dataset[i : i + batch_size]\n",
|
| 31 |
+
"\n",
|
| 32 |
+
" with torch.no_grad():\n",
|
| 33 |
+
" inputs = image_processor(batch[\"img\"], return_tensors=\"pt\")\n",
|
| 34 |
+
" outputs = model(inputs[\"pixel_values\"])\n",
|
| 35 |
+
"\n",
|
| 36 |
+
" logits.extend(outputs.logits.cpu().numpy())\n",
|
| 37 |
+
" labels.extend(batch[\"label\"])\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"preds = np.argmax(logits, axis=-1)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"metric = evaluate.load(\"accuracy\")\n",
|
| 42 |
+
"accuracy = metric.compute(predictions=preds, references=labels)\n",
|
| 43 |
+
"print(accuracy)\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"metric = evaluate.load(\"f1\")\n",
|
| 46 |
+
"f1 = metric.compute(predictions=preds, references=labels, average=\"macro\")\n",
|
| 47 |
+
"print(f1)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"comparison = evaluate.load(\"exact_match\", module_type=\"comparison\")\n",
|
| 50 |
+
"exact_match = comparison.compute(predictions1=preds, predictions2=labels)\n",
|
| 51 |
+
"print(exact_match)\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"measurement = evaluate.load(\"label_distribution\", module_type=\"measurement\")\n",
|
| 54 |
+
"distribution = measurement.compute(data=labels)\n",
|
| 55 |
+
"print(distribution)\n"
|
| 56 |
+
]
|
| 57 |
+
}
|
| 58 |
+
],
|
| 59 |
+
"metadata": {
|
| 60 |
+
"kernelspec": {
|
| 61 |
+
"display_name": "Python 3 (ipykernel)",
|
| 62 |
+
"language": "python",
|
| 63 |
+
"name": "python3"
|
| 64 |
+
},
|
| 65 |
+
"language_info": {
|
| 66 |
+
"codemirror_mode": {
|
| 67 |
+
"name": "ipython",
|
| 68 |
+
"version": 3
|
| 69 |
+
},
|
| 70 |
+
"file_extension": ".py",
|
| 71 |
+
"mimetype": "text/x-python",
|
| 72 |
+
"name": "python",
|
| 73 |
+
"nbconvert_exporter": "python",
|
| 74 |
+
"pygments_lexer": "ipython3",
|
| 75 |
+
"version": "3.9.13"
|
| 76 |
+
}
|
| 77 |
+
},
|
| 78 |
+
"nbformat": 4,
|
| 79 |
+
"nbformat_minor": 5
|
| 80 |
+
}
|
2장 허깅페이스 트랜스포머/예제 2.28 레이더 차트 시각화.ipynb
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from evaluate.visualization import radar_plot\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"data = [\n",
|
| 17 |
+
" {\"accuracy\": 0.49, \"precision\": 0.50, \"f1\": 0.49, \"latency_in_seconds\": 0.15},\n",
|
| 18 |
+
" {\"accuracy\": 0.92, \"precision\": 0.93, \"f1\": 0.92, \"latency_in_seconds\": 0.10},\n",
|
| 19 |
+
" {\"accuracy\": 0.68, \"precision\": 0.70, \"f1\": 0.68, \"latency_in_seconds\": 0.12}, \n",
|
| 20 |
+
" {\"accuracy\": 0.78, \"precision\": 0.80, \"f1\": 0.78, \"latency_in_seconds\": 0.11}\n",
|
| 21 |
+
"]\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"model_names = [\"Model 1\", \"Model 2\", \"Model 3\", \"Model 4\"]\n",
|
| 24 |
+
"plot = radar_plot(data=data, model_names=model_names)\n",
|
| 25 |
+
"plot.show()"
|
| 26 |
+
]
|
| 27 |
+
}
|
| 28 |
+
],
|
| 29 |
+
"metadata": {
|
| 30 |
+
"kernelspec": {
|
| 31 |
+
"display_name": "Python 3 (ipykernel)",
|
| 32 |
+
"language": "python",
|
| 33 |
+
"name": "python3"
|
| 34 |
+
},
|
| 35 |
+
"language_info": {
|
| 36 |
+
"codemirror_mode": {
|
| 37 |
+
"name": "ipython",
|
| 38 |
+
"version": 3
|
| 39 |
+
},
|
| 40 |
+
"file_extension": ".py",
|
| 41 |
+
"mimetype": "text/x-python",
|
| 42 |
+
"name": "python",
|
| 43 |
+
"nbconvert_exporter": "python",
|
| 44 |
+
"pygments_lexer": "ipython3",
|
| 45 |
+
"version": "3.9.13"
|
| 46 |
+
}
|
| 47 |
+
},
|
| 48 |
+
"nbformat": 4,
|
| 49 |
+
"nbformat_minor": 5
|
| 50 |
+
}
|
3장 자연어 처리/예제 3.01 BERT 토크나이저를 이용한 토큰화.ipynb
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from transformers import BertTokenizer\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"tokenizer = BertTokenizer.from_pretrained(\"google-bert/bert-base-multilingual-uncased\")\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"text = \"Transformers Is so COOL\"\n",
|
| 19 |
+
"encoded = tokenizer(text)\n",
|
| 20 |
+
"print(encoded)\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"input_ids = encoded[\"input_ids\"]\n",
|
| 23 |
+
"decoded = tokenizer.decode(input_ids)\n",
|
| 24 |
+
"print(decoded)"
|
| 25 |
+
]
|
| 26 |
+
}
|
| 27 |
+
],
|
| 28 |
+
"metadata": {
|
| 29 |
+
"kernelspec": {
|
| 30 |
+
"display_name": "Python 3 (ipykernel)",
|
| 31 |
+
"language": "python",
|
| 32 |
+
"name": "python3"
|
| 33 |
+
},
|
| 34 |
+
"language_info": {
|
| 35 |
+
"codemirror_mode": {
|
| 36 |
+
"name": "ipython",
|
| 37 |
+
"version": 3
|
| 38 |
+
},
|
| 39 |
+
"file_extension": ".py",
|
| 40 |
+
"mimetype": "text/x-python",
|
| 41 |
+
"name": "python",
|
| 42 |
+
"nbconvert_exporter": "python",
|
| 43 |
+
"pygments_lexer": "ipython3",
|
| 44 |
+
"version": "3.9.13"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"nbformat": 4,
|
| 48 |
+
"nbformat_minor": 5
|
| 49 |
+
}
|
3장 자연어 처리/예제 3.02 BERT 모델 구조.ipynb
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from transformers import BertModel\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"model = BertModel.from_pretrained(\"google-bert/bert-base-multilingual-uncased\")\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"for main_name, main_module in model.named_children():\n",
|
| 19 |
+
" print(main_name)\n",
|
| 20 |
+
" for sub_name, sub_module in main_module.named_children():\n",
|
| 21 |
+
" print(\"└\", sub_name)\n",
|
| 22 |
+
" for ssub_name, ssub_module in sub_module.named_children():\n",
|
| 23 |
+
" print(\"│ └\", ssub_name)\n",
|
| 24 |
+
" for sssub_name, sssub_module in ssub_module.named_children():\n",
|
| 25 |
+
" print(\"│ │ └\", sssub_name)"
|
| 26 |
+
]
|
| 27 |
+
}
|
| 28 |
+
],
|
| 29 |
+
"metadata": {
|
| 30 |
+
"kernelspec": {
|
| 31 |
+
"display_name": "Python 3 (ipykernel)",
|
| 32 |
+
"language": "python",
|
| 33 |
+
"name": "python3"
|
| 34 |
+
},
|
| 35 |
+
"language_info": {
|
| 36 |
+
"codemirror_mode": {
|
| 37 |
+
"name": "ipython",
|
| 38 |
+
"version": 3
|
| 39 |
+
},
|
| 40 |
+
"file_extension": ".py",
|
| 41 |
+
"mimetype": "text/x-python",
|
| 42 |
+
"name": "python",
|
| 43 |
+
"nbconvert_exporter": "python",
|
| 44 |
+
"pygments_lexer": "ipython3",
|
| 45 |
+
"version": "3.9.13"
|
| 46 |
+
}
|
| 47 |
+
},
|
| 48 |
+
"nbformat": 4,
|
| 49 |
+
"nbformat_minor": 5
|
| 50 |
+
}
|
3장 자연어 처리/예제 3.03 ~ 3.07 텍스트 분류 모델.ipynb
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from datasets import load_dataset\n",
|
| 11 |
+
"from transformers import BertTokenizer, BertForSequenceClassification\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"def preprocess_data(example, tokenizer):\n",
|
| 14 |
+
" return tokenizer(example[\"document\"], truncation=True)\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"model_name = \"google-bert/bert-base-multilingual-uncased\"\n",
|
| 17 |
+
"tokenizer = BertTokenizer.from_pretrained(model_name)\n",
|
| 18 |
+
"model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"dataset = load_dataset(\"nsmc\", trust_remote_code=True)\n",
|
| 21 |
+
"processed_dataset = dataset.map(\n",
|
| 22 |
+
" lambda example: preprocess_data(example, tokenizer),\n",
|
| 23 |
+
" batched=True,\n",
|
| 24 |
+
" remove_columns=[\"id\", \"document\"]\n",
|
| 25 |
+
").rename_column(\"label\", \"labels\")\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(dataset)\n",
|
| 28 |
+
"print(processed_dataset)\n",
|
| 29 |
+
"print(dataset[\"train\"][0])\n",
|
| 30 |
+
"print(processed_dataset[\"train\"][0])"
|
| 31 |
+
]
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"id": "ca996961",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"outputs": [],
|
| 39 |
+
"source": [
|
| 40 |
+
"from torch.utils.data import DataLoader\n",
|
| 41 |
+
"from transformers import DataCollatorWithPadding\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"max_length_collator = DataCollatorWithPadding(\n",
|
| 44 |
+
" tokenizer=tokenizer,\n",
|
| 45 |
+
" padding=\"max_length\"\n",
|
| 46 |
+
")\n",
|
| 47 |
+
"max_length_dataloader = DataLoader(\n",
|
| 48 |
+
" processed_dataset[\"train\"],\n",
|
| 49 |
+
" collate_fn=max_length_collator,\n",
|
| 50 |
+
" batch_size=4,\n",
|
| 51 |
+
" shuffle=False\n",
|
| 52 |
+
")\n",
|
| 53 |
+
"max_length_iterator = iter(max_length_dataloader)\n",
|
| 54 |
+
"max_lnegth_batch = next(max_length_iterator)\n",
|
| 55 |
+
"print(\"max_length 패딩 입력 id shape :\", max_lnegth_batch[\"input_ids\"].shape)\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"longest_collator = DataCollatorWithPadding(\n",
|
| 58 |
+
" tokenizer=tokenizer,\n",
|
| 59 |
+
" padding=\"longest\"\n",
|
| 60 |
+
")\n",
|
| 61 |
+
"longest_dataloader = DataLoader(\n",
|
| 62 |
+
" processed_dataset[\"train\"],\n",
|
| 63 |
+
" collate_fn=longest_collator,\n",
|
| 64 |
+
" batch_size=4,\n",
|
| 65 |
+
" shuffle=False\n",
|
| 66 |
+
")\n",
|
| 67 |
+
"longest_iterator = iter(longest_dataloader)\n",
|
| 68 |
+
"longest_batch = next(longest_iterator)\n",
|
| 69 |
+
"print(\"longest 패딩 입력 id shape :\", longest_batch[\"input_ids\"].shape)"
|
| 70 |
+
]
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"id": "f3fe00b8",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"outputs": [],
|
| 78 |
+
"source": [
|
| 79 |
+
"from transformers import TrainingArguments, Trainer\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"training_args = TrainingArguments(\n",
|
| 82 |
+
" output_dir=\"text-classification\",\n",
|
| 83 |
+
" per_device_train_batch_size=8,\n",
|
| 84 |
+
" per_device_eval_batch_size=16,\n",
|
| 85 |
+
" learning_rate=5e-5,\n",
|
| 86 |
+
" num_train_epochs=1,\n",
|
| 87 |
+
" eval_steps=200,\n",
|
| 88 |
+
" logging_steps=200,\n",
|
| 89 |
+
" seed=42\n",
|
| 90 |
+
")\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"trainer = Trainer(\n",
|
| 93 |
+
" model=model,\n",
|
| 94 |
+
" args=training_args,\n",
|
| 95 |
+
" data_collator=longest_collator,\n",
|
| 96 |
+
" train_dataset=processed_dataset[\"train\"].select(range(10000)),\n",
|
| 97 |
+
" eval_dataset=processed_dataset[\"test\"].select(range(100))\n",
|
| 98 |
+
")\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"trainer.train()"
|
| 101 |
+
]
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"id": "4f2642b5",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"outputs": [],
|
| 109 |
+
"source": [
|
| 110 |
+
"import torch\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"model.eval()\n",
|
| 113 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 114 |
+
"model.to(device)\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"text = \"진짜 재밌었어요. 또 보러 갈거에요\"\n",
|
| 117 |
+
"inputs = tokenizer(text, return_tensors=\"pt\")\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"with torch.no_grad():\n",
|
| 120 |
+
" outputs = model(**inputs.to(device))\n",
|
| 121 |
+
" print(outputs.logits)\n",
|
| 122 |
+
" print(outputs.logits.argmax())"
|
| 123 |
+
]
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"id": "2d2703ab",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"outputs": [],
|
| 131 |
+
"source": [
|
| 132 |
+
"import evaluate\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"yhat = trainer.predict(processed_dataset[\"test\"])\n",
|
| 135 |
+
"predictions = yhat.predictions.argmax(axis=1)\n",
|
| 136 |
+
"references = yhat.label_ids\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"metric = evaluate.load(\"accuracy\")\n",
|
| 139 |
+
"accuracy = metric.compute(predictions=predictions, references=references)\n",
|
| 140 |
+
"print(accuracy)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"metric = evaluate.load(\"f1\")\n",
|
| 143 |
+
"f1 = metric.compute(predictions=predictions, references=references)\n",
|
| 144 |
+
"print(f1)"
|
| 145 |
+
]
|
| 146 |
+
}
|
| 147 |
+
],
|
| 148 |
+
"metadata": {
|
| 149 |
+
"kernelspec": {
|
| 150 |
+
"display_name": "Python 3 (ipykernel)",
|
| 151 |
+
"language": "python",
|
| 152 |
+
"name": "python3"
|
| 153 |
+
},
|
| 154 |
+
"language_info": {
|
| 155 |
+
"codemirror_mode": {
|
| 156 |
+
"name": "ipython",
|
| 157 |
+
"version": 3
|
| 158 |
+
},
|
| 159 |
+
"file_extension": ".py",
|
| 160 |
+
"mimetype": "text/x-python",
|
| 161 |
+
"name": "python",
|
| 162 |
+
"nbconvert_exporter": "python",
|
| 163 |
+
"pygments_lexer": "ipython3",
|
| 164 |
+
"version": "3.10.12"
|
| 165 |
+
}
|
| 166 |
+
},
|
| 167 |
+
"nbformat": 4,
|
| 168 |
+
"nbformat_minor": 5
|
| 169 |
+
}
|
3장 자연어 처리/예제 3.08 ~ 3.09 BART 구조.ipynb
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from transformers import BartTokenizerFast\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"tokenizer = BartTokenizerFast.from_pretrained(\"gogamza/kobart-base-v2\")\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"text = \"BART는 요약 모델을 학습하기에 적합하다.\"\n",
|
| 19 |
+
"encoded = tokenizer(text)\n",
|
| 20 |
+
"print(encoded)"
|
| 21 |
+
]
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"execution_count": null,
|
| 26 |
+
"id": "a5ec6a70",
|
| 27 |
+
"metadata": {
|
| 28 |
+
"vscode": {
|
| 29 |
+
"languageId": "plaintext"
|
| 30 |
+
}
|
| 31 |
+
},
|
| 32 |
+
"outputs": [],
|
| 33 |
+
"source": [
|
| 34 |
+
"from transformers import BartForConditionalGeneration\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"model = BartForConditionalGeneration.from_pretrained(\"gogamza/kobart-base-v2\")\n",
|
| 37 |
+
"for main_name, main_module in model.named_children():\n",
|
| 38 |
+
" print(main_name)\n",
|
| 39 |
+
" for sub_name, sub_module in main_module.named_children():\n",
|
| 40 |
+
" print(\"└\", sub_name)\n",
|
| 41 |
+
" for ssub_name, ssub_module in sub_module.named_children():\n",
|
| 42 |
+
" print(\"│ └\", ssub_name)\n",
|
| 43 |
+
" for sssub_name, sssub_module in ssub_module.named_children():\n",
|
| 44 |
+
" print(\"│ │ └\", sssub_name)"
|
| 45 |
+
]
|
| 46 |
+
}
|
| 47 |
+
],
|
| 48 |
+
"metadata": {
|
| 49 |
+
"kernelspec": {
|
| 50 |
+
"display_name": "Python 3 (ipykernel)",
|
| 51 |
+
"language": "python",
|
| 52 |
+
"name": "python3"
|
| 53 |
+
},
|
| 54 |
+
"language_info": {
|
| 55 |
+
"codemirror_mode": {
|
| 56 |
+
"name": "ipython",
|
| 57 |
+
"version": 3
|
| 58 |
+
},
|
| 59 |
+
"file_extension": ".py",
|
| 60 |
+
"mimetype": "text/x-python",
|
| 61 |
+
"name": "python",
|
| 62 |
+
"nbconvert_exporter": "python",
|
| 63 |
+
"pygments_lexer": "ipython3",
|
| 64 |
+
"version": "3.9.13"
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
"nbformat": 4,
|
| 68 |
+
"nbformat_minor": 5
|
| 69 |
+
}
|
3장 자연어 처리/예제 3.10 ~ 3.14 요약문 생성 모델.ipynb
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from datasets import load_dataset\n",
|
| 15 |
+
"from transformers import BartTokenizerFast, BartForConditionalGeneration\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"def preprocess_data(example, tokenizer):\n",
|
| 18 |
+
" return tokenizer(\n",
|
| 19 |
+
" example[\"document\"],\n",
|
| 20 |
+
" text_target=example[\"summary\"],\n",
|
| 21 |
+
" truncation=True\n",
|
| 22 |
+
" )\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"model_name = \"gogamza/kobart-base-v2\"\n",
|
| 25 |
+
"tokenizer = BartTokenizerFast.from_pretrained(model_name)\n",
|
| 26 |
+
"model = BartForConditionalGeneration.from_pretrained(model_name)\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"dataset = load_dataset(\"daekeun-ml/naver-news-summarization-ko\")\n",
|
| 29 |
+
"print(dataset)\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"tokenizer.model_max_length = model.config.max_position_embeddings\n",
|
| 32 |
+
"processed_dataset = dataset.map(\n",
|
| 33 |
+
" lambda example: preprocess_data(example, tokenizer),\n",
|
| 34 |
+
" batched=True,\n",
|
| 35 |
+
" remove_columns=dataset[\"train\"].column_names\n",
|
| 36 |
+
")\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"sample = processed_dataset[\"train\"][\"labels\"][0]\n",
|
| 39 |
+
"print(sample)\n",
|
| 40 |
+
"print(tokenizer.decode(sample))"
|
| 41 |
+
]
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"cell_type": "code",
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"id": "1ab68856",
|
| 47 |
+
"metadata": {
|
| 48 |
+
"vscode": {
|
| 49 |
+
"languageId": "plaintext"
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"outputs": [],
|
| 53 |
+
"source": [
|
| 54 |
+
"from torch.utils.data import DataLoader\n",
|
| 55 |
+
"from transformers import DataCollatorForSeq2Seq\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"seq2seq_collator = DataCollatorForSeq2Seq(\n",
|
| 58 |
+
" tokenizer=tokenizer,\n",
|
| 59 |
+
" padding=\"longest\",\n",
|
| 60 |
+
" return_tensors=\"pt\"\n",
|
| 61 |
+
")\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"seq2seq_dataloader = DataLoader(\n",
|
| 64 |
+
" processed_dataset[\"train\"],\n",
|
| 65 |
+
" collate_fn=seq2seq_collator,\n",
|
| 66 |
+
" batch_size=4,\n",
|
| 67 |
+
" shuffle=False\n",
|
| 68 |
+
")\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"seq2seq_iterator = iter(seq2seq_dataloader)\n",
|
| 71 |
+
"seq2seq_batch = next(seq2seq_iterator)\n",
|
| 72 |
+
"for key, value in seq2seq_batch.items():\n",
|
| 73 |
+
" print(f\"{key} : {value.shape}\")"
|
| 74 |
+
]
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"id": "0536d7d0",
|
| 80 |
+
"metadata": {
|
| 81 |
+
"vscode": {
|
| 82 |
+
"languageId": "plaintext"
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
"outputs": [],
|
| 86 |
+
"source": [
|
| 87 |
+
"from transformers import Seq2SeqTrainingArguments, Seq2SeqTrainer\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"training_args = Seq2SeqTrainingArguments(\n",
|
| 90 |
+
" output_dir=\"text-summarization\",\n",
|
| 91 |
+
" per_device_train_batch_size=8,\n",
|
| 92 |
+
" per_device_eval_batch_size=16,\n",
|
| 93 |
+
" learning_rate=5e-5,\n",
|
| 94 |
+
" num_train_epochs=1,\n",
|
| 95 |
+
" eval_steps=200,\n",
|
| 96 |
+
" logging_steps=200,\n",
|
| 97 |
+
" seed=42\n",
|
| 98 |
+
")\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"trainer = Seq2SeqTrainer(\n",
|
| 101 |
+
" model=model,\n",
|
| 102 |
+
" args=training_args,\n",
|
| 103 |
+
" data_collator=seq2seq_collator,\n",
|
| 104 |
+
" train_dataset=processed_dataset[\"train\"].select(range(10000)),\n",
|
| 105 |
+
" eval_dataset=processed_dataset[\"validation\"].select(range(100))\n",
|
| 106 |
+
")\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"trainer.train()"
|
| 109 |
+
]
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"id": "45bd400b",
|
| 115 |
+
"metadata": {
|
| 116 |
+
"vscode": {
|
| 117 |
+
"languageId": "plaintext"
|
| 118 |
+
}
|
| 119 |
+
},
|
| 120 |
+
"outputs": [],
|
| 121 |
+
"source": [
|
| 122 |
+
"import torch\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"model.eval()\n",
|
| 125 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 126 |
+
"model.to(device)\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"sample = dataset[\"test\"][0]\n",
|
| 129 |
+
"document = sample[\"document\"]\n",
|
| 130 |
+
"inputs = tokenizer(document, return_tensors=\"pt\").to(device)\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"with torch.no_grad():\n",
|
| 133 |
+
" outputs = model.generate(\n",
|
| 134 |
+
" **inputs,\n",
|
| 135 |
+
" max_length=256,\n",
|
| 136 |
+
" num_beams=4,\n",
|
| 137 |
+
" no_repeat_ngram_size=2,\n",
|
| 138 |
+
" early_stopping=True\n",
|
| 139 |
+
" )\n",
|
| 140 |
+
"print(\"원문 :\", document)\n",
|
| 141 |
+
"print(\"정답 요약문 :\", sample[\"summary\"])\n",
|
| 142 |
+
"print(\"생성 요약문 :\", tokenizer.decode(outputs[0], skip_special_tokens=True))"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"id": "d4e44df8",
|
| 149 |
+
"metadata": {
|
| 150 |
+
"vscode": {
|
| 151 |
+
"languageId": "plaintext"
|
| 152 |
+
}
|
| 153 |
+
},
|
| 154 |
+
"outputs": [],
|
| 155 |
+
"source": [
|
| 156 |
+
"!pip install rouge_score"
|
| 157 |
+
]
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"id": "727fabd2",
|
| 163 |
+
"metadata": {
|
| 164 |
+
"vscode": {
|
| 165 |
+
"languageId": "plaintext"
|
| 166 |
+
}
|
| 167 |
+
},
|
| 168 |
+
"outputs": [],
|
| 169 |
+
"source": [
|
| 170 |
+
"import evaluate\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"test_loader = DataLoader(\n",
|
| 173 |
+
" processed_dataset[\"test\"].select(range(100)),\n",
|
| 174 |
+
" collate_fn=seq2seq_collator,\n",
|
| 175 |
+
" batch_size=4,\n",
|
| 176 |
+
" shuffle=False\n",
|
| 177 |
+
")\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"generated_summaries = []\n",
|
| 180 |
+
"true_summaries = dataset[\"test\"].select(range(100))[\"summary\"]\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"with torch.no_grad():\n",
|
| 183 |
+
" for batch in test_loader:\n",
|
| 184 |
+
" batch = batch.to(device)\n",
|
| 185 |
+
" output = model.generate(\n",
|
| 186 |
+
" **batch,\n",
|
| 187 |
+
" max_length=1026,\n",
|
| 188 |
+
" num_beams=4,\n",
|
| 189 |
+
" no_repeat_ngram_size=2,\n",
|
| 190 |
+
" early_stopping=True\n",
|
| 191 |
+
" )\n",
|
| 192 |
+
" batch_summaries = tokenizer.batch_decode(output, skip_special_tokens=True)\n",
|
| 193 |
+
" generated_summaries.extend(batch_summaries)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"metric = evaluate.load(\"rouge\")\n",
|
| 196 |
+
"rouge_scores = metric.compute(predictions=generated_summaries, references=true_summaries)\n",
|
| 197 |
+
"print(rouge_scores)"
|
| 198 |
+
]
|
| 199 |
+
}
|
| 200 |
+
],
|
| 201 |
+
"metadata": {
|
| 202 |
+
"kernelspec": {
|
| 203 |
+
"display_name": "Python 3 (ipykernel)",
|
| 204 |
+
"language": "python",
|
| 205 |
+
"name": "python3"
|
| 206 |
+
},
|
| 207 |
+
"language_info": {
|
| 208 |
+
"codemirror_mode": {
|
| 209 |
+
"name": "ipython",
|
| 210 |
+
"version": 3
|
| 211 |
+
},
|
| 212 |
+
"file_extension": ".py",
|
| 213 |
+
"mimetype": "text/x-python",
|
| 214 |
+
"name": "python",
|
| 215 |
+
"nbconvert_exporter": "python",
|
| 216 |
+
"pygments_lexer": "ipython3",
|
| 217 |
+
"version": "3.9.13"
|
| 218 |
+
}
|
| 219 |
+
},
|
| 220 |
+
"nbformat": 4,
|
| 221 |
+
"nbformat_minor": 5
|
| 222 |
+
}
|
3장 자연어 처리/예제 3.15 ~ 3.18 추출 질의 응답 모델.ipynb
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e4ce77ca",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from datasets import load_dataset\n",
|
| 15 |
+
"from transformers import RobertaTokenizerFast, RobertaForQuestionAnswering\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"def preprocess_data(example, tokenizer):\n",
|
| 18 |
+
" tokenized = tokenizer(\n",
|
| 19 |
+
" example[\"question\"],\n",
|
| 20 |
+
" example[\"context\"],\n",
|
| 21 |
+
" truncation=\"only_second\",\n",
|
| 22 |
+
" return_offsets_mapping=True\n",
|
| 23 |
+
" )\n",
|
| 24 |
+
" start_index = example[\"answers\"][\"answer_start\"][0]\n",
|
| 25 |
+
" answer_text = example[\"answers\"][\"text\"][0]\n",
|
| 26 |
+
" answer_tokens = tokenizer.encode(answer_text, add_special_tokens=False)\n",
|
| 27 |
+
" answer_tokens_length = len(answer_tokens)\n",
|
| 28 |
+
"\n",
|
| 29 |
+
" start_context_tokens_index = tokenized[\"input_ids\"].index(tokenizer.sep_token_id)\n",
|
| 30 |
+
" context_offset_mapping = tokenized[\"offset_mapping\"][start_context_tokens_index:]\n",
|
| 31 |
+
" tokenized[\"start_positions\"] = len(tokenized[\"input_ids\"])\n",
|
| 32 |
+
" tokenized[\"end_positions\"] = len(tokenized[\"input_ids\"])\n",
|
| 33 |
+
" \n",
|
| 34 |
+
" for i, (start_offset, end_offset) in enumerate(context_offset_mapping):\n",
|
| 35 |
+
" if start_offset >= start_index:\n",
|
| 36 |
+
" tokenized[\"start_positions\"] = start_context_tokens_index + i\n",
|
| 37 |
+
" tokenized[\"end_positions\"] = tokenized[\"start_positions\"] + answer_tokens_length\n",
|
| 38 |
+
" break\n",
|
| 39 |
+
"\n",
|
| 40 |
+
" return tokenized\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"model_name = \"klue/roberta-base\"\n",
|
| 43 |
+
"tokenizer = RobertaTokenizerFast.from_pretrained(model_name)\n",
|
| 44 |
+
"model = RobertaForQuestionAnswering.from_pretrained(model_name)\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"dataset = load_dataset(\"klue\", \"mrc\")\n",
|
| 47 |
+
"processed_dataset = dataset.filter(lambda x: not x[\"is_impossible\"])\n",
|
| 48 |
+
"processed_dataset = processed_dataset.map(\n",
|
| 49 |
+
" lambda example: preprocess_data(example, tokenizer), batched=False\n",
|
| 50 |
+
")\n",
|
| 51 |
+
"processed_dataset = processed_dataset.filter(\n",
|
| 52 |
+
" lambda x: x[\"start_positions\"] < tokenizer.model_max_length\n",
|
| 53 |
+
")\n",
|
| 54 |
+
"processed_dataset = processed_dataset.filter(\n",
|
| 55 |
+
" lambda x: x[\"end_positions\"] < tokenizer.model_max_length\n",
|
| 56 |
+
")\n",
|
| 57 |
+
"print(dataset)\n",
|
| 58 |
+
"print(processed_dataset)"
|
| 59 |
+
]
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"id": "ce30aba3",
|
| 65 |
+
"metadata": {
|
| 66 |
+
"vscode": {
|
| 67 |
+
"languageId": "plaintext"
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
"outputs": [],
|
| 71 |
+
"source": [
|
| 72 |
+
"from transformers import DataCollatorWithPadding, TrainingArguments, Trainer\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"collator = DataCollatorWithPadding(tokenizer, padding=\"longest\")\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"training_arguments = TrainingArguments(\n",
|
| 77 |
+
" output_dir=\"question-answering\",\n",
|
| 78 |
+
" per_device_train_batch_size=8,\n",
|
| 79 |
+
" per_device_eval_batch_size=16,\n",
|
| 80 |
+
" learning_rate=5e-5,\n",
|
| 81 |
+
" num_train_epochs=1,\n",
|
| 82 |
+
" eval_steps=250,\n",
|
| 83 |
+
" logging_steps=250,\n",
|
| 84 |
+
" seed=42\n",
|
| 85 |
+
")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"trainer = Trainer(\n",
|
| 88 |
+
" model=model,\n",
|
| 89 |
+
" args=training_arguments,\n",
|
| 90 |
+
" data_collator=collator,\n",
|
| 91 |
+
" train_dataset=processed_dataset[\"train\"].select(range(10000)),\n",
|
| 92 |
+
" eval_dataset=processed_dataset[\"validation\"].select(range(100))\n",
|
| 93 |
+
")\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"trainer.train()"
|
| 96 |
+
]
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"id": "51a813f0",
|
| 102 |
+
"metadata": {
|
| 103 |
+
"vscode": {
|
| 104 |
+
"languageId": "plaintext"
|
| 105 |
+
}
|
| 106 |
+
},
|
| 107 |
+
"outputs": [],
|
| 108 |
+
"source": [
|
| 109 |
+
"import torch\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"model.eval()\n",
|
| 112 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 113 |
+
"model.to(device)\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"question = \"대한민국의 수도는 어디인가요?\"\n",
|
| 116 |
+
"context = \"서울은 대한민국의 수도다.\"\n",
|
| 117 |
+
"inputs = tokenizer(question, context, return_tensors=\"pt\").to(device)\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"with torch.no_grad():\n",
|
| 120 |
+
" outputs = model(**inputs)\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"start_index = outputs[\"start_logits\"].argmax(dim=-1).item()\n",
|
| 123 |
+
"end_index = outputs[\"end_logits\"].argmax(dim=-1).item()\n",
|
| 124 |
+
"predicted_ids = inputs[\"input_ids\"][0][start_index : end_index]\n",
|
| 125 |
+
"predicted_text = tokenizer.decode(predicted_ids)\n",
|
| 126 |
+
"print(predicted_text)"
|
| 127 |
+
]
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"id": "c5898add",
|
| 133 |
+
"metadata": {
|
| 134 |
+
"vscode": {
|
| 135 |
+
"languageId": "plaintext"
|
| 136 |
+
}
|
| 137 |
+
},
|
| 138 |
+
"outputs": [],
|
| 139 |
+
"source": [
|
| 140 |
+
"from evaluate import evaluator\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"metric = evaluator(\"question-answering\")\n",
|
| 143 |
+
"results = metric.compute(\n",
|
| 144 |
+
" model,\n",
|
| 145 |
+
" tokenizer=tokenizer,\n",
|
| 146 |
+
" data=processed_dataset[\"validation\"].select(range(100)),\n",
|
| 147 |
+
" id_column=\"guid\",\n",
|
| 148 |
+
" question_column=\"question\",\n",
|
| 149 |
+
" context_column=\"context\",\n",
|
| 150 |
+
" label_column=\"answers\"\n",
|
| 151 |
+
")\n",
|
| 152 |
+
"print(results)"
|
| 153 |
+
]
|
| 154 |
+
}
|
| 155 |
+
],
|
| 156 |
+
"metadata": {
|
| 157 |
+
"kernelspec": {
|
| 158 |
+
"display_name": "Python 3 (ipykernel)",
|
| 159 |
+
"language": "python",
|
| 160 |
+
"name": "python3"
|
| 161 |
+
},
|
| 162 |
+
"language_info": {
|
| 163 |
+
"codemirror_mode": {
|
| 164 |
+
"name": "ipython",
|
| 165 |
+
"version": 3
|
| 166 |
+
},
|
| 167 |
+
"file_extension": ".py",
|
| 168 |
+
"mimetype": "text/x-python",
|
| 169 |
+
"name": "python",
|
| 170 |
+
"nbconvert_exporter": "python",
|
| 171 |
+
"pygments_lexer": "ipython3",
|
| 172 |
+
"version": "3.9.13"
|
| 173 |
+
}
|
| 174 |
+
},
|
| 175 |
+
"nbformat": 4,
|
| 176 |
+
"nbformat_minor": 5
|
| 177 |
+
}
|
3장 자연어 처리/예제 3.19 ~ 3.22 기계 번역 모델 copy.ipynb
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"from datasets import load_dataset\n",
|
| 10 |
+
"from transformers import T5TokenizerFast, T5ForConditionalGeneration\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"def preprocess_data(example, tokenizer):\n",
|
| 13 |
+
" translation = example[\"translation\"]\n",
|
| 14 |
+
" translation_source = [\"en: \" + instance[\"en\"] for instance in translation]\n",
|
| 15 |
+
" translation_target = [\"ko: \" + instance[\"ko\"] for instance in translation]\n",
|
| 16 |
+
" tokenized = tokenizer(\n",
|
| 17 |
+
" translation_source,\n",
|
| 18 |
+
" text_target=translation_target,\n",
|
| 19 |
+
" truncation=True\n",
|
| 20 |
+
" )\n",
|
| 21 |
+
" return tokenized\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"model_name = \"KETI-AIR/long-ke-t5-small\"\n",
|
| 24 |
+
"tokenizer = T5TokenizerFast.from_pretrained(model_name)\n",
|
| 25 |
+
"model = T5ForConditionalGeneration.from_pretrained(\"KETI-AIR/long-ke-t5-small\")\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"dataset = load_dataset(\"Helsinki-NLP/opus-100\", \"en-ko\")\n",
|
| 28 |
+
"processed_dataset = dataset.map(\n",
|
| 29 |
+
" lambda example: preprocess_data(example, tokenizer),\n",
|
| 30 |
+
" batched=True,\n",
|
| 31 |
+
" remove_columns=dataset[\"train\"].column_names\n",
|
| 32 |
+
")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"sample = processed_dataset[\"test\"][0]\n",
|
| 35 |
+
"print(sample)\n",
|
| 36 |
+
"print(\"변환된 출발 언어 :\", tokenizer.decode(sample[\"input_ids\"]))\n",
|
| 37 |
+
"print(\"변환된 도착 언어 :\", tokenizer.decode(sample[\"labels\"]))"
|
| 38 |
+
]
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"id": "c901d8ae",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"outputs": [],
|
| 46 |
+
"source": [
|
| 47 |
+
"from transformers import DataCollatorForSeq2Seq\n",
|
| 48 |
+
"from transformers import Seq2SeqTrainingArguments, Seq2SeqTrainer\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"seq2seq_collator = DataCollatorForSeq2Seq(\n",
|
| 51 |
+
" tokenizer=tokenizer,\n",
|
| 52 |
+
" padding=\"longest\",\n",
|
| 53 |
+
" return_tensors=\"pt\"\n",
|
| 54 |
+
")\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"training_arguments = Seq2SeqTrainingArguments(\n",
|
| 57 |
+
" output_dir=\"t5-translation\",\n",
|
| 58 |
+
" per_device_train_batch_size=8,\n",
|
| 59 |
+
" per_device_eval_batch_size=16,\n",
|
| 60 |
+
" learning_rate=5e-5,\n",
|
| 61 |
+
" num_train_epochs=1,\n",
|
| 62 |
+
" eval_steps=2500,\n",
|
| 63 |
+
" logging_steps=2500,\n",
|
| 64 |
+
" seed=42\n",
|
| 65 |
+
")\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"trainer = Seq2SeqTrainer(\n",
|
| 68 |
+
" model=model,\n",
|
| 69 |
+
" args=training_arguments,\n",
|
| 70 |
+
" data_collator=seq2seq_collator,\n",
|
| 71 |
+
" train_dataset=processed_dataset[\"train\"].select(range(100000)),\n",
|
| 72 |
+
" eval_dataset=processed_dataset[\"validation\"].select(range(1000))\n",
|
| 73 |
+
")\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"trainer.train()"
|
| 76 |
+
]
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"id": "5e4c93c5",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"outputs": [],
|
| 84 |
+
"source": [
|
| 85 |
+
"import torch\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"model.eval()\n",
|
| 88 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 89 |
+
"model.to(device)\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"data = \"en: It's always great to acquire new knowledge.\"\n",
|
| 92 |
+
"inputs = tokenizer(data, return_tensors=\"pt\").to(device)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"with torch.no_grad():\n",
|
| 95 |
+
" outputs = model.generate(\n",
|
| 96 |
+
" **inputs,\n",
|
| 97 |
+
" max_length=512,\n",
|
| 98 |
+
" num_beams=4,\n",
|
| 99 |
+
" no_repeat_ngram_size=2,\n",
|
| 100 |
+
" early_stopping=True\n",
|
| 101 |
+
" )\n",
|
| 102 |
+
"print(tokenizer.decode(outputs[0], skip_special_tokens=True))"
|
| 103 |
+
]
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"id": "a28e8515",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"outputs": [],
|
| 111 |
+
"source": [
|
| 112 |
+
"import evaluate\n",
|
| 113 |
+
"from torch.utils.data import DataLoader\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"dataloader = DataLoader(\n",
|
| 116 |
+
" processed_dataset[\"test\"].select(range(100)),\n",
|
| 117 |
+
" collate_fn=seq2seq_collator,\n",
|
| 118 |
+
" batch_size=4,\n",
|
| 119 |
+
" shuffle=False\n",
|
| 120 |
+
")\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"generated_translated = []\n",
|
| 123 |
+
"true_translated_ids = processed_dataset[\"test\"].select(range(100))[\"labels\"]\n",
|
| 124 |
+
"true_translated = tokenizer.batch_decode(true_translated_ids, skip_special_tokens=True)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"with torch.no_grad():\n",
|
| 127 |
+
" for batch in dataloader:\n",
|
| 128 |
+
" batch = batch.to(device)\n",
|
| 129 |
+
" output = model.generate(\n",
|
| 130 |
+
" **batch,\n",
|
| 131 |
+
" max_length=1026,\n",
|
| 132 |
+
" num_beams=4,\n",
|
| 133 |
+
" no_repeat_ngram_size=2,\n",
|
| 134 |
+
" early_stopping=True\n",
|
| 135 |
+
" )\n",
|
| 136 |
+
" batch_translated = tokenizer.batch_decode(output, skip_special_tokens=True)\n",
|
| 137 |
+
" generated_translated.extend(batch_translated)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"metric = evaluate.load(\"bleu\")\n",
|
| 140 |
+
"bleu_scores = metric.compute(\n",
|
| 141 |
+
" predictions=generated_translated,\n",
|
| 142 |
+
" references=true_translated\n",
|
| 143 |
+
")\n",
|
| 144 |
+
"print(bleu_scores)"
|
| 145 |
+
]
|
| 146 |
+
}
|
| 147 |
+
],
|
| 148 |
+
"metadata": {
|
| 149 |
+
"kernelspec": {
|
| 150 |
+
"display_name": "Python 3 (ipykernel)",
|
| 151 |
+
"language": "python",
|
| 152 |
+
"name": "python3"
|
| 153 |
+
},
|
| 154 |
+
"language_info": {
|
| 155 |
+
"codemirror_mode": {
|
| 156 |
+
"name": "ipython",
|
| 157 |
+
"version": 3
|
| 158 |
+
},
|
| 159 |
+
"file_extension": ".py",
|
| 160 |
+
"mimetype": "text/x-python",
|
| 161 |
+
"name": "python",
|
| 162 |
+
"nbconvert_exporter": "python",
|
| 163 |
+
"pygments_lexer": "ipython3",
|
| 164 |
+
"version": "3.9.13"
|
| 165 |
+
}
|
| 166 |
+
},
|
| 167 |
+
"nbformat": 4,
|
| 168 |
+
"nbformat_minor": 5
|
| 169 |
+
}
|
3장 자연어 처리/예제 3.23 ~ 3.26 LLaMA-3.1 실습.ipynb
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "7a8847de",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import torch\n",
|
| 15 |
+
"from transformers import BitsAndBytesConfig\n",
|
| 16 |
+
"from transformers import AutoTokenizer, AutoModelForCausalLM\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"quantization_config = BitsAndBytesConfig(\n",
|
| 19 |
+
" load_in_4bit=True,\n",
|
| 20 |
+
" bnb_4bit_quant_type=\"nf4\",\n",
|
| 21 |
+
" bnb_4bit_compute_dtype=torch.float16,\n",
|
| 22 |
+
" bnb_4bit_use_double_quant=False\n",
|
| 23 |
+
")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"token = \"hf_###...\" # 토큰 입력\n",
|
| 26 |
+
"model_name = \"meta-llama/Meta-Llama-3.1-8B-Instruct\"\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"tokenizer = AutoTokenizer.from_pretrained(\n",
|
| 29 |
+
" model_name,\n",
|
| 30 |
+
" trust_remote_code=True,\n",
|
| 31 |
+
" token=token\n",
|
| 32 |
+
")\n",
|
| 33 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
| 34 |
+
" model_name,\n",
|
| 35 |
+
" quantization_config=quantization_config,\n",
|
| 36 |
+
" device_map={\"\": 0},\n",
|
| 37 |
+
" token=token\n",
|
| 38 |
+
")"
|
| 39 |
+
]
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"id": "949ec23a",
|
| 45 |
+
"metadata": {
|
| 46 |
+
"vscode": {
|
| 47 |
+
"languageId": "plaintext"
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
+
"outputs": [],
|
| 51 |
+
"source": [
|
| 52 |
+
"model.eval()\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"messages = [\n",
|
| 55 |
+
" {\"role\": \"user\", \"content\": \"안녕하세요.\"}\n",
|
| 56 |
+
"]\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"input_ids = tokenizer.apply_chat_template(\n",
|
| 59 |
+
" messages,\n",
|
| 60 |
+
" add_generation_prompt=True,\n",
|
| 61 |
+
" return_tensors=\"pt\"\n",
|
| 62 |
+
").to(model.device)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"with torch.no_grad():\n",
|
| 65 |
+
" outputs = model.generate(\n",
|
| 66 |
+
" input_ids,\n",
|
| 67 |
+
" max_new_tokens=256,\n",
|
| 68 |
+
" do_sample=True,\n",
|
| 69 |
+
" temperature=0.7,\n",
|
| 70 |
+
" top_p=0.9\n",
|
| 71 |
+
" )\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"response = outputs[0][input_ids.shape[-1]:]\n",
|
| 74 |
+
"print(tokenizer.decode(response, skip_special_tokens=True))"
|
| 75 |
+
]
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"id": "55a86b07",
|
| 81 |
+
"metadata": {
|
| 82 |
+
"vscode": {
|
| 83 |
+
"languageId": "plaintext"
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"outputs": [],
|
| 87 |
+
"source": [
|
| 88 |
+
"model.eval()\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"messages = [\n",
|
| 91 |
+
" {\"role\": \"system\", \"content\": \"저는 위키북스의 챗봇 위키봇입니다.\"},\n",
|
| 92 |
+
" {\"role\": \"user\", \"content\": \"안녕하세요, 당신은 누구인가요?\"}\n",
|
| 93 |
+
"]\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"input_ids = tokenizer.apply_chat_template(\n",
|
| 96 |
+
" messages,\n",
|
| 97 |
+
" add_generation_prompt=True,\n",
|
| 98 |
+
" return_tensors=\"pt\"\n",
|
| 99 |
+
").to(model.device)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"with torch.no_grad():\n",
|
| 102 |
+
" outputs = model.generate(\n",
|
| 103 |
+
" input_ids,\n",
|
| 104 |
+
" max_new_tokens=256,\n",
|
| 105 |
+
" do_sample=True,\n",
|
| 106 |
+
" temperature=0.7,\n",
|
| 107 |
+
" top_p=0.9\n",
|
| 108 |
+
" )\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"response = outputs[0][input_ids.shape[-1]:]\n",
|
| 111 |
+
"print(tokenizer.decode(response, skip_special_tokens=True))"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"id": "9cc7c318",
|
| 118 |
+
"metadata": {
|
| 119 |
+
"vscode": {
|
| 120 |
+
"languageId": "plaintext"
|
| 121 |
+
}
|
| 122 |
+
},
|
| 123 |
+
"outputs": [],
|
| 124 |
+
"source": [
|
| 125 |
+
"model.eval()\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"messages = [\n",
|
| 128 |
+
" {\"role\": \"system\", \"content\": \"저는 위키북스의 챗봇 위키봇입니다.\"},\n",
|
| 129 |
+
" {\"role\": \"user\", \"content\": \"안녕하세요, 제 이름은 홍길동입니다.\"},\n",
|
| 130 |
+
" {\"role\": \"assistant\", \"content\": \"안녕하세요! 나는 위키북스의 챗봇, 위키봇입니다. 위키북스에서 다양한 지식을 공유하고 도울 목적으로 개발된 챗봇입니다. 제가 도와드릴 수 있는 다양한 주제와 질문에 대해 질문해 주세요!\"},\n",
|
| 131 |
+
" {\"role\": \"user\", \"content\": \"제 이름을 알고 있나요?\"}\n",
|
| 132 |
+
"]\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"input_ids = tokenizer.apply_chat_template(\n",
|
| 135 |
+
" messages,\n",
|
| 136 |
+
" add_generation_prompt=True,\n",
|
| 137 |
+
" return_tensors=\"pt\"\n",
|
| 138 |
+
").to(model.device)\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"with torch.no_grad():\n",
|
| 141 |
+
" outputs = model.generate(\n",
|
| 142 |
+
" input_ids,\n",
|
| 143 |
+
" max_new_tokens=256,\n",
|
| 144 |
+
" do_sample=True,\n",
|
| 145 |
+
" temperature=0.7,\n",
|
| 146 |
+
" top_p=0.9\n",
|
| 147 |
+
" )\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"response = outputs[0][input_ids.shape[-1]:]\n",
|
| 150 |
+
"print(tokenizer.decode(response, skip_special_tokens=True))"
|
| 151 |
+
]
|
| 152 |
+
}
|
| 153 |
+
],
|
| 154 |
+
"metadata": {
|
| 155 |
+
"kernelspec": {
|
| 156 |
+
"display_name": "Python 3 (ipykernel)",
|
| 157 |
+
"language": "python",
|
| 158 |
+
"name": "python3"
|
| 159 |
+
},
|
| 160 |
+
"language_info": {
|
| 161 |
+
"codemirror_mode": {
|
| 162 |
+
"name": "ipython",
|
| 163 |
+
"version": 3
|
| 164 |
+
},
|
| 165 |
+
"file_extension": ".py",
|
| 166 |
+
"mimetype": "text/x-python",
|
| 167 |
+
"name": "python",
|
| 168 |
+
"nbconvert_exporter": "python",
|
| 169 |
+
"pygments_lexer": "ipython3",
|
| 170 |
+
"version": "3.9.13"
|
| 171 |
+
}
|
| 172 |
+
},
|
| 173 |
+
"nbformat": 4,
|
| 174 |
+
"nbformat_minor": 5
|
| 175 |
+
}
|
3장 자연어 처리/예제 3.27 ~ 3.30 LLaMA-3.1 미세 조정.ipynb
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e132c346",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import torch\n",
|
| 15 |
+
"from datasets import load_dataset\n",
|
| 16 |
+
"from transformers import BitsAndBytesConfig\n",
|
| 17 |
+
"from transformers import AutoTokenizer, AutoModelForCausalLM\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"dataset = load_dataset(\"s076923/llama3-wikibook-ko\")\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"quantization_config = BitsAndBytesConfig(\n",
|
| 22 |
+
" load_in_4bit=True,\n",
|
| 23 |
+
" bnb_4bit_quant_type=\"nf4\",\n",
|
| 24 |
+
" bnb_4bit_compute_dtype=torch.float16,\n",
|
| 25 |
+
" bnb_4bit_use_double_quant=False\n",
|
| 26 |
+
")\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"token = \"hf_###...\" # 토큰 입력\n",
|
| 29 |
+
"model_name = \"meta-llama/Meta-Llama-3.1-8B-Instruct\"\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"tokenizer = AutoTokenizer.from_pretrained(\n",
|
| 32 |
+
" model_name,\n",
|
| 33 |
+
" trust_remote_code=True,\n",
|
| 34 |
+
" token=token\n",
|
| 35 |
+
")\n",
|
| 36 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
| 37 |
+
" model_name,\n",
|
| 38 |
+
" quantization_config=quantization_config,\n",
|
| 39 |
+
" device_map={\"\": 0},\n",
|
| 40 |
+
" token=token\n",
|
| 41 |
+
")\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"tokenizer.pad_token = tokenizer.eos_token\n",
|
| 44 |
+
"model.config.use_cache = False\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"print(dataset)\n",
|
| 47 |
+
"print(dataset[\"train\"][\"text\"][7])"
|
| 48 |
+
]
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"id": "92732a20",
|
| 54 |
+
"metadata": {
|
| 55 |
+
"vscode": {
|
| 56 |
+
"languageId": "plaintext"
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"outputs": [],
|
| 60 |
+
"source": [
|
| 61 |
+
"from peft import LoraConfig\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"peft_config = LoraConfig(\n",
|
| 64 |
+
" r=128,\n",
|
| 65 |
+
" lora_alpha=4,\n",
|
| 66 |
+
" lora_dropout=0.1,\n",
|
| 67 |
+
" task_type=\"CAUSAL_LM\"\n",
|
| 68 |
+
")"
|
| 69 |
+
]
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"id": "8bd9a04f",
|
| 75 |
+
"metadata": {
|
| 76 |
+
"vscode": {
|
| 77 |
+
"languageId": "plaintext"
|
| 78 |
+
}
|
| 79 |
+
},
|
| 80 |
+
"outputs": [],
|
| 81 |
+
"source": [
|
| 82 |
+
"from transformers import TrainingArguments\n",
|
| 83 |
+
"from trl import SFTTrainer\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"training_args = TrainingArguments(\n",
|
| 86 |
+
" output_dir=\"LLaMa-3.1\",\n",
|
| 87 |
+
" per_device_train_batch_size=1,\n",
|
| 88 |
+
" gradient_accumulation_steps=5,\n",
|
| 89 |
+
" learning_rate=2e-4,\n",
|
| 90 |
+
" max_steps=500,\n",
|
| 91 |
+
" warmup_steps=100,\n",
|
| 92 |
+
" logging_steps=100,\n",
|
| 93 |
+
" fp16=True,\n",
|
| 94 |
+
" optim=\"paged_adamw_8bit\",\n",
|
| 95 |
+
" seed=42\n",
|
| 96 |
+
")\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"trainer = SFTTrainer(\n",
|
| 99 |
+
" model=model,\n",
|
| 100 |
+
" tokenizer=tokenizer,\n",
|
| 101 |
+
" args=training_args,\n",
|
| 102 |
+
" peft_config=peft_config,\n",
|
| 103 |
+
" train_dataset=dataset[\"train\"],\n",
|
| 104 |
+
" dataset_text_field=\"text\",\n",
|
| 105 |
+
" max_seq_length=64\n",
|
| 106 |
+
")\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"trainer.train()"
|
| 109 |
+
]
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"id": "1a2d070b",
|
| 115 |
+
"metadata": {
|
| 116 |
+
"vscode": {
|
| 117 |
+
"languageId": "plaintext"
|
| 118 |
+
}
|
| 119 |
+
},
|
| 120 |
+
"outputs": [],
|
| 121 |
+
"source": [
|
| 122 |
+
"model.eval()\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"messages = [\n",
|
| 125 |
+
" {\"role\": \"user\", \"content\": \"위키북스 대표 저자는 누구예요?\"},\n",
|
| 126 |
+
"]\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"input_ids = tokenizer.apply_chat_template(\n",
|
| 129 |
+
" messages,\n",
|
| 130 |
+
" add_generation_prompt=True,\n",
|
| 131 |
+
" return_tensors=\"pt\"\n",
|
| 132 |
+
").to(model.device)\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"with torch.no_grad():\n",
|
| 135 |
+
" outputs = model.generate(\n",
|
| 136 |
+
" input_ids,\n",
|
| 137 |
+
" max_new_tokens=64,\n",
|
| 138 |
+
" do_sample=True,\n",
|
| 139 |
+
" temperature=0.2,\n",
|
| 140 |
+
" top_p=0.95,\n",
|
| 141 |
+
" no_repeat_ngram_size=2\n",
|
| 142 |
+
" )\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"response = outputs[0][input_ids.shape[-1]:]\n",
|
| 145 |
+
"print(tokenizer.decode(response, skip_special_tokens=True))"
|
| 146 |
+
]
|
| 147 |
+
}
|
| 148 |
+
],
|
| 149 |
+
"metadata": {
|
| 150 |
+
"kernelspec": {
|
| 151 |
+
"display_name": "Python 3 (ipykernel)",
|
| 152 |
+
"language": "python",
|
| 153 |
+
"name": "python3"
|
| 154 |
+
},
|
| 155 |
+
"language_info": {
|
| 156 |
+
"codemirror_mode": {
|
| 157 |
+
"name": "ipython",
|
| 158 |
+
"version": 3
|
| 159 |
+
},
|
| 160 |
+
"file_extension": ".py",
|
| 161 |
+
"mimetype": "text/x-python",
|
| 162 |
+
"name": "python",
|
| 163 |
+
"nbconvert_exporter": "python",
|
| 164 |
+
"pygments_lexer": "ipython3",
|
| 165 |
+
"version": "3.9.13"
|
| 166 |
+
}
|
| 167 |
+
},
|
| 168 |
+
"nbformat": 4,
|
| 169 |
+
"nbformat_minor": 5
|
| 170 |
+
}
|
4장 컴퓨터 비전/예제 4.01 ~ 4.03 제로샷 이미지 분류.ipynb
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "e41fc33d",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from datasets import load_dataset\n",
|
| 15 |
+
"from transformers import CLIPProcessor, CLIPModel\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"model_name = \"openai/clip-vit-base-patch32\"\n",
|
| 18 |
+
"processor = CLIPProcessor.from_pretrained(model_name)\n",
|
| 19 |
+
"model = CLIPModel.from_pretrained(model_name)\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"dataset = load_dataset(\"sasha/dog-food\")\n",
|
| 22 |
+
"images = dataset[\"test\"][\"image\"][:2]\n",
|
| 23 |
+
"labels = [\"dog\", \"food\"]\n",
|
| 24 |
+
"inputs = processor(images=images, text=labels, return_tensors=\"pt\") # padding=True\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(\"input_ids :\", inputs[\"input_ids\"])\n",
|
| 27 |
+
"print(\"attention_mask :\", inputs[\"attention_mask\"])\n",
|
| 28 |
+
"print(\"pixel_values :\", inputs[\"pixel_values\"])\n",
|
| 29 |
+
"print(\"image_shape :\", inputs[\"pixel_values\"].shape)"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"execution_count": null,
|
| 35 |
+
"id": "ac651f7b",
|
| 36 |
+
"metadata": {
|
| 37 |
+
"vscode": {
|
| 38 |
+
"languageId": "plaintext"
|
| 39 |
+
}
|
| 40 |
+
},
|
| 41 |
+
"outputs": [],
|
| 42 |
+
"source": [
|
| 43 |
+
"import torch\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"model.eval()\n",
|
| 46 |
+
"with torch.no_grad():\n",
|
| 47 |
+
" outputs = model(**inputs)\n",
|
| 48 |
+
" logits_per_image = outputs.logits_per_image\n",
|
| 49 |
+
" probs = logits_per_image.softmax(dim=1)\n",
|
| 50 |
+
" print(\"outputs :\", outputs.keys())\n",
|
| 51 |
+
" print(\"logits_per_image :\", logits_per_image)\n",
|
| 52 |
+
" print(\"probs :\", probs)\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"for idx, prob in enumerate(probs):\n",
|
| 55 |
+
" print(f\"- Image #{idx}\")\n",
|
| 56 |
+
" for label, p in zip(labels, prob):\n",
|
| 57 |
+
" print(f\"{label} : {p:.4f}\")"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"id": "0d98c946",
|
| 64 |
+
"metadata": {
|
| 65 |
+
"vscode": {
|
| 66 |
+
"languageId": "plaintext"
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
"outputs": [],
|
| 70 |
+
"source": [
|
| 71 |
+
"import evaluate\n",
|
| 72 |
+
"from torch.utils.data import DataLoader\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"test_dataloader = DataLoader(\n",
|
| 75 |
+
" dataset[\"test\"],\n",
|
| 76 |
+
" batch_size=8,\n",
|
| 77 |
+
" collate_fn=lambda batch: (\n",
|
| 78 |
+
" [item[\"image\"] for item in batch],\n",
|
| 79 |
+
" [item[\"label\"] for item in batch],\n",
|
| 80 |
+
" ),\n",
|
| 81 |
+
")\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"metric = evaluate.load(\"accuracy\")\n",
|
| 84 |
+
"predictions, references = [], []\n",
|
| 85 |
+
"labels_names = dataset[\"test\"].features[\"label\"].names\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"model.eval()\n",
|
| 88 |
+
"with torch.no_grad():\n",
|
| 89 |
+
" for images, labels in test_dataloader:\n",
|
| 90 |
+
" inputs = processor(images=images, text=labels_names, return_tensors=\"pt\")\n",
|
| 91 |
+
" outputs = model(**inputs)\n",
|
| 92 |
+
" probs = outputs.logits_per_image.softmax(dim=1)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" predictions += probs.argmax(dim=1).cpu().tolist()\n",
|
| 95 |
+
" references += labels\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"results = metric.compute(predictions=predictions, references=references)\n",
|
| 98 |
+
"print(f\"클래스 목록 : {labels_names}\")\n",
|
| 99 |
+
"print(f\"정확도 : {results['accuracy']*100 :.2f}%\")"
|
| 100 |
+
]
|
| 101 |
+
}
|
| 102 |
+
],
|
| 103 |
+
"metadata": {
|
| 104 |
+
"kernelspec": {
|
| 105 |
+
"display_name": "Python 3 (ipykernel)",
|
| 106 |
+
"language": "python",
|
| 107 |
+
"name": "python3"
|
| 108 |
+
},
|
| 109 |
+
"language_info": {
|
| 110 |
+
"codemirror_mode": {
|
| 111 |
+
"name": "ipython",
|
| 112 |
+
"version": 3
|
| 113 |
+
},
|
| 114 |
+
"file_extension": ".py",
|
| 115 |
+
"mimetype": "text/x-python",
|
| 116 |
+
"name": "python",
|
| 117 |
+
"nbconvert_exporter": "python",
|
| 118 |
+
"pygments_lexer": "ipython3",
|
| 119 |
+
"version": "3.9.13"
|
| 120 |
+
}
|
| 121 |
+
},
|
| 122 |
+
"nbformat": 4,
|
| 123 |
+
"nbformat_minor": 5
|
| 124 |
+
}
|
4장 컴퓨터 비전/예제 4.04 ~ 4.11 제로샷 객체 검출.ipynb
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "d3eaffd0",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import io\n",
|
| 15 |
+
"from PIL import Image\n",
|
| 16 |
+
"from datasets import load_dataset\n",
|
| 17 |
+
"from transformers import Owlv2Processor, Owlv2ForObjectDetection\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"model_name = \"google/owlv2-base-patch16\"\n",
|
| 20 |
+
"processor = Owlv2Processor.from_pretrained(model_name)\n",
|
| 21 |
+
"model = Owlv2ForObjectDetection.from_pretrained(model_name)\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"dataset = load_dataset(\"Francesco/animals-ij5d2\")\n",
|
| 24 |
+
"print(dataset)\n",
|
| 25 |
+
"print(dataset[\"test\"][0])"
|
| 26 |
+
]
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"id": "1f322644",
|
| 32 |
+
"metadata": {
|
| 33 |
+
"vscode": {
|
| 34 |
+
"languageId": "plaintext"
|
| 35 |
+
}
|
| 36 |
+
},
|
| 37 |
+
"outputs": [],
|
| 38 |
+
"source": [
|
| 39 |
+
"images = dataset[\"test\"][\"image\"][:2]\n",
|
| 40 |
+
"categories = dataset[\"test\"].features[\"objects\"].feature[\"category\"].names\n",
|
| 41 |
+
"labels = [categories] * len(images)\n",
|
| 42 |
+
"inputs = processor(text=labels, images=images, return_tensors=\"pt\", padding=True)\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"print(images)\n",
|
| 45 |
+
"print(labels)\n",
|
| 46 |
+
"print(\"input_ids :\", inputs[\"input_ids\"])\n",
|
| 47 |
+
"print(\"attention_mask :\", inputs[\"attention_mask\"])\n",
|
| 48 |
+
"print(\"pixel_values :\", inputs[\"pixel_values\"])\n",
|
| 49 |
+
"print(\"image_shape :\", inputs[\"pixel_values\"].shape)"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"id": "fdc753ca",
|
| 56 |
+
"metadata": {
|
| 57 |
+
"vscode": {
|
| 58 |
+
"languageId": "plaintext"
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
"outputs": [],
|
| 62 |
+
"source": [
|
| 63 |
+
"import torch\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"model.eval()\n",
|
| 66 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 67 |
+
"model.to(device)\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"with torch.no_grad():\n",
|
| 70 |
+
" outputs = model(**inputs.to(device))\n",
|
| 71 |
+
" \n",
|
| 72 |
+
"print(outputs.keys())\n",
|
| 73 |
+
"print(\"logits :\", outputs.logits.shape)\n",
|
| 74 |
+
"print(\"objectness_logits :\", outputs.objectness_logits.shape)\n",
|
| 75 |
+
"print(\"pred_boxes :\", outputs.pred_boxes.shape)\n",
|
| 76 |
+
"print(\"class_embeds :\", outputs.class_embeds.shape)"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"id": "24a01f43",
|
| 83 |
+
"metadata": {
|
| 84 |
+
"vscode": {
|
| 85 |
+
"languageId": "plaintext"
|
| 86 |
+
}
|
| 87 |
+
},
|
| 88 |
+
"outputs": [],
|
| 89 |
+
"source": [
|
| 90 |
+
"shape = [dataset[\"test\"][:2][\"width\"], dataset[\"test\"][:2][\"height\"]]\n",
|
| 91 |
+
"target_sizes = list(map(list, zip(*shape)))\n",
|
| 92 |
+
"detections = processor.post_process_object_detection(\n",
|
| 93 |
+
" outputs=outputs, threshold=0.5, target_sizes=target_sizes\n",
|
| 94 |
+
")\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"print(target_sizes)\n",
|
| 97 |
+
"print(detections)"
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"id": "ab07c0bd",
|
| 104 |
+
"metadata": {
|
| 105 |
+
"vscode": {
|
| 106 |
+
"languageId": "plaintext"
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
"outputs": [],
|
| 110 |
+
"source": [
|
| 111 |
+
"import matplotlib.pyplot as plt\n",
|
| 112 |
+
"from PIL import ImageDraw, ImageFont\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"for idx, (image, detect) in enumerate(zip(images, detections)):\n",
|
| 115 |
+
" im = image.copy()\n",
|
| 116 |
+
" draw = ImageDraw.Draw(im)\n",
|
| 117 |
+
" font = ImageFont.truetype(\"arial.ttf\", 36)\n",
|
| 118 |
+
"\n",
|
| 119 |
+
" for box, score, label in zip(detect[\"boxes\"], detect[\"scores\"], detect[\"labels\"]):\n",
|
| 120 |
+
" box = [round(i, 2) for i in box.tolist()]\n",
|
| 121 |
+
" draw.rectangle(box, outline=\"red\", width=3)\n",
|
| 122 |
+
" \n",
|
| 123 |
+
" label_text = f\"{labels[idx][label]}: {round(score.item(), 3)}\"\n",
|
| 124 |
+
" draw.text((box[0], box[1]), label_text, fill=\"red\", font=font)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" plt.imshow(im)\n",
|
| 127 |
+
" plt.axis(\"off\")\n",
|
| 128 |
+
" plt.show()"
|
| 129 |
+
]
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"id": "9d9c46ef",
|
| 135 |
+
"metadata": {
|
| 136 |
+
"vscode": {
|
| 137 |
+
"languageId": "plaintext"
|
| 138 |
+
}
|
| 139 |
+
},
|
| 140 |
+
"outputs": [],
|
| 141 |
+
"source": [
|
| 142 |
+
"!pip install pycocotools"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"id": "968261fa",
|
| 149 |
+
"metadata": {
|
| 150 |
+
"vscode": {
|
| 151 |
+
"languageId": "plaintext"
|
| 152 |
+
}
|
| 153 |
+
},
|
| 154 |
+
"outputs": [],
|
| 155 |
+
"source": [
|
| 156 |
+
"def get_coco_annotations(dataset):\n",
|
| 157 |
+
" annotations = []\n",
|
| 158 |
+
" for data in dataset:\n",
|
| 159 |
+
" image_id = int(data[\"image_id\"])\n",
|
| 160 |
+
" objects = data[\"objects\"]\n",
|
| 161 |
+
" for idx in range(len(objects[\"id\"])):\n",
|
| 162 |
+
" annotations.append(\n",
|
| 163 |
+
" {\n",
|
| 164 |
+
" \"image_id\": image_id,\n",
|
| 165 |
+
" \"category_id\": int(objects[\"category\"][idx]),\n",
|
| 166 |
+
" \"bbox\": [float(coord) for coord in objects[\"bbox\"][idx]],\n",
|
| 167 |
+
" \"area\": float(objects[\"area\"][idx]),\n",
|
| 168 |
+
" \"id\": int(objects[\"id\"][idx]),\n",
|
| 169 |
+
" \"iscrowd\": 0\n",
|
| 170 |
+
" }\n",
|
| 171 |
+
" )\n",
|
| 172 |
+
" return annotations\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"coco_annotations = get_coco_annotations(dataset[\"test\"])\n",
|
| 175 |
+
"coco_annotation_format = {\n",
|
| 176 |
+
" \"annotations\": coco_annotations,\n",
|
| 177 |
+
" \"images\": [{\"id\": int(data[\"image_id\"])} for data in dataset[\"test\"]],\n",
|
| 178 |
+
" \"categories\": [{\"id\": i, \"name\": name} for i, name in enumerate(categories)]\n",
|
| 179 |
+
"}\n",
|
| 180 |
+
"print(len(coco_annotations))\n",
|
| 181 |
+
"print(coco_annotation_format[\"annotations\"][0])\n",
|
| 182 |
+
"print(coco_annotation_format[\"images\"][0])\n",
|
| 183 |
+
"print(coco_annotation_format[\"categories\"][0])"
|
| 184 |
+
]
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"id": "84ab7984",
|
| 190 |
+
"metadata": {
|
| 191 |
+
"vscode": {
|
| 192 |
+
"languageId": "plaintext"
|
| 193 |
+
}
|
| 194 |
+
},
|
| 195 |
+
"outputs": [],
|
| 196 |
+
"source": [
|
| 197 |
+
"from torch.utils.data import DataLoader\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"dataloader = DataLoader(\n",
|
| 200 |
+
" dataset[\"test\"],\n",
|
| 201 |
+
" batch_size=2,\n",
|
| 202 |
+
" collate_fn=lambda batch: (\n",
|
| 203 |
+
" [item[\"image\"] for item in batch],\n",
|
| 204 |
+
" [list(item[\"image\"].size) for item in batch],\n",
|
| 205 |
+
" [item[\"image_id\"] for item in batch],\n",
|
| 206 |
+
" [item[\"objects\"] for item in batch]\n",
|
| 207 |
+
" )\n",
|
| 208 |
+
")\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"predictions = []\n",
|
| 211 |
+
"model.eval()\n",
|
| 212 |
+
"with torch.no_grad():\n",
|
| 213 |
+
" for images, target_sizes, image_ids, objects in dataloader:\n",
|
| 214 |
+
" input_labels = [categories] * len(images)\n",
|
| 215 |
+
" inputs = processor(images=images, text=input_labels, return_tensors=\"pt\")\n",
|
| 216 |
+
" outputs = model(**inputs.to(device))\n",
|
| 217 |
+
" detections = processor.post_process_object_detection(\n",
|
| 218 |
+
" outputs=outputs, threshold=0.3, target_sizes=target_sizes\n",
|
| 219 |
+
" )\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" for batch_idx, detection in enumerate(detections):\n",
|
| 222 |
+
" category_ids = detection[\"labels\"].cpu().numpy().tolist()\n",
|
| 223 |
+
" scores = detection[\"scores\"].cpu().numpy().tolist()\n",
|
| 224 |
+
" boxes = detection[\"boxes\"].cpu().numpy()\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" boxes[:, 2:4] -= boxes[:, :2]\n",
|
| 227 |
+
" boxes = boxes.tolist()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" for obj_idx, box in enumerate(boxes):\n",
|
| 230 |
+
" prediction = {\n",
|
| 231 |
+
" \"image_id\": image_ids[batch_idx],\n",
|
| 232 |
+
" \"category_id\": category_ids[obj_idx],\n",
|
| 233 |
+
" \"bbox\": box,\n",
|
| 234 |
+
" \"score\": scores[obj_idx]\n",
|
| 235 |
+
" }\n",
|
| 236 |
+
" predictions.append(prediction)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"print(len(predictions))\n",
|
| 239 |
+
"print(predictions[0])"
|
| 240 |
+
]
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"id": "dcda78ac",
|
| 246 |
+
"metadata": {
|
| 247 |
+
"vscode": {
|
| 248 |
+
"languageId": "plaintext"
|
| 249 |
+
}
|
| 250 |
+
},
|
| 251 |
+
"outputs": [],
|
| 252 |
+
"source": [
|
| 253 |
+
"from pycocotools.coco import COCO\n",
|
| 254 |
+
"from pycocotools.cocoeval import COCOeval\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"coco_gt = COCO()\n",
|
| 257 |
+
"coco_gt.dataset = coco_annotation_format\n",
|
| 258 |
+
"coco_gt.createIndex()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"coco_dt = coco_gt.loadRes(predictions)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"coco_eval = COCOeval(coco_gt, coco_dt, \"bbox\")\n",
|
| 263 |
+
"coco_eval.evaluate()\n",
|
| 264 |
+
"coco_eval.accumulate()\n",
|
| 265 |
+
"coco_eval.summarize()"
|
| 266 |
+
]
|
| 267 |
+
}
|
| 268 |
+
],
|
| 269 |
+
"metadata": {
|
| 270 |
+
"kernelspec": {
|
| 271 |
+
"display_name": "Python 3 (ipykernel)",
|
| 272 |
+
"language": "python",
|
| 273 |
+
"name": "python3"
|
| 274 |
+
},
|
| 275 |
+
"language_info": {
|
| 276 |
+
"codemirror_mode": {
|
| 277 |
+
"name": "ipython",
|
| 278 |
+
"version": 3
|
| 279 |
+
},
|
| 280 |
+
"file_extension": ".py",
|
| 281 |
+
"mimetype": "text/x-python",
|
| 282 |
+
"name": "python",
|
| 283 |
+
"nbconvert_exporter": "python",
|
| 284 |
+
"pygments_lexer": "ipython3",
|
| 285 |
+
"version": "3.9.13"
|
| 286 |
+
}
|
| 287 |
+
},
|
| 288 |
+
"nbformat": 4,
|
| 289 |
+
"nbformat_minor": 5
|
| 290 |
+
}
|
4장 컴퓨터 비전/예제 4.12 ~ 4.17 이미지 세그먼테이션.ipynb
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "9d9c46ef",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import io\n",
|
| 15 |
+
"from PIL import Image\n",
|
| 16 |
+
"from datasets import load_dataset\n",
|
| 17 |
+
"from transformers import SamProcessor, SamModel\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"def filter_category(data):\n",
|
| 20 |
+
" # 16 = dog\n",
|
| 21 |
+
" # 23 = giraffe\n",
|
| 22 |
+
" return 16 in data[\"objects\"][\"category\"] or 23 in data[\"objects\"][\"category\"]\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"def convert_image(data):\n",
|
| 25 |
+
" byte = io.BytesIO(data[\"image\"][\"bytes\"])\n",
|
| 26 |
+
" img = Image.open(byte)\n",
|
| 27 |
+
" return {\"img\": img}\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"model_name = \"facebook/sam-vit-base\"\n",
|
| 30 |
+
"processor = SamProcessor.from_pretrained(model_name) \n",
|
| 31 |
+
"model = SamModel.from_pretrained(model_name)\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"dataset = load_dataset(\"s076923/coco-val\")\n",
|
| 34 |
+
"filtered_dataset = dataset[\"validation\"].filter(filter_category)\n",
|
| 35 |
+
"converted_dataset = filtered_dataset.map(convert_image, remove_columns=[\"image\"])"
|
| 36 |
+
]
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"execution_count": null,
|
| 41 |
+
"id": "4eece5f7",
|
| 42 |
+
"metadata": {
|
| 43 |
+
"vscode": {
|
| 44 |
+
"languageId": "plaintext"
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"outputs": [],
|
| 48 |
+
"source": [
|
| 49 |
+
"import numpy as np\n",
|
| 50 |
+
"from matplotlib import pyplot as plt\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"def show_point_box(image, input_points, input_labels, input_boxes=None, marker_size=375):\n",
|
| 54 |
+
" plt.figure(figsize=(10, 10))\n",
|
| 55 |
+
" plt.imshow(image)\n",
|
| 56 |
+
" ax = plt.gca()\n",
|
| 57 |
+
" \n",
|
| 58 |
+
" input_points = np.array(input_points)\n",
|
| 59 |
+
" input_labels = np.array(input_labels)\n",
|
| 60 |
+
"\n",
|
| 61 |
+
" pos_points = input_points[input_labels[0] == 1]\n",
|
| 62 |
+
" neg_points = input_points[input_labels[0] == 0]\n",
|
| 63 |
+
" \n",
|
| 64 |
+
" ax.scatter(\n",
|
| 65 |
+
" pos_points[:, 0],\n",
|
| 66 |
+
" pos_points[:, 1],\n",
|
| 67 |
+
" color=\"green\",\n",
|
| 68 |
+
" marker=\"*\",\n",
|
| 69 |
+
" s=marker_size,\n",
|
| 70 |
+
" edgecolor=\"white\",\n",
|
| 71 |
+
" linewidth=1.25\n",
|
| 72 |
+
" )\n",
|
| 73 |
+
" ax.scatter(\n",
|
| 74 |
+
" neg_points[:, 0],\n",
|
| 75 |
+
" neg_points[:, 1],\n",
|
| 76 |
+
" color=\"red\",\n",
|
| 77 |
+
" marker=\"*\",\n",
|
| 78 |
+
" s=marker_size,\n",
|
| 79 |
+
" edgecolor=\"white\",\n",
|
| 80 |
+
" linewidth=1.25\n",
|
| 81 |
+
" )\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" if input_boxes is not None:\n",
|
| 84 |
+
" for box in input_boxes:\n",
|
| 85 |
+
" x0, y0 = box[0], box[1]\n",
|
| 86 |
+
" w, h = box[2] - box[0], box[3] - box[1]\n",
|
| 87 |
+
" ax.add_patch(\n",
|
| 88 |
+
" plt.Rectangle(\n",
|
| 89 |
+
" (x0, y0), w, h, edgecolor=\"green\", facecolor=(0, 0, 0, 0), lw=2\n",
|
| 90 |
+
" )\n",
|
| 91 |
+
" )\n",
|
| 92 |
+
"\n",
|
| 93 |
+
" plt.axis(\"on\")\n",
|
| 94 |
+
" plt.show()\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"image = converted_dataset[0][\"img\"]\n",
|
| 98 |
+
"input_points = [[[250, 200]]]\n",
|
| 99 |
+
"input_labels = [[[1]]]\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"show_point_box(image, input_points[0], input_labels[0])\n",
|
| 102 |
+
"inputs = processor(\n",
|
| 103 |
+
" image, input_points=input_points, input_labels=input_labels, return_tensors=\"pt\"\n",
|
| 104 |
+
")\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"print(\"input_points shape :\", inputs[\"input_points\"].shape)\n",
|
| 107 |
+
"print(\"input_points :\", inputs[\"input_points\"])\n",
|
| 108 |
+
"print(\"input_labels shape :\", inputs[\"input_labels\"].shape)\n",
|
| 109 |
+
"print(\"input_labels :\", inputs[\"input_labels\"])\n",
|
| 110 |
+
"print(\"pixel_values shape :\", inputs[\"pixel_values\"].shape)\n",
|
| 111 |
+
"print(\"pixel_values :\", inputs[\"pixel_values\"])"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"id": "5116671c",
|
| 118 |
+
"metadata": {
|
| 119 |
+
"vscode": {
|
| 120 |
+
"languageId": "plaintext"
|
| 121 |
+
}
|
| 122 |
+
},
|
| 123 |
+
"outputs": [],
|
| 124 |
+
"source": [
|
| 125 |
+
"import torch\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"def show_mask(mask, ax, random_color=False):\n",
|
| 129 |
+
" if random_color:\n",
|
| 130 |
+
" color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n",
|
| 131 |
+
" else:\n",
|
| 132 |
+
" color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])\n",
|
| 133 |
+
" h, w = mask.shape[-2:]\n",
|
| 134 |
+
" mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
|
| 135 |
+
" ax.imshow(mask_image)\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"def show_masks_on_image(raw_image, masks, scores):\n",
|
| 139 |
+
" if len(masks.shape) == 4:\n",
|
| 140 |
+
" masks = masks.squeeze()\n",
|
| 141 |
+
" if scores.shape[0] == 1:\n",
|
| 142 |
+
" scores = scores.squeeze()\n",
|
| 143 |
+
"\n",
|
| 144 |
+
" nb_predictions = scores.shape[-1]\n",
|
| 145 |
+
" fig, axes = plt.subplots(1, nb_predictions, figsize=(30, 15))\n",
|
| 146 |
+
"\n",
|
| 147 |
+
" for i, (mask, score) in enumerate(zip(masks, scores)):\n",
|
| 148 |
+
" mask = mask.cpu().detach()\n",
|
| 149 |
+
" axes[i].imshow(np.array(raw_image))\n",
|
| 150 |
+
" show_mask(mask, axes[i])\n",
|
| 151 |
+
" axes[i].title.set_text(f\"Mask {i+1}, Score: {score.item():.3f}\")\n",
|
| 152 |
+
" axes[i].axis(\"off\")\n",
|
| 153 |
+
" plt.show()\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"model.eval()\n",
|
| 157 |
+
"with torch.no_grad():\n",
|
| 158 |
+
" outputs = model(**inputs)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"masks = processor.image_processor.post_process_masks(\n",
|
| 161 |
+
" outputs.pred_masks.cpu(),\n",
|
| 162 |
+
" inputs[\"original_sizes\"].cpu(),\n",
|
| 163 |
+
" inputs[\"reshaped_input_sizes\"].cpu(),\n",
|
| 164 |
+
")\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"show_masks_on_image(image, masks[0], outputs.iou_scores)\n",
|
| 167 |
+
"print(\"iou_scores shape :\", outputs.iou_scores.shape)\n",
|
| 168 |
+
"print(\"iou_scores :\", outputs.iou_scores)\n",
|
| 169 |
+
"print(\"pred_masks shape :\", outputs.pred_masks.shape)\n",
|
| 170 |
+
"print(\"pred_masks :\", outputs.pred_masks)"
|
| 171 |
+
]
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"id": "f64bc619",
|
| 177 |
+
"metadata": {
|
| 178 |
+
"vscode": {
|
| 179 |
+
"languageId": "plaintext"
|
| 180 |
+
}
|
| 181 |
+
},
|
| 182 |
+
"outputs": [],
|
| 183 |
+
"source": [
|
| 184 |
+
"input_points = [[[250, 200], [15, 50]]]\n",
|
| 185 |
+
"input_labels = [[[0, 1]]]\n",
|
| 186 |
+
"input_boxes = [[[100, 100, 400, 600]]]\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"show_point_box(image, input_points[0], input_labels[0], input_boxes[0])\n",
|
| 189 |
+
"inputs = processor(\n",
|
| 190 |
+
" image,\n",
|
| 191 |
+
" input_points=input_points,\n",
|
| 192 |
+
" input_labels=input_labels,\n",
|
| 193 |
+
" input_boxes=input_boxes,\n",
|
| 194 |
+
" return_tensors=\"pt\"\n",
|
| 195 |
+
")\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"model.eval()\n",
|
| 198 |
+
"with torch.no_grad():\n",
|
| 199 |
+
" outputs = model(**inputs)\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"masks = processor.image_processor.post_process_masks(\n",
|
| 202 |
+
" outputs.pred_masks.cpu(),\n",
|
| 203 |
+
" inputs[\"original_sizes\"].cpu(),\n",
|
| 204 |
+
" inputs[\"reshaped_input_sizes\"].cpu(),\n",
|
| 205 |
+
")\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"show_masks_on_image(image, masks[0], outputs.iou_scores)"
|
| 208 |
+
]
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"id": "dfe37f93",
|
| 214 |
+
"metadata": {
|
| 215 |
+
"vscode": {
|
| 216 |
+
"languageId": "plaintext"
|
| 217 |
+
}
|
| 218 |
+
},
|
| 219 |
+
"outputs": [],
|
| 220 |
+
"source": [
|
| 221 |
+
"from transformers import pipeline\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"generator = pipeline(\"mask-generation\", model=model_name)\n",
|
| 224 |
+
"outputs = generator(image, points_per_batch=32)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"plt.imshow(np.array(image))\n",
|
| 227 |
+
"ax = plt.gca()\n",
|
| 228 |
+
"for mask in outputs[\"masks\"]:\n",
|
| 229 |
+
" show_mask(mask, ax=ax, random_color=True)\n",
|
| 230 |
+
"plt.axis(\"off\")\n",
|
| 231 |
+
"plt.show()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"print(\"outputs mask의 개수 :\", len(outputs[\"masks\"]))\n",
|
| 234 |
+
"print(\"outputs scores의 개수 :\", len(outputs[\"scores\"]))"
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"id": "5277bdad",
|
| 241 |
+
"metadata": {
|
| 242 |
+
"vscode": {
|
| 243 |
+
"languageId": "plaintext"
|
| 244 |
+
}
|
| 245 |
+
},
|
| 246 |
+
"outputs": [],
|
| 247 |
+
"source": [
|
| 248 |
+
"detector = pipeline(\n",
|
| 249 |
+
" model=\"google/owlv2-base-patch16\", task=\"zero-shot-object-detection\"\n",
|
| 250 |
+
")\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"image = converted_dataset[24][\"img\"]\n",
|
| 253 |
+
"labels = [\"dog\", \"giraffe\"]\n",
|
| 254 |
+
"results = detector(image, candidate_labels=labels, threshold=0.5)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"input_boxes = []\n",
|
| 257 |
+
"for result in results:\n",
|
| 258 |
+
" input_boxes.append(\n",
|
| 259 |
+
" [\n",
|
| 260 |
+
" result[\"box\"][\"xmin\"],\n",
|
| 261 |
+
" result[\"box\"][\"ymin\"],\n",
|
| 262 |
+
" result[\"box\"][\"xmax\"],\n",
|
| 263 |
+
" result[\"box\"][\"ymax\"]\n",
|
| 264 |
+
" ]\n",
|
| 265 |
+
" )\n",
|
| 266 |
+
" print(result)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"inputs = processor(image, input_boxes=[input_boxes], return_tensors=\"pt\")\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"model.eval()\n",
|
| 271 |
+
"with torch.no_grad():\n",
|
| 272 |
+
" outputs = model(**inputs)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"masks = processor.image_processor.post_process_masks(\n",
|
| 275 |
+
" outputs.pred_masks.cpu(),\n",
|
| 276 |
+
" inputs[\"original_sizes\"].cpu(),\n",
|
| 277 |
+
" inputs[\"reshaped_input_sizes\"].cpu()\n",
|
| 278 |
+
")\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"plt.imshow(np.array(image))\n",
|
| 281 |
+
"ax = plt.gca()\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"for mask, iou in zip(masks[0], outputs.iou_scores[0]):\n",
|
| 284 |
+
" max_iou_idx = torch.argmax(iou)\n",
|
| 285 |
+
" best_mask = mask[max_iou_idx]\n",
|
| 286 |
+
" show_mask(best_mask, ax=ax, random_color=True)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"plt.axis(\"off\")\n",
|
| 289 |
+
"plt.show()"
|
| 290 |
+
]
|
| 291 |
+
}
|
| 292 |
+
],
|
| 293 |
+
"metadata": {
|
| 294 |
+
"kernelspec": {
|
| 295 |
+
"display_name": "Python 3 (ipykernel)",
|
| 296 |
+
"language": "python",
|
| 297 |
+
"name": "python3"
|
| 298 |
+
},
|
| 299 |
+
"language_info": {
|
| 300 |
+
"codemirror_mode": {
|
| 301 |
+
"name": "ipython",
|
| 302 |
+
"version": 3
|
| 303 |
+
},
|
| 304 |
+
"file_extension": ".py",
|
| 305 |
+
"mimetype": "text/x-python",
|
| 306 |
+
"name": "python",
|
| 307 |
+
"nbconvert_exporter": "python",
|
| 308 |
+
"pygments_lexer": "ipython3",
|
| 309 |
+
"version": "3.9.13"
|
| 310 |
+
}
|
| 311 |
+
},
|
| 312 |
+
"nbformat": 4,
|
| 313 |
+
"nbformat_minor": 5
|
| 314 |
+
}
|
5장 멀티모달/예제 5.01 ~ 5.02 BLIP-2 모델 구조.ipynb
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "da11820c",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import Blip2Config\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"model_name = \"Salesforce/blip2-opt-2.7b\"\n",
|
| 13 |
+
"config = Blip2Config.from_pretrained(model_name)\n",
|
| 14 |
+
"print(config)"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"id": "6d3977dd",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"outputs": [],
|
| 23 |
+
"source": [
|
| 24 |
+
"from transformers import Blip2ForConditionalGeneration\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"model = Blip2ForConditionalGeneration(config)\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"for main_name, main_module in model.named_children():\n",
|
| 29 |
+
" print(main_name)\n",
|
| 30 |
+
" for sub_name, sub_module in main_module.named_children():\n",
|
| 31 |
+
" print(\"└\", sub_name)\n",
|
| 32 |
+
" for ssub_name, ssub_module in sub_module.named_children():\n",
|
| 33 |
+
" print(\"│ └\", ssub_name)\n",
|
| 34 |
+
" for sssub_name, sssub_module in ssub_module.named_children():\n",
|
| 35 |
+
" print(\"│ └\", sssub_name)"
|
| 36 |
+
]
|
| 37 |
+
}
|
| 38 |
+
],
|
| 39 |
+
"metadata": {
|
| 40 |
+
"kernelspec": {
|
| 41 |
+
"display_name": "Python 3 (ipykernel)",
|
| 42 |
+
"language": "python",
|
| 43 |
+
"name": "python3"
|
| 44 |
+
},
|
| 45 |
+
"language_info": {
|
| 46 |
+
"codemirror_mode": {
|
| 47 |
+
"name": "ipython",
|
| 48 |
+
"version": 3
|
| 49 |
+
},
|
| 50 |
+
"file_extension": ".py",
|
| 51 |
+
"mimetype": "text/x-python",
|
| 52 |
+
"name": "python",
|
| 53 |
+
"nbconvert_exporter": "python",
|
| 54 |
+
"pygments_lexer": "ipython3",
|
| 55 |
+
"version": "3.9.13"
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"nbformat": 4,
|
| 59 |
+
"nbformat_minor": 5
|
| 60 |
+
}
|
5장 멀티모달/예제 5.03 ~ 5.05 BLIP-2 모델 작동 방식.ipynb
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "6d3977dd",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"from datasets import load_dataset\n",
|
| 12 |
+
"from transformers import Blip2Processor, Blip2ForConditionalGeneration\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"model_name = \"Salesforce/blip2-opt-2.7b\"\n",
|
| 15 |
+
"processor = Blip2Processor.from_pretrained(model_name)\n",
|
| 16 |
+
"model = Blip2ForConditionalGeneration.from_pretrained(\n",
|
| 17 |
+
" model_name, torch_dtype=torch.float16, device_map=\"auto\"\n",
|
| 18 |
+
")\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 21 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"inputs = processor(images=image, return_tensors=\"pt\").to(\n",
|
| 24 |
+
" model.device, dtype=torch.float16\n",
|
| 25 |
+
")\n",
|
| 26 |
+
"image_embeds = model.vision_model(\n",
|
| 27 |
+
" inputs[\"pixel_values\"], return_dict=True\n",
|
| 28 |
+
").last_hidden_state\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"print(model.vision_model)\n",
|
| 31 |
+
"print(image_embeds)\n",
|
| 32 |
+
"print(image_embeds.shape)"
|
| 33 |
+
]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"id": "b9e4454f",
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"outputs": [],
|
| 41 |
+
"source": [
|
| 42 |
+
"image_attention_mask = torch.ones(\n",
|
| 43 |
+
" image_embeds.size()[:-1], dtype=torch.long, device=model.device\n",
|
| 44 |
+
")\n",
|
| 45 |
+
"query_tokens = model.query_tokens.expand(image_embeds.shape[0], -1, -1)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"query_outputs = model.qformer(\n",
|
| 48 |
+
" query_embeds=query_tokens,\n",
|
| 49 |
+
" encoder_hidden_states=image_embeds,\n",
|
| 50 |
+
" encoder_attention_mask=image_attention_mask,\n",
|
| 51 |
+
" return_dict=True\n",
|
| 52 |
+
")\n",
|
| 53 |
+
"query_output = query_outputs.last_hidden_state\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"print(image_attention_mask.shape)\n",
|
| 56 |
+
"print(query_tokens.shape)\n",
|
| 57 |
+
"print(query_output.shape)"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"id": "53afdc60",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"outputs": [],
|
| 66 |
+
"source": [
|
| 67 |
+
"language_model_inputs = model.language_projection(query_output)\n",
|
| 68 |
+
"language_attention_mask = torch.ones(\n",
|
| 69 |
+
" language_model_inputs.size()[:-1],\n",
|
| 70 |
+
" dtype=torch.long,\n",
|
| 71 |
+
" device=model.device\n",
|
| 72 |
+
")\n",
|
| 73 |
+
"input_ids = (\n",
|
| 74 |
+
" torch.LongTensor([[model.config.text_config.bos_token_id]])\n",
|
| 75 |
+
" .repeat(inputs[\"pixel_values\"].shape[0], 1)\n",
|
| 76 |
+
" .to(model.device)\n",
|
| 77 |
+
")\n",
|
| 78 |
+
"attention_mask = torch.ones_like(input_ids)\n",
|
| 79 |
+
"attention_mask = torch.cat(\n",
|
| 80 |
+
" [language_attention_mask, attention_mask.to(model.device)], dim=1\n",
|
| 81 |
+
")\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"print(language_model_inputs.shape)\n",
|
| 84 |
+
"print(input_ids)\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"inputs_embeds = model.get_input_embeddings()(input_ids)\n",
|
| 87 |
+
"inputs_embeds = torch.cat(\n",
|
| 88 |
+
" [language_model_inputs, inputs_embeds.to(model.device)], dim=1\n",
|
| 89 |
+
")\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"outputs = model.language_model.generate(\n",
|
| 92 |
+
" inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_length=50\n",
|
| 93 |
+
")\n",
|
| 94 |
+
"print(outputs)\n",
|
| 95 |
+
"print(outputs.shape)"
|
| 96 |
+
]
|
| 97 |
+
}
|
| 98 |
+
],
|
| 99 |
+
"metadata": {
|
| 100 |
+
"kernelspec": {
|
| 101 |
+
"display_name": "Python 3 (ipykernel)",
|
| 102 |
+
"language": "python",
|
| 103 |
+
"name": "python3"
|
| 104 |
+
},
|
| 105 |
+
"language_info": {
|
| 106 |
+
"codemirror_mode": {
|
| 107 |
+
"name": "ipython",
|
| 108 |
+
"version": 3
|
| 109 |
+
},
|
| 110 |
+
"file_extension": ".py",
|
| 111 |
+
"mimetype": "text/x-python",
|
| 112 |
+
"name": "python",
|
| 113 |
+
"nbconvert_exporter": "python",
|
| 114 |
+
"pygments_lexer": "ipython3",
|
| 115 |
+
"version": "3.9.13"
|
| 116 |
+
}
|
| 117 |
+
},
|
| 118 |
+
"nbformat": 4,
|
| 119 |
+
"nbformat_minor": 5
|
| 120 |
+
}
|
5장 멀티모달/예제 5.06 ~ 5.07 이미지 캡셔닝.ipynb
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "f3c6f204",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"import torch\n",
|
| 15 |
+
"from datasets import load_dataset\n",
|
| 16 |
+
"from transformers import Blip2Processor, Blip2ForConditionalGeneration\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"model_name = \"Salesforce/blip2-opt-2.7b\"\n",
|
| 19 |
+
"processor = Blip2Processor.from_pretrained(model_name)\n",
|
| 20 |
+
"model = Blip2ForConditionalGeneration.from_pretrained(\n",
|
| 21 |
+
" model_name, torch_dtype=torch.float16, device_map=\"auto\"\n",
|
| 22 |
+
")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"dataset = load_dataset(\"huggingface/cats-image\")\n",
|
| 25 |
+
"image = dataset[\"test\"][\"image\"][0]\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"inputs = processor(images=image, return_tensors=\"pt\").to(model.device, torch.float16)\n",
|
| 28 |
+
"generated_ids = model.generate(**inputs, max_length=50)\n",
|
| 29 |
+
"print(generated_ids)\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n",
|
| 32 |
+
"print(generated_text)"
|
| 33 |
+
]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"id": "4b26083c",
|
| 39 |
+
"metadata": {
|
| 40 |
+
"vscode": {
|
| 41 |
+
"languageId": "plaintext"
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"outputs": [],
|
| 45 |
+
"source": [
|
| 46 |
+
"prompt = \"Question: Describe the location of the image. Answer:\"\n",
|
| 47 |
+
"inputs = processor(images=image, text=prompt, return_tensors=\"pt\").to(model.device, dtype=torch.float16)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"generated_ids = model.generate(**inputs, max_length=50)\n",
|
| 50 |
+
"generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()\n",
|
| 51 |
+
"print(generated_text)"
|
| 52 |
+
]
|
| 53 |
+
}
|
| 54 |
+
],
|
| 55 |
+
"metadata": {
|
| 56 |
+
"kernelspec": {
|
| 57 |
+
"display_name": "Python 3 (ipykernel)",
|
| 58 |
+
"language": "python",
|
| 59 |
+
"name": "python3"
|
| 60 |
+
},
|
| 61 |
+
"language_info": {
|
| 62 |
+
"codemirror_mode": {
|
| 63 |
+
"name": "ipython",
|
| 64 |
+
"version": 3
|
| 65 |
+
},
|
| 66 |
+
"file_extension": ".py",
|
| 67 |
+
"mimetype": "text/x-python",
|
| 68 |
+
"name": "python",
|
| 69 |
+
"nbconvert_exporter": "python",
|
| 70 |
+
"pygments_lexer": "ipython3",
|
| 71 |
+
"version": "3.9.13"
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"nbformat": 4,
|
| 75 |
+
"nbformat_minor": 5
|
| 76 |
+
}
|
5장 멀티모달/예제 5.08 ~ 5.09 LayoutLMv3 모델 구조.ipynb
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "f3c6f204",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"from transformers import LayoutLMv3Config\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"model_name = \"microsoft/layoutlmv3-base\"\n",
|
| 17 |
+
"config = LayoutLMv3Config(model_name)\n",
|
| 18 |
+
"print(config)"
|
| 19 |
+
]
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "code",
|
| 23 |
+
"execution_count": null,
|
| 24 |
+
"id": "4b26083c",
|
| 25 |
+
"metadata": {
|
| 26 |
+
"vscode": {
|
| 27 |
+
"languageId": "plaintext"
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"outputs": [],
|
| 31 |
+
"source": [
|
| 32 |
+
"from transformers import LayoutLMv3Model\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"model = LayoutLMv3Model.from_pretrained(model_name)\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"for main_name, main_module in model.named_children():\n",
|
| 37 |
+
" print(main_name)\n",
|
| 38 |
+
" for sub_name, sub_module in main_module.named_children():\n",
|
| 39 |
+
" print(\"└\", sub_name)\n",
|
| 40 |
+
" for ssub_name, ssub_module in sub_module.named_children():\n",
|
| 41 |
+
" print(\"│ └\", ssub_name)\n",
|
| 42 |
+
" for sssub_name, sssub_module in ssub_module.named_children():\n",
|
| 43 |
+
" print(\"│ └\", sssub_name)"
|
| 44 |
+
]
|
| 45 |
+
}
|
| 46 |
+
],
|
| 47 |
+
"metadata": {
|
| 48 |
+
"kernelspec": {
|
| 49 |
+
"display_name": "Python 3 (ipykernel)",
|
| 50 |
+
"language": "python",
|
| 51 |
+
"name": "python3"
|
| 52 |
+
},
|
| 53 |
+
"language_info": {
|
| 54 |
+
"codemirror_mode": {
|
| 55 |
+
"name": "ipython",
|
| 56 |
+
"version": 3
|
| 57 |
+
},
|
| 58 |
+
"file_extension": ".py",
|
| 59 |
+
"mimetype": "text/x-python",
|
| 60 |
+
"name": "python",
|
| 61 |
+
"nbconvert_exporter": "python",
|
| 62 |
+
"pygments_lexer": "ipython3",
|
| 63 |
+
"version": "3.9.13"
|
| 64 |
+
}
|
| 65 |
+
},
|
| 66 |
+
"nbformat": 4,
|
| 67 |
+
"nbformat_minor": 5
|
| 68 |
+
}
|
5장 멀티모달/예제 5.10 ~ 5.15 문서 시각 질의 응답.ipynb
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "22628136",
|
| 7 |
+
"metadata": {
|
| 8 |
+
"vscode": {
|
| 9 |
+
"languageId": "plaintext"
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"outputs": [],
|
| 13 |
+
"source": [
|
| 14 |
+
"!pip3 install pytesseract"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"id": "ddf62285",
|
| 21 |
+
"metadata": {
|
| 22 |
+
"vscode": {
|
| 23 |
+
"languageId": "plaintext"
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"outputs": [],
|
| 27 |
+
"source": [
|
| 28 |
+
"# # Windows\n",
|
| 29 |
+
"# import pytesseract\n",
|
| 30 |
+
"# pytesseract.pytesseract.tesseract_cmd = r\"<설치 경로>\\tesseract.exe\""
|
| 31 |
+
]
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"id": "e4bf6720",
|
| 37 |
+
"metadata": {
|
| 38 |
+
"vscode": {
|
| 39 |
+
"languageId": "plaintext"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"outputs": [],
|
| 43 |
+
"source": [
|
| 44 |
+
"# # macOS\n",
|
| 45 |
+
"# brew install tesseract"
|
| 46 |
+
]
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"id": "b0d808bd",
|
| 52 |
+
"metadata": {
|
| 53 |
+
"vscode": {
|
| 54 |
+
"languageId": "plaintext"
|
| 55 |
+
}
|
| 56 |
+
},
|
| 57 |
+
"outputs": [],
|
| 58 |
+
"source": [
|
| 59 |
+
"# # Linux/Google Colab\n",
|
| 60 |
+
"# sudo apt install tesseract-ocr"
|
| 61 |
+
]
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"id": "f3c6f204",
|
| 67 |
+
"metadata": {
|
| 68 |
+
"vscode": {
|
| 69 |
+
"languageId": "plaintext"
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
"outputs": [],
|
| 73 |
+
"source": [
|
| 74 |
+
"import io\n",
|
| 75 |
+
"from PIL import Image\n",
|
| 76 |
+
"from datasets import load_dataset\n",
|
| 77 |
+
"from transformers import LayoutLMv3FeatureExtractor\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"def get_ocr_words_and_boxes(sample):\n",
|
| 80 |
+
" image_bytes = io.BytesIO(sample[\"image\"])\n",
|
| 81 |
+
" image = Image.open(image_bytes)\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" encoded_inputs = feature_extractor(image)\n",
|
| 84 |
+
" sample[\"words\"] = encoded_inputs.words[0]\n",
|
| 85 |
+
" sample[\"boxes\"] = encoded_inputs.boxes[0]\n",
|
| 86 |
+
" sample[\"pixel_values\"] = encoded_inputs.pixel_values[0]\n",
|
| 87 |
+
" return sample\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"dataset = load_dataset(\"s076923/docvqa-train\")\n",
|
| 90 |
+
"model_name = \"microsoft/layoutlmv3-base\"\n",
|
| 91 |
+
"feature_extractor = LayoutLMv3FeatureExtractor(model_name)\n",
|
| 92 |
+
"dataset_with_ocr = dataset[\"train\"].map(get_ocr_words_and_boxes)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"print(dataset_with_ocr[1].keys())\n",
|
| 95 |
+
"print(\"question :\", dataset_with_ocr[1][\"question\"])\n",
|
| 96 |
+
"print(\"answers :\", dataset_with_ocr[1][\"answers\"])\n",
|
| 97 |
+
"print(\"words :\", dataset_with_ocr[1][\"words\"])\n",
|
| 98 |
+
"print(\"boxes :\", dataset_with_ocr[1][\"boxes\"])"
|
| 99 |
+
]
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"id": "4b26083c",
|
| 105 |
+
"metadata": {
|
| 106 |
+
"vscode": {
|
| 107 |
+
"languageId": "plaintext"
|
| 108 |
+
}
|
| 109 |
+
},
|
| 110 |
+
"outputs": [],
|
| 111 |
+
"source": [
|
| 112 |
+
"def find_sublist(word_list, target_list):\n",
|
| 113 |
+
" word_list = [word.lower() for word in word_list]\n",
|
| 114 |
+
" target_list = target_list.lower().split()\n",
|
| 115 |
+
"\n",
|
| 116 |
+
" for i in range(len(word_list) - len(target_list) + 1):\n",
|
| 117 |
+
" if word_list[i : i + len(target_list)] == target_list:\n",
|
| 118 |
+
" return target_list, i, i + len(target_list) - 1\n",
|
| 119 |
+
" return None, 0, 0\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"question = dataset_with_ocr[10][\"question\"]\n",
|
| 122 |
+
"words = dataset_with_ocr[10][\"words\"]\n",
|
| 123 |
+
"answers = dataset_with_ocr[10][\"answers\"]\n",
|
| 124 |
+
"print(question)\n",
|
| 125 |
+
"print(words)\n",
|
| 126 |
+
"print(answers)\n",
|
| 127 |
+
"print()\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"for answer in answers:\n",
|
| 130 |
+
" match, word_idx_start, word_idx_end = find_sublist(words, answer)\n",
|
| 131 |
+
" print(\"Match :\", match)\n",
|
| 132 |
+
" print(\"Word idx start :\", word_idx_start)\n",
|
| 133 |
+
" print(\"Word idx end :\", word_idx_end)\n",
|
| 134 |
+
" print()"
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"id": "842dce7b",
|
| 141 |
+
"metadata": {
|
| 142 |
+
"vscode": {
|
| 143 |
+
"languageId": "plaintext"
|
| 144 |
+
}
|
| 145 |
+
},
|
| 146 |
+
"outputs": [],
|
| 147 |
+
"source": [
|
| 148 |
+
"from transformers import LayoutLMv3TokenizerFast\n",
|
| 149 |
+
"from datasets import Features, Sequence, Value, Array2D, Array3D\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"def find_answer_match(words, answers):\n",
|
| 152 |
+
" for answer in answers:\n",
|
| 153 |
+
" match, word_idx_start, word_idx_end = find_sublist(words, answer)\n",
|
| 154 |
+
" if match:\n",
|
| 155 |
+
" return match, word_idx_start, word_idx_end\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" for answer in answers:\n",
|
| 158 |
+
" for i in range(len(answer)):\n",
|
| 159 |
+
" answer_modified = answer[:i] + answer[i + 1 :]\n",
|
| 160 |
+
" match, word_idx_start, word_idx_end = find_sublist(words, answer_modified)\n",
|
| 161 |
+
" if match:\n",
|
| 162 |
+
" return match, word_idx_start, word_idx_end\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" return False, None, None\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"def encode_dataset(examples, processor, max_length=512):\n",
|
| 167 |
+
" encoding = processor(\n",
|
| 168 |
+
" examples[\"question\"],\n",
|
| 169 |
+
" examples[\"words\"],\n",
|
| 170 |
+
" examples[\"boxes\"],\n",
|
| 171 |
+
" max_length=max_length,\n",
|
| 172 |
+
" padding=\"max_length\",\n",
|
| 173 |
+
" truncation=True\n",
|
| 174 |
+
" )\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" cls_index = encoding.input_ids.index(processor.cls_token_id)\n",
|
| 177 |
+
" start_position = end_position = cls_index\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" match, word_idx_start, word_idx_end = find_answer_match(\n",
|
| 180 |
+
" examples[\"words\"], examples[\"answers\"]\n",
|
| 181 |
+
" )\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" if match:\n",
|
| 184 |
+
" sequence_ids = encoding.sequence_ids(0)\n",
|
| 185 |
+
" token_start_index = next(i for i, seq_id in enumerate(sequence_ids) if seq_id == 1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" token_end_index = len(encoding.input_ids) - 1 - sequence_ids[::-1].index(1)\n",
|
| 188 |
+
" word_ids = encoding.word_ids()[token_start_index : token_end_index + 1]\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" start_position = token_start_index + word_ids.index(word_idx_start)\n",
|
| 191 |
+
" end_position = token_end_index - word_ids[::-1].index(word_idx_end)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" encoding[\"image\"] = examples[\"pixel_values\"]\n",
|
| 194 |
+
" encoding[\"start_positions\"] = start_position\n",
|
| 195 |
+
" encoding[\"end_positions\"] = end_position\n",
|
| 196 |
+
" return encoding\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"processor = LayoutLMv3TokenizerFast.from_pretrained(model_name)\n",
|
| 199 |
+
"encoded_dataset = dataset_with_ocr.map(\n",
|
| 200 |
+
" lambda x: encode_dataset(x, processor),\n",
|
| 201 |
+
" remove_columns=dataset_with_ocr.column_names,\n",
|
| 202 |
+
" features=Features(\n",
|
| 203 |
+
" {\n",
|
| 204 |
+
" \"input_ids\": Sequence(feature=Value(dtype=\"int64\")),\n",
|
| 205 |
+
" \"bbox\": Array2D(dtype=\"int64\", shape=(512, 4)),\n",
|
| 206 |
+
" \"attention_mask\": Sequence(Value(dtype=\"int64\")),\n",
|
| 207 |
+
" \"image\": Array3D(dtype=\"float32\", shape=(3, 224, 224)),\n",
|
| 208 |
+
" \"start_positions\": Value(dtype=\"int64\"),\n",
|
| 209 |
+
" \"end_positions\": Value(dtype=\"int64\")\n",
|
| 210 |
+
" }\n",
|
| 211 |
+
" )\n",
|
| 212 |
+
")\n",
|
| 213 |
+
"print(encoded_dataset)"
|
| 214 |
+
]
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"id": "1744922d",
|
| 220 |
+
"metadata": {
|
| 221 |
+
"vscode": {
|
| 222 |
+
"languageId": "plaintext"
|
| 223 |
+
}
|
| 224 |
+
},
|
| 225 |
+
"outputs": [],
|
| 226 |
+
"source": [
|
| 227 |
+
"from transformers import TrainingArguments, Trainer\n",
|
| 228 |
+
"from transformers import LayoutLMv3ForQuestionAnswering\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"model = LayoutLMv3ForQuestionAnswering.from_pretrained(model_name)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"training_args = TrainingArguments(\n",
|
| 233 |
+
" output_dir=\"DocVQA\",\n",
|
| 234 |
+
" num_train_epochs=20,\n",
|
| 235 |
+
" per_device_train_batch_size=4,\n",
|
| 236 |
+
" learning_rate=5e-5,\n",
|
| 237 |
+
" warmup_steps=100,\n",
|
| 238 |
+
" weight_decay=0.01,\n",
|
| 239 |
+
" logging_strategy=\"steps\",\n",
|
| 240 |
+
" logging_steps=20,\n",
|
| 241 |
+
" seed=42\n",
|
| 242 |
+
")\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"trainer = Trainer(\n",
|
| 245 |
+
" model=model,\n",
|
| 246 |
+
" args=training_args,\n",
|
| 247 |
+
" train_dataset=encoded_dataset\n",
|
| 248 |
+
")\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"trainer.train()"
|
| 251 |
+
]
|
| 252 |
+
},
|
| 253 |
+
{
|
| 254 |
+
"cell_type": "code",
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"id": "6453ba0f",
|
| 257 |
+
"metadata": {
|
| 258 |
+
"vscode": {
|
| 259 |
+
"languageId": "plaintext"
|
| 260 |
+
}
|
| 261 |
+
},
|
| 262 |
+
"outputs": [],
|
| 263 |
+
"source": [
|
| 264 |
+
"import torch\n",
|
| 265 |
+
"from transformers import LayoutLMv3Processor\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"index = 5\n",
|
| 268 |
+
"processor = LayoutLMv3Processor.from_pretrained(model_name)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"image_bytes = io.BytesIO(dataset_with_ocr[index][\"image\"])\n",
|
| 271 |
+
"image = Image.open(image_bytes)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"full_text = processor.decode(encoded_dataset[\"input_ids\"][index])\n",
|
| 274 |
+
"print(\"Full text:\", full_text)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"question = dataset_with_ocr[index][\"question\"]\n",
|
| 277 |
+
"print(\"Question:\", question)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"start_position = encoded_dataset[\"start_positions\"][index]\n",
|
| 280 |
+
"end_position = encoded_dataset[\"end_positions\"][index]\n",
|
| 281 |
+
"answer = processor.decode(\n",
|
| 282 |
+
" encoded_dataset[\"input_ids\"][index][start_position : end_position + 1]\n",
|
| 283 |
+
")\n",
|
| 284 |
+
"print(\"Answer:\", answer)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 287 |
+
"encoded_inputs = processor(image, question, return_tensors=\"pt\")\n",
|
| 288 |
+
"encoded_inputs = {k: v.to(device) for k, v in encoded_inputs.items()}\n",
|
| 289 |
+
"print(\"Encoded input keys:\", encoded_inputs.keys())"
|
| 290 |
+
]
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"execution_count": null,
|
| 295 |
+
"id": "038dbe71",
|
| 296 |
+
"metadata": {
|
| 297 |
+
"vscode": {
|
| 298 |
+
"languageId": "plaintext"
|
| 299 |
+
}
|
| 300 |
+
},
|
| 301 |
+
"outputs": [],
|
| 302 |
+
"source": [
|
| 303 |
+
"model.to(device)\n",
|
| 304 |
+
"model.eval()\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"with torch.no_grad():\n",
|
| 307 |
+
" outputs = model(**encoded_inputs)\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"start_logits, end_logits = outputs.start_logits, outputs.end_logits\n",
|
| 310 |
+
"start_index = start_logits.argmax(-1).item()\n",
|
| 311 |
+
"end_index = end_logits.argmax(-1).item()\n",
|
| 312 |
+
"predicted_answer = processor.decode(\n",
|
| 313 |
+
" encoded_inputs[\"input_ids\"].squeeze()[start_index : end_index + 1]\n",
|
| 314 |
+
")\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"print(\"Predicted start_index:\", start_index)\n",
|
| 317 |
+
"print(\"Predicted end_index:\", end_index)\n",
|
| 318 |
+
"print(\"predicted_answer:\", predicted_answer)"
|
| 319 |
+
]
|
| 320 |
+
}
|
| 321 |
+
],
|
| 322 |
+
"metadata": {
|
| 323 |
+
"kernelspec": {
|
| 324 |
+
"display_name": "Python 3 (ipykernel)",
|
| 325 |
+
"language": "python",
|
| 326 |
+
"name": "python3"
|
| 327 |
+
},
|
| 328 |
+
"language_info": {
|
| 329 |
+
"codemirror_mode": {
|
| 330 |
+
"name": "ipython",
|
| 331 |
+
"version": 3
|
| 332 |
+
},
|
| 333 |
+
"file_extension": ".py",
|
| 334 |
+
"mimetype": "text/x-python",
|
| 335 |
+
"name": "python",
|
| 336 |
+
"nbconvert_exporter": "python",
|
| 337 |
+
"pygments_lexer": "ipython3",
|
| 338 |
+
"version": "3.9.13"
|
| 339 |
+
}
|
| 340 |
+
},
|
| 341 |
+
"nbformat": 4,
|
| 342 |
+
"nbformat_minor": 5
|
| 343 |
+
}
|
5장 멀티모달/예제 5.16 ~ 5.17 ViLT 모델 구조 copy.ipynb
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "da11820c",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"from transformers import ViltConfig\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"model_name = \"dandelin/vilt-b32-mlm\"\n",
|
| 13 |
+
"config = ViltConfig.from_pretrained(model_name)\n",
|
| 14 |
+
"print(config)"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"id": "6d3977dd",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"outputs": [],
|
| 23 |
+
"source": [
|
| 24 |
+
"from transformers import ViltModel\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"model = ViltModel.from_pretrained(model_name)\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"for main_name, main_module in model.named_children():\n",
|
| 29 |
+
" print(main_name)\n",
|
| 30 |
+
" for sub_name, sub_module in main_module.named_children():\n",
|
| 31 |
+
" print(\"└\", sub_name)\n",
|
| 32 |
+
" for ssub_name, ssub_module in sub_module.named_children():\n",
|
| 33 |
+
" print(\"│ └\", ssub_name)\n",
|
| 34 |
+
" for sssub_name, sssub_module in ssub_module.named_children():\n",
|
| 35 |
+
" print(\"│ └\", sssub_name)"
|
| 36 |
+
]
|
| 37 |
+
}
|
| 38 |
+
],
|
| 39 |
+
"metadata": {
|
| 40 |
+
"kernelspec": {
|
| 41 |
+
"display_name": "Python 3 (ipykernel)",
|
| 42 |
+
"language": "python",
|
| 43 |
+
"name": "python3"
|
| 44 |
+
},
|
| 45 |
+
"language_info": {
|
| 46 |
+
"codemirror_mode": {
|
| 47 |
+
"name": "ipython",
|
| 48 |
+
"version": 3
|
| 49 |
+
},
|
| 50 |
+
"file_extension": ".py",
|
| 51 |
+
"mimetype": "text/x-python",
|
| 52 |
+
"name": "python",
|
| 53 |
+
"nbconvert_exporter": "python",
|
| 54 |
+
"pygments_lexer": "ipython3",
|
| 55 |
+
"version": "3.9.13"
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"nbformat": 4,
|
| 59 |
+
"nbformat_minor": 5
|
| 60 |
+
}
|