diff --git "a/DistilBERT_Experiment.ipynb" "b/DistilBERT_Experiment.ipynb" new file mode 100644 --- /dev/null +++ "b/DistilBERT_Experiment.ipynb" @@ -0,0 +1,1484 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "b99032e0-8493-4322-b0d1-12a63b07c700", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "torch version: 2.5.1+cu118\n", + "torchvision version: 0.20.1+cu118\n" + ] + } + ], + "source": [ + "# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+\n", + "try:\n", + " import torch\n", + " import torchvision\n", + " print(f\"torch version: {torch.__version__}\")\n", + " print(f\"torchvision version: {torchvision.__version__}\")\n", + "except:\n", + " print(f\"[INFO] torch/torchvision versions is not available\")\n", + "\n", + "# Continue with regular imports\n", + "import matplotlib.pyplot as plt\n", + "import torch\n", + "import torchvision\n", + "import os\n", + "import pandas as pd\n", + "\n", + "from torch import nn\n", + "from torchvision import transforms\n", + "\n", + "# Try to get torchinfo, install it if it doesn't work\n", + "try:\n", + " from torchinfo import summary\n", + "except:\n", + " print(\"[INFO] Couldn't find torchinfo... installing it.\")\n", + " !pip install -q torchinfo\n", + " from torchinfo import summary" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "id": "8fedc3b3-acc4-4947-93bf-28289da0e047", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'cuda'" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "device" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "e6b148a9-e056-4033-8298-c79ea02c41c0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4.47.1\n" + ] + } + ], + "source": [ + "import transformers\n", + "print(transformers.__version__) # 應該輸出 transformers 的版本號" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "5f27aa58-690b-4574-86a3-1a5514934450", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting demos/DistilBERT_Experiment/model.py\n" + ] + } + ], + "source": [ + "%%writefile demos/DistilBERT_Experiment/model.py\n", + "import torch\n", + "from torch import nn\n", + "import transformers\n", + "from transformers import DistilBertForSequenceClassification, DistilBertTokenizer\n", + "\n", + "def create_distilbert_model(num_classes: int = 2, seed: int = 42):\n", + " \"\"\"\n", + " Creates a DistilBERT model for sentiment analysis with a customized classification head.\n", + "\n", + " Args:\n", + " num_classes (int): Number of output classes.\n", + " seed (int): Random seed for reproducibility.\n", + "\n", + " Returns:\n", + " model (torch.nn.Module): DistilBERT model with a custom classification head.\n", + " tokenizer (transformers.PreTrainedTokenizer): Tokenizer for text preprocessing.\n", + " \"\"\"\n", + " # Set random seed for reproducibility\n", + " torch.manual_seed(seed)\n", + "\n", + " # Load pre-trained DistilBERT model\n", + " model = DistilBertForSequenceClassification.from_pretrained(\n", + " \"distilbert-base-uncased\",\n", + " num_labels=num_classes # Output layer matches the number of classes\n", + " )\n", + "\n", + " # Freeze base model parameters (optional)\n", + " for param in model.distilbert.parameters():\n", + " param.requires_grad = False\n", + "\n", + " # Customize the classification head\n", + " model.classifier = nn.Sequential(\n", + " nn.Dropout(p=0.5), # Add dropout to prevent overfitting\n", + " nn.Linear(768, 256), # Add a hidden layer (768 -> 256)\n", + " nn.ReLU(), # Non-linear activation function\n", + " nn.Dropout(p=0.3), # Add another dropout layer\n", + " nn.Linear(256, num_classes) # Output layer (256 -> num_classes)\n", + " )\n", + "\n", + " # model.classifier = nn.Sequential(\n", + " # nn.Dropout(p=0.6),\n", + " # nn.Linear(768, 256),\n", + " # nn.ReLU(),\n", + " # nn.Dropout(p=0.4),\n", + " # nn.Linear(256, 2)\n", + " # )\n", + "\n", + " # Load DistilBERT tokenizer\n", + " tokenizer = DistilBertTokenizer.from_pretrained(\"distilbert-base-uncased\")\n", + "\n", + " return model, tokenizer\n", + "\n", + "def tokenize_texts_and_labels(tokenizer, texts, labels=None, max_length=128):\n", + " \"\"\"\n", + " 將文本數據進行分詞,並處理標籤(如果提供)。\n", + " Args:\n", + " tokenizer: 分詞器,用於將文本轉換為模型輸入格式。\n", + " texts (list[str]): 文本數據列表。\n", + " labels (list[int], optional): 標籤列表,可選。\n", + " max_length (int): 最大文本長度。\n", + " Returns:\n", + " dict: 包含分詞結果的字典,包括 input_ids、attention_mask 和 labels(如果提供)。\n", + " \"\"\"\n", + " encodings = tokenizer(\n", + " list(texts),\n", + " padding=\"max_length\",\n", + " truncation=True,\n", + " max_length=max_length,\n", + " return_tensors=\"pt\"\n", + " )\n", + " if labels is not None:\n", + " encodings[\"labels\"] = torch.tensor(labels) # 將標籤轉為 PyTorch 張量\n", + " return encodings" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "d984ebb6-b452-451b-9336-0239b99b60d6", + "metadata": {}, + "outputs": [], + "source": [ + "import sys\n", + "import os\n", + "\n", + "# 新增 `demos/DistilBERT_Experiment/` 到 Python 的模組搜尋路徑\n", + "sys.path.append(os.path.join(os.getcwd(), \"demos\", \"DistilBERT_Experiment\"))\n", + "\n", + "# 從 model 模組中匯入函數\n", + "from model import create_distilbert_model" + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "id": "7f1ea2a0-c2bc-4184-b533-2304efc6eebf", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight', 'pre_classifier.bias', 'pre_classifier.weight']\n", + "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" + ] + } + ], + "source": [ + "DistilBERT_Model, DistilBERT_Tokenizer = create_distilbert_model(num_classes=2, seed=42)" + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "id": "19404541-1d46-41e6-a28d-0763ba6d3731", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DistilBertForSequenceClassification(\n", + " (distilbert): DistilBertModel(\n", + " (embeddings): Embeddings(\n", + " (word_embeddings): Embedding(30522, 768, padding_idx=0)\n", + " (position_embeddings): Embedding(512, 768)\n", + " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " )\n", + " (transformer): Transformer(\n", + " (layer): ModuleList(\n", + " (0-5): 6 x TransformerBlock(\n", + " (attention): DistilBertSdpaAttention(\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " (q_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (k_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (v_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (out_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " )\n", + " (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " (ffn): FFN(\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " (lin1): Linear(in_features=768, out_features=3072, bias=True)\n", + " (lin2): Linear(in_features=3072, out_features=768, bias=True)\n", + " (activation): GELUActivation()\n", + " )\n", + " (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " )\n", + " )\n", + " )\n", + " )\n", + " (pre_classifier): Linear(in_features=768, out_features=768, bias=True)\n", + " (classifier): Sequential(\n", + " (0): Dropout(p=0.5, inplace=False)\n", + " (1): Linear(in_features=768, out_features=256, bias=True)\n", + " (2): ReLU()\n", + " (3): Dropout(p=0.3, inplace=False)\n", + " (4): Linear(in_features=256, out_features=2, bias=True)\n", + " )\n", + " (dropout): Dropout(p=0.2, inplace=False)\n", + ")\n", + "Total parameters: 67150850\n", + "Trainable parameters: 787970\n" + ] + } + ], + "source": [ + "# 打印模型的結構\n", + "print(DistilBERT_Model)\n", + "\n", + "# 計算參數總量和可訓練參數\n", + "total_params = sum(p.numel() for p in DistilBERT_Model.parameters())\n", + "trainable_params = sum(p.numel() for p in DistilBERT_Model.parameters() if p.requires_grad)\n", + "\n", + "print(f\"Total parameters: {total_params}\")\n", + "print(f\"Trainable parameters: {trainable_params}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "91f2bd69-9fb3-4756-a3e7-20d2fc6493bb", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\n" + ] + } + ], + "source": [ + "print(os.getcwd()) # 輸出當前工作目錄" + ] + }, + { + "cell_type": "markdown", + "id": "a4a600f6-c72a-444b-ad55-c1bc31884ee9", + "metadata": {}, + "source": [ + "### 讀取 IMDb 數據集" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "a97c7663-58af-4cd8-b24f-d0b16415e04f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\\data\\IMDb_Large_Movie_Review_Dataset\\aclImdb\n" + ] + } + ], + "source": [ + "IMDb_path = os.path.join(os.getcwd(), \"data\", \"IMDb_Large_Movie_Review_Dataset\", \"aclImdb\")\n", + "print(IMDb_path)" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "27714990-ecdf-4dba-83ef-cdb4a7af08fb", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import pandas as pd\n", + "\n", + "def load_imdb_data(data_dir):\n", + " \"\"\"\n", + " 加載 IMDb 數據集中的單一資料夾(train 或 test),並返回包含文本和標籤的 DataFrame。\n", + " Args:\n", + " data_dir (str): 資料夾的路徑(例如 'train' 或 'test' 資料夾)。\n", + " Returns:\n", + " pd.DataFrame: 包含 'text' 和 'label' 的 DataFrame。\n", + " \"\"\"\n", + " texts, labels = [], []\n", + " for sentiment in [\"pos\", \"neg\"]: # 遍歷 'pos' 和 'neg' 資料夾\n", + " dir_path = os.path.join(data_dir, sentiment)\n", + " for file_name in os.listdir(dir_path): # 遍歷該資料夾內的所有文件\n", + " with open(os.path.join(dir_path, file_name), \"r\", encoding=\"utf-8\") as f:\n", + " texts.append(f.read()) # 讀取文本內容\n", + " labels.append(1 if sentiment == \"pos\" else 0) # 添加標籤\n", + " return pd.DataFrame({\"text\": texts, \"label\": labels}) # 返回 DataFrame" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "66df4473-98e7-44f2-a250-5dd5f144ecde", + "metadata": {}, + "outputs": [], + "source": [ + "# 加載 IMDb 數據集(不分train與Test)\n", + "# 使用函式加載數據集\n", + "# imdb_df = load_imdb_data(IMDb_path)\n", + "\n", + "# 查看數據\n", + "# print(imdb_df.head())\n", + "# print(f\"總共加載了 {len(imdb_df)} 條數據!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "f60900fe-33a5-44e9-86b4-56e987148bbd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "訓練集大小: 25000\n", + "驗證集大小: 25000\n" + ] + } + ], + "source": [ + "# 加載 IMDb 並分開處理 train 和 test 數據\n", + "# 加載 train 數據\n", + "train_df = load_imdb_data(os.path.join(IMDb_path, \"train\"))\n", + "\n", + "# 加載 test 數據\n", + "test_df = load_imdb_data(os.path.join(IMDb_path, \"test\"))\n", + "\n", + "print(f\"訓練集大小: {len(train_df)}\")\n", + "print(f\"驗證集大小: {len(test_df)}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "be51c4af-d267-46a1-b261-fdb713770424", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "每篇影評的平均字數為: 1325.07\n" + ] + } + ], + "source": [ + "# 計算每篇影評的字數\n", + "train_text_lengths = train_df[\"text\"].apply(len)\n", + "\n", + "# 計算平均字數\n", + "average_length = train_text_lengths.mean()\n", + "\n", + "# 輸出結果\n", + "print(f\"每篇影評的平均字數為: {average_length:.2f}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "7f64cbd5-9fe7-42f4-94c9-1f1c70092d37", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "50% 的影評長度在 174 單詞內\n", + "75% 的影評長度在 284 單詞內\n", + "90% 的影評長度在 458 單詞內\n", + "95% 的影評長度在 598 單詞內\n", + "99% 的影評長度在 913 單詞內\n" + ] + } + ], + "source": [ + "# 計算單詞數\n", + "train_word_lengths = train_df[\"text\"].apply(lambda x: len(x.split()))\n", + "\n", + "# 查看不同分位數的文本長度\n", + "for percentile in [50, 75, 90, 95, 99]:\n", + " length_at_percentile = train_word_lengths.quantile(percentile / 100)\n", + " print(f\"{percentile}% 的影評長度在 {length_at_percentile:.0f} 單詞內\")" + ] + }, + { + "cell_type": "markdown", + "id": "ef8eed79-48c5-43e5-abe3-30e4aaa22474", + "metadata": {}, + "source": [ + "### 將讀取的 data 轉換成 model 的 input 格式" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "65a24cba-751f-43a8-9498-5c979831e5b8", + "metadata": {}, + "outputs": [], + "source": [ + "# tokenizer 的基本功能:\n", + "# input_ids:文本的 token ID(數字表示)。\n", + "# attention_mask:用於區分有效 token 和填充部分(padding)的掩碼。\n", + "# 而 model 的 input 需要 labels" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "c11232ae-4134-440e-9ea0-795a5df965d5", + "metadata": {}, + "outputs": [], + "source": [ + "def tokenize_texts_and_labels(tokenizer, texts, labels=None, max_length=128):\n", + " \"\"\"\n", + " 將文本數據進行分詞,並處理標籤(如果提供)。\n", + " Args:\n", + " tokenizer: 分詞器,用於將文本轉換為模型輸入格式。\n", + " texts (list[str]): 文本數據列表。\n", + " labels (list[int], optional): 標籤列表,可選。\n", + " max_length (int): 最大文本長度。\n", + " Returns:\n", + " dict: 包含分詞結果的字典,包括 input_ids、attention_mask 和 labels(如果提供)。\n", + " \"\"\"\n", + " encodings = tokenizer(\n", + " list(texts),\n", + " padding=\"max_length\",\n", + " truncation=True,\n", + " max_length=max_length,\n", + " return_tensors=\"pt\"\n", + " )\n", + " if labels is not None:\n", + " encodings[\"labels\"] = torch.tensor(labels) # 將標籤轉為 PyTorch 張量\n", + " return encodings" + ] + }, + { + "cell_type": "code", + "execution_count": 99, + "id": "2abd5227-cbfc-4f7a-b2e4-128fcfe25d8a", + "metadata": {}, + "outputs": [], + "source": [ + "# 處理訓練集\n", + "train_encodings = tokenize_texts_and_labels(\n", + " DistilBERT_Tokenizer,\n", + " train_df[\"text\"], # 傳入文本\n", + " labels = train_df[\"label\"], # 傳入標籤\n", + " max_length=512\n", + ")\n", + "\n", + "# 處理測試集\n", + "test_encodings = tokenize_texts_and_labels(\n", + " DistilBERT_Tokenizer,\n", + " test_df[\"text\"], # 傳入文本\n", + " labels = test_df[\"label\"], # 傳入標籤\n", + " max_length=512\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 85, + "id": "b4f9fde0-5e15-4a3e-9c16-46b873df6d9b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "print(type(train_encodings))" + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "id": "2ab86f7d-8bef-47b9-a444-bb6afc037313", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input IDs (前兩筆):\n", + "tensor([[ 101, 22953, 2213, ..., 0, 0, 0],\n", + " [ 101, 11573, 2791, ..., 0, 0, 0]])\n", + "\n", + "Attention Mask (前兩筆):\n", + "tensor([[1, 1, 1, ..., 0, 0, 0],\n", + " [1, 1, 1, ..., 0, 0, 0]])\n", + "\n", + "Labels (前兩筆):\n", + "tensor([1, 1])\n" + ] + } + ], + "source": [ + "# 查看 input_ids 的前兩筆資料\n", + "print(\"Input IDs (前兩筆):\")\n", + "print(train_encodings[\"input_ids\"][:2])\n", + "\n", + "# 查看 attention_mask 的前兩筆資料\n", + "print(\"\\nAttention Mask (前兩筆):\")\n", + "print(train_encodings[\"attention_mask\"][:2])\n", + "\n", + "# 查看 labels 的前兩筆資料(如果有標籤)\n", + "if \"labels\" in train_encodings:\n", + " print(\"\\nLabels (前兩筆):\")\n", + " print(train_encodings[\"labels\"][:2])" + ] + }, + { + "cell_type": "markdown", + "id": "51da01ee-64aa-4a0c-a077-ce9c65bca910", + "metadata": {}, + "source": [ + "### 建立 Dataset 類\n", + "### 創建 DataLoader" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "id": "c74e991a-a393-4558-be2e-1d630b75a161", + "metadata": {}, + "outputs": [], + "source": [ + "from torch.utils.data import Dataset\n", + "\n", + "class IMDbDataset(Dataset):\n", + " def __init__(self, encodings):\n", + " \"\"\"\n", + " 初始化 Dataset 類,將分詞後的數據封裝起來。\n", + " Args:\n", + " encodings (dict): 包含 input_ids、attention_mask 和(可選的)labels 的字典。\n", + " \"\"\"\n", + " self.encodings = encodings\n", + "\n", + " def __len__(self):\n", + " \"\"\"\n", + " 返回數據集的樣本數。\n", + " \"\"\"\n", + " return len(self.encodings[\"input_ids\"])\n", + "\n", + " def __getitem__(self, idx):\n", + " \"\"\"\n", + " 返回指定索引的數據(如 input_ids, attention_mask, labels)。\n", + " \"\"\"\n", + " item = {key: tensor[idx] for key, tensor in self.encodings.items()}\n", + " return item" + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "id": "2e41660d-2e2e-4bac-a853-84a831b13da1", + "metadata": {}, + "outputs": [], + "source": [ + "from torch.utils.data import DataLoader\n", + "\n", + "# 創建訓練集和測試集的 Dataset\n", + "train_dataset = IMDbDataset(train_encodings)\n", + "test_dataset = IMDbDataset(test_encodings)\n", + "\n", + "# 創建訓練集和測試集的 DataLoader\n", + "train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=16, shuffle=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "id": "cbde9720-0748-45aa-b1cf-115d26f84547", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "input_ids: torch.Size([16, 512])\n", + "attention_mask: torch.Size([16, 512])\n", + "labels: torch.Size([16])\n" + ] + } + ], + "source": [ + "# 檢查數據加載結果\n", + "# 從訓練集 DataLoader 中取出一個批次\n", + "batch = next(iter(train_loader))\n", + "\n", + "# 輸出批次的鍵和值形狀\n", + "for key, value in batch.items():\n", + " print(f\"{key}: {value.shape}\")" + ] + }, + { + "cell_type": "markdown", + "id": "720b04e0-5faa-4258-b404-d9a7a2d055c8", + "metadata": {}, + "source": [ + "### 創建 Training Process" + ] + }, + { + "cell_type": "markdown", + "id": "268be27d-f919-4a90-88bf-ddd65f3b611f", + "metadata": {}, + "source": [ + "### DistilBERTForSequenceClassification 自帶 loss,無需單獨定義損失函數" + ] + }, + { + "cell_type": "code", + "execution_count": 91, + "id": "f4830bad-a86e-4c5b-a1f9-ad6172147622", + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "from tqdm.auto import tqdm\n", + "from typing import Dict, List, Tuple\n", + "\n", + "def train_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " optimizer: torch.optim.Optimizer,\n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"\n", + " Trains a DistilBERT model for a single epoch.\n", + " \"\"\"\n", + " # Set model to training mode\n", + " model.train()\n", + "\n", + " # Initialize metrics\n", + " train_loss, train_acc = 0, 0\n", + "\n", + " # Loop through DataLoader batches\n", + " for batch in dataloader:\n", + " # Move data to the target device\n", + " input_ids = batch[\"input_ids\"].to(device)\n", + " attention_mask = batch[\"attention_mask\"].to(device)\n", + " labels = batch[\"labels\"].to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", + " loss = outputs.loss # Get the loss from model output\n", + " logits = outputs.logits # Predicted logits\n", + "\n", + " # Backward pass\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " # Accumulate metrics\n", + " train_loss += loss.item()\n", + " preds = torch.argmax(logits, dim=1)\n", + " train_acc += (preds == labels).sum().item() / len(labels)\n", + "\n", + " # Return average loss and accuracy\n", + " train_loss = train_loss / len(dataloader)\n", + " train_acc = train_acc / len(dataloader)\n", + " return train_loss, train_acc\n", + "\n", + "def test_step(model: torch.nn.Module, \n", + " dataloader: torch.utils.data.DataLoader, \n", + " device: torch.device) -> Tuple[float, float]:\n", + " \"\"\"\n", + " Evaluates a DistilBERT model for a single epoch.\n", + " \"\"\"\n", + " # Set model to evaluation mode\n", + " model.eval()\n", + "\n", + " # Initialize metrics\n", + " test_loss, test_acc = 0, 0\n", + "\n", + " # Disable gradient computation\n", + " with torch.no_grad():\n", + " for batch in dataloader:\n", + " # Move data to the target device\n", + " input_ids = batch[\"input_ids\"].to(device)\n", + " attention_mask = batch[\"attention_mask\"].to(device)\n", + " labels = batch[\"labels\"].to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", + " loss = outputs.loss # Get the loss\n", + " logits = outputs.logits # Predicted logits\n", + "\n", + " # Accumulate metrics\n", + " test_loss += loss.item()\n", + " preds = torch.argmax(logits, dim=1)\n", + " test_acc += (preds == labels).sum().item() / len(labels)\n", + "\n", + " # Return average loss and accuracy\n", + " test_loss = test_loss / len(dataloader)\n", + " test_acc = test_acc / len(dataloader)\n", + " return test_loss, test_acc\n", + "\n", + "# def train(model: torch.nn.Module, \n", + "# train_dataloader: torch.utils.data.DataLoader, \n", + "# test_dataloader: torch.utils.data.DataLoader, \n", + "# optimizer: torch.optim.Optimizer,\n", + "# epochs: int,\n", + "# device: torch.device) -> Dict[str, List]:\n", + "# \"\"\"\n", + "# Trains and evaluates a DistilBERT model for a specified number of epochs.\n", + "# \"\"\"\n", + "# # Create a dictionary to store results\n", + "# results = {\"train_loss\": [], \"train_acc\": [], \"test_loss\": [], \"test_acc\": []}\n", + "\n", + "# # Loop through epochs\n", + "# for epoch in tqdm(range(epochs)):\n", + "# # Train the model\n", + "# train_loss, train_acc = train_step(model, train_dataloader, optimizer, device)\n", + "\n", + "# # Test the model\n", + "# test_loss, test_acc = test_step(model, test_dataloader, device)\n", + "\n", + "# # Print metrics for each epoch\n", + "# print(\n", + "# f\"Epoch {epoch+1}/{epochs}: \"\n", + "# f\"Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, \"\n", + "# f\"Test Loss: {test_loss:.4f}, Test Acc: {test_acc:.4f}\"\n", + "# )\n", + "\n", + "# # Store metrics\n", + "# results[\"train_loss\"].append(train_loss)\n", + "# results[\"train_acc\"].append(train_acc)\n", + "# results[\"test_loss\"].append(test_loss)\n", + "# results[\"test_acc\"].append(test_acc)\n", + "\n", + "# return results\n", + "\n", + "def train(model: torch.nn.Module, \n", + " train_dataloader: torch.utils.data.DataLoader, \n", + " test_dataloader: torch.utils.data.DataLoader, \n", + " optimizer: torch.optim.Optimizer,\n", + " epochs: int,\n", + " device: torch.device,\n", + " lr_scheduler=None) -> Dict[str, List]:\n", + " \"\"\"\n", + " Trains and evaluates a DistilBERT model for a specified number of epochs.\n", + " \"\"\"\n", + " # Create a dictionary to store results\n", + " results = {\"train_loss\": [], \"train_acc\": [], \"test_loss\": [], \"test_acc\": [], \"lr\": []}\n", + "\n", + " # Loop through epochs\n", + " for epoch in tqdm(range(epochs)):\n", + " print(f\"Epoch {epoch+1}/{epochs}\")\n", + "\n", + " # Train the model\n", + " train_loss, train_acc = train_step(model, train_dataloader, optimizer, device)\n", + "\n", + " # Test the model\n", + " test_loss, test_acc = test_step(model, test_dataloader, device)\n", + "\n", + " # Update learning rate if scheduler is provided\n", + " if lr_scheduler:\n", + " lr_scheduler.step()\n", + "\n", + " # Get current learning rate\n", + " current_lr = optimizer.param_groups[0][\"lr\"]\n", + " results[\"lr\"].append(current_lr)\n", + "\n", + " # Print metrics for each epoch\n", + " print(\n", + " f\"Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, \"\n", + " f\"Test Loss: {test_loss:.4f}, Test Acc: {test_acc:.4f}, \"\n", + " f\"Learning Rate: {current_lr:.6f}\"\n", + " )\n", + "\n", + " # Store metrics\n", + " results[\"train_loss\"].append(train_loss)\n", + " results[\"train_acc\"].append(train_acc)\n", + " results[\"test_loss\"].append(test_loss)\n", + " results[\"test_acc\"].append(test_acc)\n", + "\n", + " return results" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "id": "1a307d22-594e-468f-ad79-f88a59fe50d7", + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "DistilBertForSequenceClassification(\n", + " (distilbert): DistilBertModel(\n", + " (embeddings): Embeddings(\n", + " (word_embeddings): Embedding(30522, 768, padding_idx=0)\n", + " (position_embeddings): Embedding(512, 768)\n", + " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " )\n", + " (transformer): Transformer(\n", + " (layer): ModuleList(\n", + " (0-5): 6 x TransformerBlock(\n", + " (attention): DistilBertSdpaAttention(\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " (q_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (k_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (v_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " (out_lin): Linear(in_features=768, out_features=768, bias=True)\n", + " )\n", + " (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " (ffn): FFN(\n", + " (dropout): Dropout(p=0.1, inplace=False)\n", + " (lin1): Linear(in_features=768, out_features=3072, bias=True)\n", + " (lin2): Linear(in_features=3072, out_features=768, bias=True)\n", + " (activation): GELUActivation()\n", + " )\n", + " (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", + " )\n", + " )\n", + " )\n", + " )\n", + " (pre_classifier): Linear(in_features=768, out_features=768, bias=True)\n", + " (classifier): Sequential(\n", + " (0): Dropout(p=0.5, inplace=False)\n", + " (1): Linear(in_features=768, out_features=256, bias=True)\n", + " (2): ReLU()\n", + " (3): Dropout(p=0.3, inplace=False)\n", + " (4): Linear(in_features=256, out_features=2, bias=True)\n", + " )\n", + " (dropout): Dropout(p=0.2, inplace=False)\n", + ")\n" + ] + } + ], + "source": [ + "print(DistilBERT_Model)" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "id": "16e022fc-d27f-42fa-977b-617eb033828b", + "metadata": {}, + "outputs": [], + "source": [ + "from torch.optim import AdamW\n", + "\n", + "# Move model to target device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "DistilBERT_Model.to(device)\n", + "\n", + "from torch.optim.lr_scheduler import StepLR\n", + "# Define optimizer\n", + "optimizer = AdamW(DistilBERT_Model.parameters(), lr=5e-5)\n", + "lr_scheduler = StepLR(optimizer, step_size=2, gamma=0.9)" + ] + }, + { + "cell_type": "code", + "execution_count": 108, + "id": "c5e5b1c4-687b-4479-b9df-aba275e4544a", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "82a9d8b32bb44845a07cc5605de7788a", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/10 [00:00" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from helper_functions import plot_loss_curves\n", + "\n", + "# Check out the loss curves for FoodVision Big\n", + "plot_loss_curves(results)" + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "id": "bfdbbf8b-99a4-4408-a939-1f965e485554", + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "bb08d09334044e9097a9f1b2f5c69c4c", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/10 [00:00" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 存到hugging face會跟這不一樣\n", + "# 加載保存的權重\n", + "DistilBERT_Model.load_state_dict(\n", + " torch.load(\n", + " f=r\"C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\\models\\DistilBERT_Model_512.pth\", # 路徑到保存的檔案\n", + " map_location=torch.device(\"cpu\") # 將權重加載到 CPU\n", + " )\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "3fb297ae-a2af-4fd1-a017-b3d8522328b7", + "metadata": {}, + "outputs": [], + "source": [ + "device = \"cpu\"" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "1f07ffb5-ce14-4957-a67a-e26f635429a4", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Logits: tensor([[ 1.7964, -1.9624]])\n", + "Prediction: 0 (Negative)\n" + ] + } + ], + "source": [ + "test_text = \"Fuck you! This movie is suck.\"\n", + "# test_text = \"This movie is fantastic!\"\n", + "\n", + "test_input = tokenize_texts_and_labels(\n", + " DistilBERT_Tokenizer,\n", + " [test_text], ## 傳入列表形式的文本\n", + " labels=None, # 測試時不需要標籤\n", + " max_length=512\n", + ")\n", + "\n", + "inputs = {key: val.to(device) for key, val in test_input.items()}\n", + "\n", + "# 推理\n", + "with torch.no_grad():\n", + " outputs = DistilBERT_Model(**inputs) # 將分詞後的字典傳入模型,**這符號是可以自動解包字典,把 input_ids 和 attention_mask 等傳遞給對應的參數。\n", + " logits = outputs.logits # 提取 logits\n", + " predictions = torch.argmax(logits, dim=1) # 預測類別\n", + "\n", + " # 將類別對應到情感標籤\n", + " label_map = {0: \"Negative\", 1: \"Positive\"} # 根據訓練時的設定調整\n", + " prediction_label = label_map[predictions.item()] # 取得單條樣本的標籤\n", + "\n", + " # 打印結果\n", + " print(f\"Logits: {logits}\")\n", + " print(f\"Prediction: {predictions.item()} ({prediction_label})\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "dbc70e38-bc44-475d-8f05-6e872835f593", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight', 'pre_classifier.bias', 'pre_classifier.weight']\n", + "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n", + "C:\\Users\\User\\AppData\\Local\\Temp\\ipykernel_15788\\3835257041.py:16: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", + " torch.load(\n" + ] + } + ], + "source": [ + "import torch\n", + "import transformers\n", + "# from model import create_distilbert_model, tokenize_texts_and_labels\n", + "from transformers import DistilBertForSequenceClassification, DistilBertTokenizer\n", + "from typing import Tuple, Dict\n", + "from timeit import default_timer as timer\n", + "\n", + "# Setup class names\n", + "with open(r\"C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\\demos\\DistilBERT_Experiment\\class_names.txt\", \"r\") as f:\n", + " class_names = [label.strip() for label in f.readlines()] # ['Negative', 'Positive']\n", + "\n", + "# 加載模型與 tokenizer\n", + "DistilBERT_Model, DistilBERT_Tokenizer = create_distilbert_model(num_classes=2, seed=42)\n", + "\n", + "DistilBERT_Model.load_state_dict(\n", + " torch.load(\n", + " f=r\"C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\\models\\DistilBERT_Model_512.pth\", # 路徑到保存的檔案\n", + " map_location=torch.device(\"cpu\") # 加載到 CPU\n", + " )\n", + ")\n", + "\n", + "# 設定設備\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "DistilBERT_Model.to(device)\n", + "\n", + "# 預測函數\n", + "def predict(text: str) -> Tuple[Dict[str, float], float]:\n", + " \"\"\"\n", + " 預測輸入文字的情感,返回預測的機率字典和耗時。\n", + " Args:\n", + " text (str): 要進行情感分析的文本\n", + " Returns:\n", + " Tuple[Dict[str, float], float]: 包含每個類別的機率字典和預測所需的時間\n", + " \"\"\"\n", + " # 計時開始\n", + " start_time = timer()\n", + " \n", + " # 將文本轉為模型輸入格式\n", + " test_input = tokenize_texts_and_labels(\n", + " DistilBERT_Tokenizer,\n", + " [text], # 傳入單條文本,需封裝為列表\n", + " labels=None, # 測試時不需要標籤\n", + " max_length=512\n", + " )\n", + " \n", + " # 移動輸入到設備(CPU/GPU)\n", + " inputs = {key: val.to(device) for key, val in test_input.items()}\n", + " \n", + " # 模型推理\n", + " DistilBERT_Model.eval() # 設定模型為評估模式\n", + " with torch.no_grad(): # 禁用梯度計算以加速推理\n", + " outputs = DistilBERT_Model(**inputs)\n", + " logits = outputs.logits # 提取 logits\n", + " \n", + " # 計算 softmax 機率\n", + " pred_probs = torch.softmax(logits, dim=1)\n", + " \n", + " # 將機率與類別名稱對應\n", + " pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}\n", + " \n", + " # 計算耗時\n", + " pred_time = round(timer() - start_time, 5)\n", + " \n", + " return pred_labels_and_probs, pred_time\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "d4dff04b-8ded-4d7f-b4ff-6f8dc0490aa9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* Running on local URL: http://127.0.0.1:7860\n", + "* Running on public URL: https://b372b5f1552bb6dd7b.gradio.live\n", + "\n", + "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import gradio as gr\n", + "\n", + "# Gradio predict function\n", + "def gradio_predict(text):\n", + " pred_labels_and_probs, pred_time = predict(text)\n", + "\n", + " # Get highest probability label\n", + " predicted_label = max(pred_labels_and_probs, key=pred_labels_and_probs.get)\n", + " predicted_probability = pred_labels_and_probs[predicted_label]\n", + "\n", + " # 給 Gradio 的輸出\n", + " # 第一個輸出:主要的情感標籤\n", + " sentiment_label = f\"{predicted_label} ({predicted_probability:.2f})\"\n", + " \n", + " # 第二個輸出:詳細的預測數據\n", + " details = {\n", + " \"Sentiment\": predicted_label,\n", + " \"Probability\": f\"{predicted_probability:.2f}\",\n", + " \"Prediction Time (s)\": pred_time,\n", + " }\n", + "\n", + " return sentiment_label, details # 確保返回兩個值\n", + "\n", + "# Gradio Interface\n", + "title = \"DistilBERT Sentiment Classifier 😃/😡\"\n", + "description = (\n", + " \"A sentiment analysis model powered by DistilBERT. \"\n", + " \"Enter a sentence and the model will classify it as Positive or Negative, \"\n", + " \"along with the prediction probability and time taken.\"\n", + ")\n", + "examples = [\n", + " [\"I love this movie!\"],\n", + " [\"This product is terrible.\"],\n", + " [\"Amazing experience, would highly recommend!\"],\n", + " [\"I hate waiting in line for hours.\"],\n", + " [\"The service was good, but the food was average.\"]\n", + "]\n", + "\n", + "# Create Gradio interface\n", + "demo = gr.Interface(\n", + " fn=gradio_predict,\n", + " inputs=gr.Textbox(lines=3, placeholder=\"Type your sentence here...\"),\n", + " outputs=[\n", + " gr.Label(label=\"Sentiment Prediction\"), # 第一個輸出:情感標籤\n", + " gr.JSON(label=\"Details\"), # 第二個輸出:詳細信息\n", + " ],\n", + " examples=examples,\n", + " title=title,\n", + " description=description\n", + ")\n", + "\n", + "# Launch the demo!\n", + "demo.launch(debug=False, # print errors locally?\n", + " share=True) # generate a publically shareable URL?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed0a353c-cb57-4310-97c1-117daf3dae27", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}