File size: 36,036 Bytes
95c04d5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 | {
"cells": [
{
"cell_type": "code",
"execution_count": 10,
"id": "84c3988f-70ba-4a88-bfa1-a23d82624e64",
"metadata": {},
"outputs": [],
"source": [
"import gradio as gr\n",
"import os\n",
"import torch\n",
"from torch import nn\n",
"import transformers\n",
"from transformers import DistilBertForSequenceClassification, DistilBertTokenizer\n",
"from typing import Tuple, Dict\n",
"from timeit import default_timer as timer"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a2b7fa40-a16c-47c0-889c-5e9890bf6475",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"C:\\Users\\User\\Desktop\\Pytorch\\pytorchPractice\n"
]
}
],
"source": [
"print(os.getcwd()) # 輸出當前工作目錄"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "b37238ff-b5ac-4d4f-85c2-7ecbbfd95651",
"metadata": {},
"outputs": [],
"source": [
"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": 11,
"id": "9f964cd0-5807-405e-85df-3a7273954974",
"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_26504\\1788877457.py:5: 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"
]
},
{
"data": {
"text/plain": [
"<All keys matched successfully>"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 加載模型與 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",
")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "66298cdd-f803-4127-b06e-ead97c078a76",
"metadata": {
"scrolled": true
},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (1090613077.py, line 2)",
"output_type": "error",
"traceback": [
"\u001b[1;36m Cell \u001b[1;32mIn[15], line 2\u001b[1;36m\u001b[0m\n\u001b[1;33m pip install faiss-cpu\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"# pip install sentence-transformers"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "db19b181-e276-400d-9fde-d78c22b380ae",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting faiss-cpu\n",
" Downloading faiss_cpu-1.9.0.post1-cp312-cp312-win_amd64.whl.metadata (4.5 kB)\n",
"Requirement already satisfied: numpy<3.0,>=1.25.0 in c:\\users\\user\\desktop\\pytorch\\lib\\site-packages (from faiss-cpu) (1.26.4)\n",
"Requirement already satisfied: packaging in c:\\users\\user\\desktop\\pytorch\\lib\\site-packages (from faiss-cpu) (24.1)\n",
"Downloading faiss_cpu-1.9.0.post1-cp312-cp312-win_amd64.whl (13.8 MB)\n",
" ---------------------------------------- 0.0/13.8 MB ? eta -:--:--\n",
" ---------------------------------------- 0.0/13.8 MB ? eta -:--:--\n",
" ---- ----------------------------------- 1.6/13.8 MB 7.0 MB/s eta 0:00:02\n",
" ----------- ---------------------------- 3.9/13.8 MB 9.4 MB/s eta 0:00:02\n",
" ------------ --------------------------- 4.5/13.8 MB 7.3 MB/s eta 0:00:02\n",
" --------------- ------------------------ 5.2/13.8 MB 6.2 MB/s eta 0:00:02\n",
" ----------------- ---------------------- 6.0/13.8 MB 5.7 MB/s eta 0:00:02\n",
" ---------------------- ----------------- 7.9/13.8 MB 6.3 MB/s eta 0:00:01\n",
" ------------------------ --------------- 8.4/13.8 MB 5.8 MB/s eta 0:00:01\n",
" -------------------------- ------------- 9.2/13.8 MB 5.6 MB/s eta 0:00:01\n",
" ---------------------------- ----------- 10.0/13.8 MB 5.4 MB/s eta 0:00:01\n",
" ---------------------------------- ----- 11.8/13.8 MB 5.6 MB/s eta 0:00:01\n",
" ---------------------------------------- 13.8/13.8 MB 6.1 MB/s eta 0:00:00\n",
"Installing collected packages: faiss-cpu\n",
"Successfully installed faiss-cpu-1.9.0.post1\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"# pip install faiss-cpu"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "0a95c78d-6945-4f2d-a7d1-be6c95bc791b",
"metadata": {},
"outputs": [],
"source": [
"from sentence_transformers import SentenceTransformer\n",
"import faiss\n",
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "aebab6bd-5699-4882-904f-b8e5e6e5ddb3",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "3fb129526331493a8fb80b5c86f8fba2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"modules.json: 0%| | 0.00/349 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\User\\Desktop\\Pytorch\\Lib\\site-packages\\huggingface_hub\\file_download.py:139: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\\Users\\User\\.cache\\huggingface\\hub\\models--sentence-transformers--all-MiniLM-L6-v2. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n",
"To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n",
" warnings.warn(message)\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bd955f2584e441aaa1e1228547ff105f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"config_sentence_transformers.json: 0%| | 0.00/116 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "db84b9e38b7e4e5dbef6d532343c8761",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"README.md: 0%| | 0.00/10.7k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c74024a7c16d47df84a5fa455f4875d1",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"sentence_bert_config.json: 0%| | 0.00/53.0 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "60942e39359d4ac1aa303586678dc0ed",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"config.json: 0%| | 0.00/612 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "66a913b1948e41b49d818250f374cedf",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"model.safetensors: 0%| | 0.00/90.9M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ded07d8232234013ac4ac00d5a4fbc5b",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"tokenizer_config.json: 0%| | 0.00/350 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "fb03376cf56e4eea8f11168a451fe8d9",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"vocab.txt: 0%| | 0.00/232k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "754a531ada1e422fa3a35a6ffc176323",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"tokenizer.json: 0%| | 0.00/466k [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "66552c08b6104b998acbe57680d17185",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"special_tokens_map.json: 0%| | 0.00/112 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "9412d92d9b5f422488c7e98b912abb0e",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"1_Pooling/config.json: 0%| | 0.00/190 [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"FAISS 索引已建立,向量數量: 98\n",
"Questions 和 Answers 資料已保存為 rag_data.csv\n"
]
}
],
"source": [
"# # 讀取 CSV\n",
"# file_path = \"Mental_Health_FAQ.csv\" # 使用您上傳的檔案路徑\n",
"# df = pd.read_csv(file_path)\n",
"# rag_data = df[['Questions', 'Answers']].dropna() # 只保留非空的 Questions 和 Answers\n",
"\n",
"# # 提取 Questions\n",
"# questions = rag_data['Questions'].tolist()\n",
"\n",
"# # 加載 Sentence-BERT 嵌入模型\n",
"# embed_model = SentenceTransformer('all-MiniLM-L6-v2')\n",
"# question_embeddings = embed_model.encode(questions)\n",
"\n",
"# # 建立 FAISS 索引\n",
"# dimension = question_embeddings.shape[1] # 嵌入向量的維度\n",
"# index = faiss.IndexFlatL2(dimension)\n",
"# index.add(np.array(question_embeddings))\n",
"\n",
"# # 保存索引到磁盤\n",
"# faiss.write_index(index, \"faiss_index.faiss\")\n",
"# rag_data.to_csv(\"rag_data.csv\", index=False) # 將篩選後的資料保存,供後續查詢生成使用\n",
"\n",
"# print(\"FAISS 索引已建立,向量數量:\", index.ntotal)\n",
"# print(\"Questions 和 Answers 資料已保存為 rag_data.csv\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "6da9d932-a70b-4be1-9222-1bdf28a509f4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"FAISS 索引已建立,向量數量: 50\n"
]
}
],
"source": [
"import pandas as pd\n",
"import faiss\n",
"import numpy as np\n",
"from sentence_transformers import SentenceTransformer\n",
"\n",
"# 讀取剛剛生成的 CSV\n",
"file_path = \"small_rag_data.csv\" # 使用生成的檔案路徑\n",
"rag_data = pd.read_csv(file_path)\n",
"\n",
"# 提取 Questions\n",
"questions = rag_data['Questions'].tolist()\n",
"\n",
"# 加載 Sentence-BERT 嵌入模型\n",
"embed_model = SentenceTransformer('all-MiniLM-L6-v2')\n",
"question_embeddings = embed_model.encode(questions)\n",
"\n",
"# 建立 FAISS 索引\n",
"dimension = question_embeddings.shape[1] # 嵌入向量的維度\n",
"index = faiss.IndexFlatL2(dimension)\n",
"index.add(np.array(question_embeddings))\n",
"\n",
"# 保存索引到磁盤\n",
"faiss.write_index(index, \"faiss_index.faiss\")\n",
"\n",
"print(\"FAISS 索引已建立,向量數量:\", index.ntotal)"
]
},
{
"cell_type": "code",
"execution_count": 110,
"id": "33032c47-2214-4792-a15f-a1fc41be5289",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"查詢問題: I have a bad mood?\n",
"\n",
"最符合的相關結果:\n",
"距離: 0.75\n",
"Question: What are ways to improve my mood?\n",
"Answer: Listen to uplifting music or try physical activity.\n",
"\n",
"生成模型的 Prompt Context:\n",
"Context: The retrieved context is highly relevant: 'Listen to uplifting music or try physical activity.'.\n"
]
}
],
"source": [
"# 查詢問題\n",
"query = \"I have a bad mood?\"\n",
"query_embedding = embed_model.encode([query])\n",
"\n",
"# 搜索最接近的結果\n",
"k = 1 # 只返回 1 個結果\n",
"distances, indices = index.search(np.array(query_embedding), k)\n",
"\n",
"# 設置距離閾值\n",
"threshold = 0.8 # 距離閾值\n",
"\n",
"print(\"查詢問題:\", query)\n",
"\n",
"if distances[0][0] < threshold:\n",
" # 高相關性結果\n",
" confidence = \"high\"\n",
" best_match_idx = indices[0][0]\n",
" best_match_question = rag_data.iloc[best_match_idx]['Questions']\n",
" best_match_answer = rag_data.iloc[best_match_idx]['Answers']\n",
" print(\"\\n最符合的相關結果:\")\n",
" print(f\"距離: {distances[0][0]:.2f}\")\n",
" print(\"Question:\", best_match_question)\n",
" print(\"Answer:\", best_match_answer)\n",
"elif distances[0][0] < 1.0:\n",
" # 次相關性結果\n",
" confidence = \"medium\"\n",
" best_match_idx = indices[0][0]\n",
" best_match_question = rag_data.iloc[best_match_idx]['Questions']\n",
" best_match_answer = rag_data.iloc[best_match_idx]['Answers']\n",
" print(\"\\n次相關結果:\")\n",
" print(f\"距離: {distances[0][0]:.2f}\")\n",
" print(\"Question:\", best_match_question)\n",
" print(\"Answer:\", best_match_answer)\n",
"else:\n",
" # 無關的結果\n",
" confidence = \"low\"\n",
" print(\"沒有找到符合條件的相關結果。\")\n",
"\n",
"# 根據相關性調整上下文影響力\n",
"if confidence == \"high\":\n",
" prompt_context = f\"Context: The retrieved context is highly relevant: '{best_match_answer}'.\"\n",
"elif confidence == \"medium\":\n",
" prompt_context = f\"Context: The retrieved context may be partially relevant: '{best_match_answer}'.\"\n",
"else:\n",
" prompt_context = \"\"\n",
"\n",
"print(\"\\n生成模型的 Prompt Context:\")\n",
"print(prompt_context)"
]
},
{
"cell_type": "code",
"execution_count": 111,
"id": "0a05210f-3fcf-469c-b83d-770aeba7724e",
"metadata": {},
"outputs": [],
"source": [
"# 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']"
]
},
{
"cell_type": "code",
"execution_count": 112,
"id": "10fa5182-07d5-4238-b03e-f6700b7f465b",
"metadata": {},
"outputs": [],
"source": [
"# 設定設備\n",
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
"DistilBERT_Model.to(device)\n",
"\n",
"def predict(text: str) -> Tuple[str, float]:\n",
" \"\"\"\n",
" 預測輸入文字的情感,返回預測的標籤和對應的機率。\n",
" Args:\n",
" text (str): 要進行情感分析的文本\n",
" Returns:\n",
" Tuple[str, float]: 預測的標籤和該標籤的機率\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",
" predicted_label = max(pred_labels_and_probs, key=pred_labels_and_probs.get)\n",
" predicted_probability = round(pred_labels_and_probs[predicted_label] * 100, 2) # 轉為百分比並取小數點第2位\n",
"\n",
" return predicted_label, predicted_probability"
]
},
{
"cell_type": "code",
"execution_count": 113,
"id": "0f1bf516-ea28-4206-8c5c-40da3eeb6c21",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"negative\n",
"95.78%\n"
]
}
],
"source": [
"predicted_label, predicted_probability = predict(query)\n",
"print(predicted_label)\n",
"print(f\"{predicted_probability}%\")"
]
},
{
"cell_type": "code",
"execution_count": 114,
"id": "ba671cac-96d8-4866-bfee-3a732b4af9f8",
"metadata": {},
"outputs": [],
"source": [
"if predicted_label == \"negative\":\n",
" sentiment_prompt = \"Provide a supportive and empathetic response to help the user.\"\n",
"elif predicted_label == \"positive\":\n",
" sentiment_prompt = \"Reinforce the user's positive emotion and provide encouragement or congratulations.\""
]
},
{
"cell_type": "code",
"execution_count": 115,
"id": "565db182-609a-490c-8111-7d9328c1c479",
"metadata": {},
"outputs": [],
"source": [
"# 最終 Prompt\n",
"prompt = (\n",
" f'Input: \"{query[:512]}\" '\n",
" f'Sentiment: {predicted_label.capitalize()} '\n",
" f'{prompt_context} '\n",
" f'Task: {sentiment_prompt}'\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 116,
"id": "ba6b4ed0-b39c-492c-9107-b381a8b496af",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Input: \"I have a bad mood?\" Sentiment: Negative Context: The retrieved context is highly relevant: 'Listen to uplifting music or try physical activity.'. Task: Provide a supportive and empathetic response to help the user.\n"
]
}
],
"source": [
"print(prompt)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"id": "68d5972e-beac-4342-bbdf-7535fa222ef8",
"metadata": {},
"outputs": [],
"source": [
"# from transformers import GPT2LMHeadModel, GPT2Tokenizer\n",
"\n",
"# # 加載 GPT-2 模型和 Tokenizer\n",
"# tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n",
"# model = GPT2LMHeadModel.from_pretrained(\"gpt2\")"
]
},
{
"cell_type": "code",
"execution_count": 67,
"id": "112b2783-4859-4908-87df-8c9577937b24",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# # 加載 GPT-2 模型和 Tokenizer\n",
"# tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n",
"# model = GPT2LMHeadModel.from_pretrained(\"gpt2\")\n",
"\n",
"# # 將 Prompt 傳遞給 GPT-2\n",
"# input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\n",
"\n",
"# output = model.generate(\n",
"# input_ids,\n",
"# max_length=300,\n",
"# temperature=0.7,\n",
"# do_sample=True,\n",
"# num_return_sequences=1,\n",
"# pad_token_id=tokenizer.eos_token_id\n",
"# )\n",
"\n",
"# # 解碼生成的結果\n",
"# generated_text = tokenizer.decode(output[0], skip_special_tokens=True)\n",
"\n",
"# # 去掉 Prompt 的部分,只保留生成的回應\n",
"# if prompt in generated_text:\n",
"# generated_response = generated_text[len(prompt):].strip()\n",
"# else:\n",
"# generated_response = generated_text.strip()\n",
"\n",
"# print(\"\\n生成的回應:\")\n",
"# print(generated_text)"
]
},
{
"cell_type": "code",
"execution_count": 130,
"id": "e7837f5a-f3cb-4272-ae6d-a0e2e409d12c",
"metadata": {},
"outputs": [],
"source": [
"# from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"\n",
"# # 載入模型與 Tokenizer\n",
"# model_name = \"EleutherAI/gpt-neo-1.3B\"\n",
"# tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"# model = AutoModelForCausalLM.from_pretrained(model_name)\n",
"\n",
"# # 設置 Prompt\n",
"# prompt = \"Write a funny conversation between a human and a robot.\"\n",
"# inputs = tokenizer(prompt, return_tensors=\"pt\")\n",
"\n",
"# # 生成文本\n",
"# outputs = model.generate(**inputs, max_length=150, temperature=0.8)\n",
"# response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
"\n",
"# print(\"Generated Text:\")\n",
"# print(response)"
]
},
{
"cell_type": "code",
"execution_count": 117,
"id": "131ea442-e8ce-45fc-97e2-99ed4295a4d4",
"metadata": {},
"outputs": [],
"source": [
"# Input: \"I have a bad mood?\" Sentiment: Negative Context: The retrieved context is highly relevant: 'Listen to uplifting music or try physical activity.'. Task: Provide a supportive and empathetic response to help the user."
]
},
{
"cell_type": "code",
"execution_count": 140,
"id": "494a40e8-cffb-4c8b-ae1b-05cd97e118b4",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Generated Text:\n",
"I have a bad mood. I'm not going to be able do anything about it.\"\n",
"\"You're right, but you don't want me doing this,\" said the man who had been sitting next us in his office with an open book on him and another woman's body parts that he'd never seen before: \"It was just so much fun for her when she came out of my room last night!\" He looked at our two men as if they were trying desperately hard; we could see their eyes widen from shock or disbelief because there wasn' nothing else like them around here except one person standing behind each other holding up some kind-of paper bag full probably filled entirely by women (and maybe even children) whose bodies might look different than ours now—a small piece which would make any child blush more clearly after seeing what happened between these three people! And then suddenly all hell broke loose again…\n",
"\n",
" <!--iframe--> \n"
]
}
],
"source": [
"# from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"\n",
"# # 載入 GPT-2 模型\n",
"# model_name = \"gpt2\"\n",
"# tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"# model = AutoModelForCausalLM.from_pretrained(model_name)\n",
"\n",
"# # 構造 Prompt 並加入 \\nRobot\n",
"# prompt = (\n",
"# 'Input: \"I have a bad mood\"\\n'\n",
"# \"Sentiment: Negative\\n\"\n",
"# \"Context: The retrieved context is highly relevant: 'Listen to uplifting music or try physical activity.'.\\n\"\n",
"# \"Task: Respond as a supportive and empathetic assistant to help the user feel better.\\n\"\n",
"# \"Robot:\"\n",
"# )\n",
"\n",
"# # 將 Prompt 編碼為張量\n",
"# inputs = tokenizer(\"I have a bad mood\", return_tensors=\"pt\")\n",
"\n",
"# # 生成文本\n",
"# outputs = model.generate(\n",
"# **inputs, \n",
"# max_length=200,# 調整生成文本的長度\n",
"# temperature=0.8, \n",
"# repetition_penalty=1.2, \n",
"# top_k=50, \n",
"# top_p=0.9\n",
"# )\n",
"\n",
"# # 解碼輸出\n",
"# response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
"\n",
"# # 輸出結果\n",
"# print(\"Generated Text:\")\n",
"# print(response)\n"
]
},
{
"cell_type": "code",
"execution_count": 155,
"id": "e69c7eff-e6a2-45fc-b800-3661d75a69ca",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Answer: Die Garantie dauert ein Jahr.\n"
]
}
],
"source": [
"# from transformers import AutoModelForSeq2SeqLM, AutoTokenizer\n",
"# from sentence_transformers import SentenceTransformer, util\n",
"\n",
"# # 初始化檢索模型\n",
"# retriever = SentenceTransformer('msmarco-MiniLM-L-6-v3')\n",
"# corpus = [\"The warranty lasts for one year.\", \"The product can be replaced within 30 days.\"]\n",
"# corpus_embeddings = retriever.encode(corpus, convert_to_tensor=True)\n",
"\n",
"# # 查詢問題\n",
"# query = \"What is the warranty policy?\"\n",
"# query_embedding = retriever.encode(query, convert_to_tensor=True)\n",
"# scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)\n",
"\n",
"# # 找到最相關的文檔\n",
"# relevant_doc = corpus[scores.argmax()]\n",
"\n",
"# # 使用生成模型生成答案\n",
"# model_name = \"t5-small\"\n",
"# tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"# model = AutoModelForSeq2SeqLM.from_pretrained(model_name)\n",
"\n",
"# prompt = f\"Summarize the warranty policy in English: {relevant_doc}\"\n",
"# inputs = tokenizer(prompt, return_tensors=\"pt\")\n",
"# outputs = model.generate(**inputs)\n",
"# response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
"\n",
"# print(\"Answer:\", response)\n",
"\n",
"# # 載入翻譯模型\n",
"# translator_tokenizer = AutoTokenizer.from_pretrained(\"Helsinki-NLP/opus-mt-de-en\")\n",
"# translator_model = AutoModelForSeq2SeqLM.from_pretrained(\"Helsinki-NLP/opus-mt-de-en\")\n",
"\n",
"# # 翻譯生成的德文到英文\n",
"# translation_inputs = translator_tokenizer(response, return_tensors=\"pt\")\n",
"# translation_outputs = translator_model.generate(**translation_inputs)\n",
"# english_response = translator_tokenizer.decode(translation_outputs[0], skip_special_tokens=True)\n",
"\n",
"# print(\"Translated Answer:\", english_response)"
]
},
{
"cell_type": "code",
"execution_count": 149,
"id": "ed7b9b7c-9243-4ac0-be8d-4dd0b7edbc28",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"SentencePiece is installed and ready to use.\n"
]
}
],
"source": [
"import sentencepiece\n",
"print(\"SentencePiece is installed and ready to use.\")"
]
},
{
"cell_type": "code",
"execution_count": 156,
"id": "adfda46d-e02a-4460-bf27-f42ea0c525f6",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.\n",
"Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Generated Answer: The user asked: 'What is the warranty policy?'\n",
"The retrieved document is: 'The warranty lasts for one year.'\n",
"Provide a helpful and concise answer. The customer has been provided with an excellent product, which they are happy to accept as their own (or at least in good faith).\n"
]
}
],
"source": [
"from transformers import GPT2LMHeadModel, GPT2Tokenizer\n",
"from sentence_transformers import SentenceTransformer, util\n",
"\n",
"# 初始化檢索模型\n",
"retriever = SentenceTransformer('msmarco-MiniLM-L-6-v3')\n",
"corpus = [\"The warranty lasts for one year.\", \"The product can be replaced within 30 days.\"]\n",
"corpus_embeddings = retriever.encode(corpus, convert_to_tensor=True)\n",
"\n",
"# 查詢問題\n",
"query = \"What is the warranty policy?\"\n",
"query_embedding = retriever.encode(query, convert_to_tensor=True)\n",
"scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)\n",
"\n",
"# 找到最相關的文檔\n",
"relevant_doc = corpus[scores.argmax()]\n",
"\n",
"# 載入本地 GPT-2 模型和分詞器\n",
"model_name = \"gpt2\"\n",
"tokenizer = GPT2Tokenizer.from_pretrained(model_name)\n",
"model = GPT2LMHeadModel.from_pretrained(model_name)\n",
"\n",
"# 構建輸入 Prompt\n",
"prompt = f\"The user asked: '{query}'\\nThe retrieved document is: '{relevant_doc}'\\nProvide a helpful and concise answer.\"\n",
"\n",
"# 將 Prompt 編碼為張量\n",
"inputs = tokenizer.encode(prompt, return_tensors=\"pt\")\n",
"\n",
"# 使用 GPT-2 生成答案\n",
"outputs = model.generate(\n",
" inputs,\n",
" max_length=100, # 限制生成長度\n",
" temperature=0.7, # 控制隨機性\n",
" top_k=50, # 限制前 K 個 token\n",
" top_p=0.9, # 使用核採樣\n",
" repetition_penalty=1.2 # 懲罰重複\n",
")\n",
"\n",
"# 解碼輸出\n",
"generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
"\n",
"# 提取答案部分\n",
"print(\"Generated Answer:\", generated_text)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9883d71d-830d-408d-ae94-98138f7430d7",
"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
}
|