File size: 40,003 Bytes
73b7597
1
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"gpuType":"T4","authorship_tag":"ABX9TyNlkM6gdJ9UQhoEKeLwmvkN"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU","widgets":{"application/vnd.jupyter.widget-state+json":{"211f09f515934e2aad2520b22c88a2e7":{"model_module":"@jupyter-widgets/controls","model_name":"HBoxModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_d3c8c25ce2614015ab2a245c64fabdc4","IPY_MODEL_c4f1a28569344cf392a8d80b303ab565","IPY_MODEL_3818815a59bc4939b5018f6cecbfcd9c"],"layout":"IPY_MODEL_6463e7e247c04344979beb4c35f4f7b8"}},"d3c8c25ce2614015ab2a245c64fabdc4":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_f1892916ff384e87af67b10371446c31","placeholder":"​","style":"IPY_MODEL_e1b60130c47f4337beabed500b712d03","value":"Map: 100%"}},"c4f1a28569344cf392a8d80b303ab565":{"model_module":"@jupyter-widgets/controls","model_name":"FloatProgressModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"ProgressView","bar_style":"success","description":"","description_tooltip":null,"layout":"IPY_MODEL_363c3ebb3fdc4cc7a6ac98d999abc248","max":8,"min":0,"orientation":"horizontal","style":"IPY_MODEL_0c0d1f9564f84f86847d172aa174d92e","value":8}},"3818815a59bc4939b5018f6cecbfcd9c":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_76e869fb06fc4244bcf5e249740d786b","placeholder":"","style":"IPY_MODEL_067dd02f058b46cba719e19a3e1af91b","value":"8/8 [00:00&lt;00:00, 303.78 examples/s]"}},"6463e7e247c04344979beb4c35f4f7b8":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"f1892916ff384e87af67b10371446c31":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"e1b60130c47f4337beabed500b712d03":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"363c3ebb3fdc4cc7a6ac98d999abc248":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"0c0d1f9564f84f86847d172aa174d92e":{"model_module":"@jupyter-widgets/controls","model_name":"ProgressStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"76e869fb06fc4244bcf5e249740d786b":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"067dd02f058b46cba719e19a3e1af91b":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"2693abb6f7af4b62ab69a70330a365a2":{"model_module":"@jupyter-widgets/controls","model_name":"HBoxModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_271fc1d762c34c269ba52e2dce05ac6d","IPY_MODEL_63d86ec5b54940d098215fa76216aa13","IPY_MODEL_c4bcb7f2067a44e98f41cd59dc23fc6b"],"layout":"IPY_MODEL_b7f13a810dd24a61805701b25a8bffba"}},"271fc1d762c34c269ba52e2dce05ac6d":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_30f0c31d40be43099baa67d869fe7080","placeholder":"","style":"IPY_MODEL_70e5760378424fee8febc1ac657c22e9","value":"Map: 100%"}},"63d86ec5b54940d098215fa76216aa13":{"model_module":"@jupyter-widgets/controls","model_name":"FloatProgressModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"ProgressView","bar_style":"success","description":"","description_tooltip":null,"layout":"IPY_MODEL_0a65dc166d7649d9a67e0b029da26402","max":2,"min":0,"orientation":"horizontal","style":"IPY_MODEL_fb330bb950f54820972a4de7d0d0d3bc","value":2}},"c4bcb7f2067a44e98f41cd59dc23fc6b":{"model_module":"@jupyter-widgets/controls","model_name":"HTMLModel","model_module_version":"1.5.0","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"1.5.0","_view_name":"HTMLView","description":"","description_tooltip":null,"layout":"IPY_MODEL_725317117c2042f2b228cd3ba7d5ba34","placeholder":"​","style":"IPY_MODEL_89ed6063d28546258a7ff2b151fb4453","value":" 2/2 [00:00&lt;00:00, 60.27 examples/s]"}},"b7f13a810dd24a61805701b25a8bffba":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"30f0c31d40be43099baa67d869fe7080":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"70e5760378424fee8febc1ac657c22e9":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}},"0a65dc166d7649d9a67e0b029da26402":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"fb330bb950f54820972a4de7d0d0d3bc":{"model_module":"@jupyter-widgets/controls","model_name":"ProgressStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"725317117c2042f2b228cd3ba7d5ba34":{"model_module":"@jupyter-widgets/base","model_name":"LayoutModel","model_module_version":"1.2.0","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"1.2.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"overflow_x":null,"overflow_y":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"89ed6063d28546258a7ff2b151fb4453":{"model_module":"@jupyter-widgets/controls","model_name":"DescriptionStyleModel","model_module_version":"1.5.0","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"1.5.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"1.2.0","_view_name":"StyleView","description_width":""}}}}},"cells":[{"cell_type":"code","source":["import pandas as pd\n","\n","data = {\n","    \"text\": [\n","        \"I love this movie!\",\n","        \"This is the best phone I've ever used.\",\n","        \"The food was amazing and the service was great.\",\n","        \"This product is okay, not the best though.\",\n","        \"It's fine, but I expected more.\",\n","        \"The movie was boring and too long.\",\n","        \"I hate this restaurant, terrible experience.\",\n","        \"The laptop stopped working after one week.\",\n","        \"Nothing special about this item.\",\n","        \"Absolutely fantastic! Highly recommend.\"\n","    ],\n","    \"label\": [\n","        \"positive\",\n","        \"positive\",\n","        \"positive\",\n","        \"neutral\",\n","        \"neutral\",\n","        \"negative\",\n","        \"negative\",\n","        \"negative\",\n","        \"neutral\",\n","        \"positive\"\n","    ]\n","}\n","\n","df = pd.DataFrame(data)\n","df.to_csv(\"/content/data.csv\", index=False)\n","print(\"✅ Đã tạo file /content/data.csv\")\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vl2HA1Zw4h-Z","executionInfo":{"status":"ok","timestamp":1760800437019,"user_tz":-420,"elapsed":481,"user":{"displayName":"Lâm Đức Cương","userId":"02362263444637620675"}},"outputId":"a5485f4c-c252-4c15-803b-8f3ff6b5435f"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["✅ Đã tạo file /content/data.csv\n"]}]},{"cell_type":"code","execution_count":3,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":136,"referenced_widgets":["211f09f515934e2aad2520b22c88a2e7","d3c8c25ce2614015ab2a245c64fabdc4","c4f1a28569344cf392a8d80b303ab565","3818815a59bc4939b5018f6cecbfcd9c","6463e7e247c04344979beb4c35f4f7b8","f1892916ff384e87af67b10371446c31","e1b60130c47f4337beabed500b712d03","363c3ebb3fdc4cc7a6ac98d999abc248","0c0d1f9564f84f86847d172aa174d92e","76e869fb06fc4244bcf5e249740d786b","067dd02f058b46cba719e19a3e1af91b","2693abb6f7af4b62ab69a70330a365a2","271fc1d762c34c269ba52e2dce05ac6d","63d86ec5b54940d098215fa76216aa13","c4bcb7f2067a44e98f41cd59dc23fc6b","b7f13a810dd24a61805701b25a8bffba","30f0c31d40be43099baa67d869fe7080","70e5760378424fee8febc1ac657c22e9","0a65dc166d7649d9a67e0b029da26402","fb330bb950f54820972a4de7d0d0d3bc","725317117c2042f2b228cd3ba7d5ba34","89ed6063d28546258a7ff2b151fb4453"]},"id":"O4bzJiuq4AHZ","executionInfo":{"status":"ok","timestamp":1760800676728,"user_tz":-420,"elapsed":8954,"user":{"displayName":"Lâm Đức Cương","userId":"02362263444637620675"}},"outputId":"edbb6822-394f-4498-8db5-35f21e53dbd4"},"outputs":[{"output_type":"display_data","data":{"text/plain":["Map:   0%|          | 0/8 [00:00<?, ? examples/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"211f09f515934e2aad2520b22c88a2e7"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["Map:   0%|          | 0/2 [00:00<?, ? examples/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"2693abb6f7af4b62ab69a70330a365a2"}},"metadata":{}},{"output_type":"stream","name":"stderr","text":["Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['classifier.bias', '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":["# ==============================================\n","# 1️⃣ CÀI ĐẶT & IMPORT\n","# ==============================================\n","!pip install transformers datasets torch scikit-learn -q\n","\n","from datasets import load_dataset, Dataset\n","from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments\n","from sklearn.model_selection import train_test_split\n","import pandas as pd\n","import numpy as np\n","import torch\n","\n","# ==============================================\n","# 2️⃣ NẠP & CHUẨN HÓA DỮ LIỆU\n","# ==============================================\n","# Giả sử bạn có file CSV: data.csv gồm 2 cột text, label\n","data = pd.read_csv(\"/content/data.csv\")\n","\n","# Chuẩn hóa nhãn (map từ string -> số)\n","label2id = {label: idx for idx, label in enumerate(data['label'].unique())}\n","id2label = {v: k for k, v in label2id.items()}\n","data['label'] = data['label'].map(label2id)\n","\n","# Chia train/test\n","train_df, test_df = train_test_split(data, test_size=0.2, random_state=42)\n","train_dataset = Dataset.from_pandas(train_df)\n","test_dataset = Dataset.from_pandas(test_df)\n","\n","# ==============================================\n","# 3️⃣ TOKENIZATION\n","# ==============================================\n","model_name = \"bert-base-uncased\"  # có thể đổi sang model tiếng Việt: \"vinai/phobert-base\"\n","tokenizer = AutoTokenizer.from_pretrained(model_name)\n","\n","def tokenize_fn(batch):\n","    return tokenizer(batch[\"text\"], padding=\"max_length\", truncation=True, max_length=128)\n","\n","train_dataset = train_dataset.map(tokenize_fn, batched=True)\n","test_dataset = test_dataset.map(tokenize_fn, batched=True)\n","\n","# Xóa cột không cần\n","train_dataset = train_dataset.remove_columns([\"text\", \"__index_level_0__\"])\n","test_dataset = test_dataset.remove_columns([\"text\", \"__index_level_0__\"])\n","\n","train_dataset.set_format(\"torch\")\n","test_dataset.set_format(\"torch\")\n","\n","# ==============================================\n","# 4️⃣ CHỌN MÔ HÌNH\n","# ==============================================\n","model = AutoModelForSequenceClassification.from_pretrained(\n","    model_name,\n","    num_labels=len(label2id),\n","    id2label=id2label,\n","    label2id=label2id\n",")\n","\n"]},{"cell_type":"code","source":["# ==============================================\n","import os\n","os.environ[\"WANDB_DISABLED\"] = \"true\"\n","\n","# 5️⃣ HUẤN LUYỆN\n","# ==============================================\n","training_args = TrainingArguments(\n","    output_dir=\"./results\",\n","    learning_rate=2e-5,\n","    per_device_train_batch_size=8,\n","    per_device_eval_batch_size=8,\n","    num_train_epochs=2,\n","    logging_dir=\"./logs\",\n","    logging_steps=10,\n",")\n","\n","\n","\n","from sklearn.metrics import accuracy_score, precision_recall_fscore_support\n","\n","def compute_metrics(eval_pred):\n","    logits, labels = eval_pred\n","    preds = np.argmax(logits, axis=-1)\n","    precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')\n","    acc = accuracy_score(labels, preds)\n","    return {\"accuracy\": acc, \"precision\": precision, \"recall\": recall, \"f1\": f1}\n","\n","trainer = Trainer(\n","    model=model,\n","    args=training_args,\n","    train_dataset=train_dataset,\n","    eval_dataset=test_dataset,\n","    tokenizer=tokenizer,\n","    compute_metrics=compute_metrics\n",")\n","\n","trainer.train()\n","\n","# ==============================================\n","# 6️⃣ ĐÁNH GIÁ\n","# ==============================================\n","metrics = trainer.evaluate()\n","print(metrics)\n","\n","# ==============================================\n","# 7️⃣ TRIỂN KHAI DỰ ĐOÁN\n","# ==============================================\n","def predict(text):\n","    inputs = tokenizer(text, return_tensors=\"pt\", truncation=True, padding=True, max_length=128)\n","    with torch.no_grad():\n","        outputs = model(**inputs)\n","        probs = torch.nn.functional.softmax(outputs.logits, dim=-1)\n","        pred = torch.argmax(probs, dim=-1).item()\n","    return id2label[pred], probs[0][pred].item()\n","\n","print(predict(\"I really love this product!\"))\n","print(predict(\"This is the worst thing ever.\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":323},"id":"Sfx1yYdc5d0P","executionInfo":{"status":"ok","timestamp":1760800889168,"user_tz":-420,"elapsed":45695,"user":{"displayName":"Lâm Đức Cương","userId":"02362263444637620675"}},"outputId":"a58a2e54-2671-49ad-8933-650fffa7a9b7"},"execution_count":6,"outputs":[{"output_type":"stream","name":"stderr","text":["Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the --report_to flag to control the integrations used for logging result (for instance --report_to none).\n","/tmp/ipython-input-824382958.py:28: FutureWarning: `tokenizer` is deprecated and will be removed in version 5.0.0 for `Trainer.__init__`. Use `processing_class` instead.\n","  trainer = Trainer(\n","/usr/local/lib/python3.12/dist-packages/torch/utils/data/dataloader.py:666: UserWarning: 'pin_memory' argument is set as true but no accelerator is found, then device pinned memory won't be used.\n","  warnings.warn(warn_msg)\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.HTML object>"],"text/html":["\n","    <div>\n","      \n","      <progress value='2' max='2' style='width:300px; height:20px; vertical-align: middle;'></progress>\n","      [2/2 00:19, Epoch 2/2]\n","    </div>\n","    <table border=\"1\" class=\"dataframe\">\n","  <thead>\n"," <tr style=\"text-align: left;\">\n","      <th>Step</th>\n","      <th>Training Loss</th>\n","    </tr>\n","  </thead>\n","  <tbody>\n","  </tbody>\n","</table><p>"]},"metadata":{}},{"output_type":"stream","name":"stderr","text":["/usr/local/lib/python3.12/dist-packages/torch/utils/data/dataloader.py:666: UserWarning: 'pin_memory' argument is set as true but no accelerator is found, then device pinned memory won't be used.\n","  warnings.warn(warn_msg)\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.HTML object>"],"text/html":["\n","    <div>\n","      \n","      <progress value='1' max='1' style='width:300px; height:20px; vertical-align: middle;'></progress>\n","      [1/1 : < :]\n","    </div>\n","    "]},"metadata":{}},{"output_type":"stream","name":"stderr","text":["/usr/local/lib/python3.12/dist-packages/sklearn/metrics/_classification.py:1565: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n","  _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n"]},{"output_type":"stream","name":"stdout","text":["{'eval_loss': 1.0297198295593262, 'eval_accuracy': 0.5, 'eval_precision': 0.25, 'eval_recall': 0.5, 'eval_f1': 0.3333333333333333, 'eval_runtime': 1.4353, 'eval_samples_per_second': 1.393, 'eval_steps_per_second': 0.697, 'epoch': 2.0}\n","('positive', 0.44261372089385986)\n","('positive', 0.41787630319595337)\n"]}]},{"cell_type":"markdown","source":["#Model HG"],"metadata":{"id":"5aXdD6vS6s2-"}},{"cell_type":"code","source":["# ==========================================\n","# 🧩 CÀI ĐẶT THƯ VIỆN\n","# ==========================================\n","!pip install -q huggingface_hub\n","\n","# ==========================================\n","# ⚙️ IMPORT CÁC MODULE CẦN THIẾT\n","# ==========================================\n","from huggingface_hub import snapshot_download\n","\n","# ==========================================\n","# 🧠 NHẬP TÊN MODEL MUỐN TẢI\n","# ==========================================\n","# 👉 Ví dụ: Stable Diffusion XL base 1.0\n","model_id = \"stabilityai/stable-diffusion-xl-base-1.0\"\n","\n","# Nếu bạn muốn thay model khác, chỉ cần đổi model_id\n","# Ví dụ:\n","# model_id = \"bert-base-uncased\"\n","# model_id = \"facebook/bart-large-cnn\"\n","# model_id = \"openai/whisper-small\"\n","\n","# ==========================================\n","# 📦 TẢI MODEL VỀ MÁY (KHÔNG CẦN ĐĂNG NHẬP)\n","# ==========================================\n","model_path = snapshot_download(\n","    repo_id=model_id,\n","    local_dir=\"models/\" + model_id.split(\"/\")[-1],  # lưu vào thư mục models/\n","    revision=\"main\",  # nhánh chính\n","    token=None        # KHÔNG cần token\n",")\n","\n","# ==========================================\n","# ✅ IN RA ĐƯỜNG DẪN MODEL SAU KHI TẢI\n","# ==========================================\n","print(f\"✅ Model '{model_id}' đã được tải về tại: {model_path}\")\n"],"metadata":{"id":"yIlc04Ei7_1g"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["model_id = \"bert-base-uncased\"\n","snapshot_download(repo_id=model_id, local_dir=f\"/kaggle/working/{model_id.split('/')[-1]}\")\n","tokenizer = AutoTokenizer.from_pretrained(f\"/kaggle/working/{model_id.split('/')[-1]}\")\n","model = AutoModel.from_pretrained(f\"/kaggle/working/{model_id.split('/')[-1]}\")\n","\n","inputs = tokenizer(\"This is a test sentence.\", return_tensors=\"pt\")\n","outputs = model(**inputs)\n","print(outputs.last_hidden_state.shape)"],"metadata":{"id":"tV-2VvEP8EiF"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Kaggle"],"metadata":{"id":"GhT3ChdX8jqx"}},{"cell_type":"code","source":["# ============================================================\n","# ⚙️ 1️⃣ CÀI ĐẶT THƯ VIỆN CẦN THIẾT\n","# ============================================================\n","# diffusers: dùng cho model Stable Diffusion, T2I, SDXL,...\n","# transformers: cho NLP, vision-language models\n","# accelerate + safetensors: giúp tăng tốc & load file an toàn\n","# huggingface_hub: thao tác tải & quản lý model từ Hugging Face\n","# ============================================================\n","!pip install -U diffusers transformers accelerate safetensors huggingface_hub torch torchvision xformers --quiet\n","\n","\n","# ============================================================\n","# 🔑 2️⃣ ĐĂNG NHẬP HUGGING FACE\n","# ============================================================\n","# - Cần token để tải model private hoặc có license.\n","# - Lấy token tại: https://huggingface.co/settings/tokens\n","# ============================================================\n","from huggingface_hub import login\n","\n","login()  # 👉 Chạy lệnh này rồi dán token Hugging Face vào ô nhập\n","\n","\n","# ============================================================\n","# 🧠 3️⃣ NHẬP TÊN MODEL MUỐN TẢI\n","# ============================================================\n","# - Bạn có thể thay \"model_id\" bằng bất kỳ model nào:\n","#   📚 NLP: \"bert-base-uncased\", \"vinai/phobert-base-v2\"\n","#   🖼️ T2I: \"stabilityai/stable-diffusion-xl-base-1.0\"\n","#   🎧 Audio: \"facebook/wav2vec2-base-960h\"\n","# ============================================================\n","\n","model_id = \"stabilityai/stable-diffusion-xl-base-1.0\"  # 👉 đổi tên model ở đây\n","\n","\n","# ============================================================\n","# 💾 4️⃣ TẢI MODEL VỀ THƯ MỤC LÀM VIỆC (VD: /kaggle/working/)\n","# ============================================================\n","# - Model sẽ được lưu vào /kaggle/working/<model_id> để dùng lại.\n","# - Nếu muốn lưu trên Google Drive hoặc Dataset riêng thì chỉ cần đổi đường dẫn.\n","# ============================================================\n","\n","from huggingface_hub import snapshot_download\n","\n","# Tải toàn bộ model (bao gồm weights, config, tokenizer,...)\n","local_dir = f\"/kaggle/working/{model_id.split('/')[-1]}\"\n","snapshot_download(repo_id=model_id, local_dir=local_dir, resume_download=True)\n","\n","print(f\"✅ Model đã tải về thư mục: {local_dir}\")\n","\n","\n","# ============================================================\n","# 🧪 5️⃣ LOAD MODEL ĐỂ DÙNG (THEO LOẠI)\n","# ============================================================\n","\n","from transformers import AutoModel, AutoTokenizer\n","from diffusers import StableDiffusionXLPipeline\n","import torch\n","\n","# 👉 Kiểm tra loại model để load đúng lớp\n","if \"diffusion\" in model_id.lower() or \"sdxl\" in model_id.lower():\n","    print(\"🖼️ Đây là model diffusion, dùng pipeline SDXL...\")\n","    pipe = StableDiffusionXLPipeline.from_pretrained(\n","        local_dir,\n","        torch_dtype=torch.float16,\n","        use_safetensors=True,\n","        variant=\"fp16\"\n","    ).to(\"cuda\")\n","\n","    prompt = \"a cute cat wearing glasses, watercolor style\"\n","    image = pipe(prompt).images[0]\n","    image.save(\"/kaggle/working/sample.png\")\n","    print(\"✅ Đã tạo ảnh mẫu: /kaggle/working/sample.png\")\n","\n","else:\n","    print(\"📚 Đây là model NLP/Transformer thông thường...\")\n","    tokenizer = AutoTokenizer.from_pretrained(local_dir)\n","    model = AutoModel.from_pretrained(local_dir)\n","\n","    # Ví dụ: mã hóa câu\n","    inputs = tokenizer(\"Hello Hugging Face!\", return_tensors=\"pt\")\n","    with torch.no_grad():\n","        outputs = model(**inputs)\n","    print(\"✅ Đã load thành công model NLP, vector đầu ra:\", outputs.last_hidden_state.shape)\n","\n","\n","# ============================================================\n","# 🧰 6️⃣ (TUỲ CHỌN) LƯU MODEL LÊN DRIVE HOẶC DATASET\n","# ============================================================\n","# Nếu bạn muốn lưu lại model để dùng sau:\n","# ============================================================\n","# !cp -r /kaggle/working/<model_folder> /kaggle/drive/MyDrive/"],"metadata":{"id":"AkH3RfwT8Iz_"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#Exam"],"metadata":{"id":"EoK3AkOW8ejP"}},{"cell_type":"code","source":["!pip install -U diffusers transformers accelerate safetensors torch torchvision xformers --quiet"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"bkqMGOKg6pkm","outputId":"0e3097f0-dee2-451a-b50e-9dc007c52ab3"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[?25l     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/4.1 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/4.1 MB\u001b[0m \u001b[31m46.0 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m4.1/4.1 MB\u001b[0m \u001b[31m59.6 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.1/4.1 MB\u001b[0m \u001b[31m37.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m899.7/899.7 MB\u001b[0m \u001b[31m1.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m594.3/594.3 MB\u001b[0m \u001b[31m2.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m58.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m88.0/88.0 MB\u001b[0m \u001b[31m9.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m954.8/954.8 kB\u001b[0m \u001b[31m24.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m193.1/193.1 MB\u001b[0m \u001b[31m6.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m24.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.6/63.6 MB\u001b[0m \u001b[31m12.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m267.5/267.5 MB\u001b[0m \u001b[31m4.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m288.2/288.2 MB\u001b[0m \u001b[31m2.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m322.3/322.3 MB\u001b[0m \u001b[31m4.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m39.3/39.3 MB\u001b[0m \u001b[31m23.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m124.7/124.7 MB\u001b[0m \u001b[31m7.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m90.0/90.0 kB\u001b[0m \u001b[31m7.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m170.5/170.5 MB\u001b[0m \u001b[31m6.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m8.1/8.1 MB\u001b[0m \u001b[31m140.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h  Building wheel for xformers (setup.py) ... \u001b[?25l\u001b[?25hcanceled\u001b[31mERROR: Operation cancelled by user\u001b[0m\u001b[31m\n","\u001b[0m^C\n"]}]},{"cell_type":"code","source":["from diffusers import StableDiffusionXLPipeline\n","import torch\n","\n","model_id = \"stabilityai/stable-diffusion-xl-base-1.0\"\n","\n","pipe = StableDiffusionXLPipeline.from_pretrained(\n","    model_id,\n","    torch_dtype=torch.float16,\n","    use_safetensors=True,\n","    variant=\"fp16\"\n",").to(\"cuda\")\n"],"metadata":{"id":"wF9ldRHK6xrF"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["prompt = \"A cute cat sitting on a pile of books, watercolor style\"\n","image = pipe(prompt).images[0]\n","image.save(\"sample.png\")\n","\n","image\n"],"metadata":{"id":"6ncGcuHM60dn"},"execution_count":null,"outputs":[]}]}