{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5bba7abb", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:15.252393Z", "iopub.status.busy": "2025-09-29T03:52:15.252092Z", "iopub.status.idle": "2025-09-29T03:52:17.151894Z", "shell.execute_reply": "2025-09-29T03:52:17.150967Z" }, "papermill": { "duration": 1.90738, "end_time": "2025-09-29T03:52:17.153646", "exception": false, "start_time": "2025-09-29T03:52:15.246266", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt \n", "import seaborn as sns\n", "import os, re, warnings\n", "\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "code", "execution_count": 2, "id": "9f73e599", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:17.163059Z", "iopub.status.busy": "2025-09-29T03:52:17.162673Z", "iopub.status.idle": "2025-09-29T03:52:17.251586Z", "shell.execute_reply": "2025-09-29T03:52:17.250752Z" }, "papermill": { "duration": 0.094622, "end_time": "2025-09-29T03:52:17.252914", "exception": false, "start_time": "2025-09-29T03:52:17.158292", "status": "completed" }, "tags": [] }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Id_NumberPatient QuestionDistorted partDominant DistortionSecondary Distortion (Optional)
04500Hello, I have a beautiful,smart,outgoing and a...The voice are always fimilar (someone she know...PersonalizationNaN
14501Since I was about 16 years old I’ve had these ...I feel trapped inside my disgusting self and l...LabelingEmotional Reasoning
24502So I’ve been dating on and off this guy for a...NaNNo DistortionNaN
34503My parents got divorced in 2004. My mother has...NaNNo DistortionNaN
44504I don’t really know how to explain the situati...I refused to go because I didn’t know if it wa...Fortune-tellingEmotional Reasoning
\n", "
" ], "text/plain": [ " Id_Number Patient Question \\\n", "0 4500 Hello, I have a beautiful,smart,outgoing and a... \n", "1 4501 Since I was about 16 years old I’ve had these ... \n", "2 4502 So I’ve been dating on and off this guy for a... \n", "3 4503 My parents got divorced in 2004. My mother has... \n", "4 4504 I don’t really know how to explain the situati... \n", "\n", " Distorted part Dominant Distortion \\\n", "0 The voice are always fimilar (someone she know... Personalization \n", "1 I feel trapped inside my disgusting self and l... Labeling \n", "2 NaN No Distortion \n", "3 NaN No Distortion \n", "4 I refused to go because I didn’t know if it wa... Fortune-telling \n", "\n", " Secondary Distortion (Optional) \n", "0 NaN \n", "1 Emotional Reasoning \n", "2 NaN \n", "3 NaN \n", "4 Emotional Reasoning " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv('/kaggle/input/cognitive-distortion-detetction-dataset/Annotated_data.csv')\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 3, "id": "4bdec7e0", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:17.262119Z", "iopub.status.busy": "2025-09-29T03:52:17.261822Z", "iopub.status.idle": "2025-09-29T03:52:17.264808Z", "shell.execute_reply": "2025-09-29T03:52:17.264189Z" }, "papermill": { "duration": 0.00864, "end_time": "2025-09-29T03:52:17.265921", "exception": false, "start_time": "2025-09-29T03:52:17.257281", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# df=df.dropna()" ] }, { "cell_type": "code", "execution_count": 4, "id": "49316246", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:17.274826Z", "iopub.status.busy": "2025-09-29T03:52:17.274598Z", "iopub.status.idle": "2025-09-29T03:52:17.277625Z", "shell.execute_reply": "2025-09-29T03:52:17.276818Z" }, "papermill": { "duration": 0.009205, "end_time": "2025-09-29T03:52:17.279273", "exception": false, "start_time": "2025-09-29T03:52:17.270068", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# lengths = df['Distorted part'].apply(lambda x: len(x.split()))\n", "\n", "# plt.figure(figsize=(10, 5))\n", "# plt.hist(lengths, bins=30, edgecolor='k', alpha=0.7)\n", "# plt.title('Distribution of sentence lengths')\n", "# plt.xlabel('Sentence Length')\n", "# plt.ylabel('Number of Sentences')\n", "# plt.grid(True, which='both', linestyle='--', linewidth=0.5)\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": 5, "id": "872f92ef", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:17.287846Z", "iopub.status.busy": "2025-09-29T03:52:17.287596Z", "iopub.status.idle": "2025-09-29T03:52:17.404691Z", "shell.execute_reply": "2025-09-29T03:52:17.403977Z" }, "papermill": { "duration": 0.123138, "end_time": "2025-09-29T03:52:17.406334", "exception": false, "start_time": "2025-09-29T03:52:17.283196", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "from sklearn.preprocessing import LabelEncoder\n", "# Tạo LabelEncoder\n", "encoder = LabelEncoder()\n", "\n", "# Mã hóa cột 'Dominant Distortion', 'No Distortion' thành 0, các loại còn lại thành 1\n", "df['Dominant Distortion Encoded'] = encoder.fit_transform(df['Dominant Distortion'].apply(lambda x: 0 if x == 'No Distortion' else 1))" ] }, { "cell_type": "code", "execution_count": 6, "id": "d0c55440", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:17.415784Z", "iopub.status.busy": "2025-09-29T03:52:17.415525Z", "iopub.status.idle": "2025-09-29T03:52:18.256425Z", "shell.execute_reply": "2025-09-29T03:52:18.255403Z" }, "papermill": { "duration": 0.84688, "end_time": "2025-09-29T03:52:18.257776", "exception": false, "start_time": "2025-09-29T03:52:17.410896", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[nltk_data] Downloading package punkt to /usr/share/nltk_data...\n", "[nltk_data] Package punkt is already up-to-date!\n", "[nltk_data] Downloading package stopwords to /usr/share/nltk_data...\n", "[nltk_data] Unzipping corpora/stopwords.zip.\n", "[nltk_data] Downloading package wordnet to /usr/share/nltk_data...\n", "[nltk_data] Package wordnet is already up-to-date!\n", "i luv programmng u r gr8 i cant believe its 123 times better\n" ] } ], "source": [ "# !pip install spellchecker\n", "import re\n", "import string\n", "import nltk\n", "from nltk.tokenize import word_tokenize\n", "from nltk.corpus import stopwords\n", "from nltk.stem import PorterStemmer, WordNetLemmatizer\n", "# from spellchecker import SpellChecker\n", "\n", "# Tải các tài nguyên cần thiết\n", "nltk.download(\"punkt\")\n", "nltk.download(\"stopwords\")\n", "nltk.download(\"wordnet\")\n", "\n", "# Khởi tạo các công cụ\n", "stemmer = PorterStemmer()\n", "lemmatizer = WordNetLemmatizer()\n", "# spell = SpellChecker()\n", "stop_words = set(stopwords.words(\"english\"))\n", "\n", "def preprocess_text(text, use_stemming=False, use_lemmatization=True, correct_spelling=False):\n", " text = text.lower()\n", " \n", " text = text.translate(str.maketrans(\"\", \"\", string.punctuation))\n", " \n", " # tokens = word_tokenize(text)\n", " \n", " # tokens = [word for word in tokens if word not in stop_words]\n", " \n", " # if use_stemming:\n", " # tokens = [stemmer.stem(word) for word in tokens]\n", " # elif use_lemmatization:\n", " # tokens = [lemmatizer.lemmatize(word) for word in tokens]\n", " \n", " # 7. Xóa khoảng trắng dư thừa (không cần vì token đã tách sẵn)\n", " \n", " # 8. Chuyển đổi số thành \"NUM\"\n", " # tokens = [\"NUM\" if word.isdigit() else word for word in tokens]\n", " \n", " # 9. Xử lý lỗi chính tả\n", " # if correct_spelling:\n", " # tokens = [spell.correction(word) if word not in spell else word for word in tokens]\n", " \n", " return text#\" \".join(text)\n", "\n", "# Ví dụ sử dụng\n", "text = \"I luv programmng! U r gr8. I can't believe it's 123 times better!\"\n", "processed_text = preprocess_text(text)\n", "print(processed_text)\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "d232a9ba", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.267764Z", "iopub.status.busy": "2025-09-29T03:52:18.267488Z", "iopub.status.idle": "2025-09-29T03:52:18.451213Z", "shell.execute_reply": "2025-09-29T03:52:18.450248Z" }, "papermill": { "duration": 0.190457, "end_time": "2025-09-29T03:52:18.452821", "exception": false, "start_time": "2025-09-29T03:52:18.262364", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "df['cleaned'] = df['Patient Question'].map(lambda text: preprocess_text(text))" ] }, { "cell_type": "code", "execution_count": 8, "id": "0e75019a", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.463419Z", "iopub.status.busy": "2025-09-29T03:52:18.463120Z", "iopub.status.idle": "2025-09-29T03:52:18.466631Z", "shell.execute_reply": "2025-09-29T03:52:18.465966Z" }, "papermill": { "duration": 0.009927, "end_time": "2025-09-29T03:52:18.467830", "exception": false, "start_time": "2025-09-29T03:52:18.457903", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# from collections import Counter\n", "\n", "# def create_corpus():\n", "# corpus = []\n", "# for x in df['cleaned'].str.split():\n", "# for i in x:\n", "# corpus.append(i)\n", "# return corpus\n", "\n", "# corpus = create_corpus()\n", "\n", "# counter = Counter(corpus)\n", "# most_common_words = counter.most_common(40)\n", "\n", "# x = []\n", "# y = []\n", "# for word, count in most_common_words:\n", "# x.append(word)\n", "# y.append(count)\n", "\n", "# plt.figure(figsize=(10, 8))\n", "# sns.barplot(x=y, y=x, palette='viridis')\n", "# plt.xlabel('Count')\n", "# plt.ylabel('Words')\n", "# plt.title('Top 40 Most Common Words in review')\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": 9, "id": "a6d0e1ec", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.476634Z", "iopub.status.busy": "2025-09-29T03:52:18.476371Z", "iopub.status.idle": "2025-09-29T03:52:18.479532Z", "shell.execute_reply": "2025-09-29T03:52:18.478900Z" }, "papermill": { "duration": 0.008762, "end_time": "2025-09-29T03:52:18.480677", "exception": false, "start_time": "2025-09-29T03:52:18.471915", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# from wordcloud import WordCloud\n", "# import matplotlib.pyplot as plt\n", "# import numpy as np\n", "# from PIL import Image, ImageOps\n", "\n", "# text = ' '.join(df['cleaned'])\n", "\n", "# mask_img = Image.open('/kaggle/input/butter-mask/c26289174f9d2ee80a9bc60455257030.png').convert(\"L\") \n", "# mask_img_inverted = ImageOps.invert(mask_img) \n", "\n", "# mask = np.array(mask_img_inverted)\n", "# mask[mask == 255] = 0\n", "# mask[mask == 158] = 255\n", "\n", "# wordcloud = WordCloud(background_color='white',\n", "# max_words=2000,\n", "# mask=mask,\n", "# contour_width=3,\n", "# contour_color='white',\n", "# colormap='viridis').generate(text)\n", "\n", "# # Hiển thị\n", "# plt.figure(figsize=(10, 10))\n", "# plt.imshow(wordcloud, interpolation='bilinear')\n", "# plt.axis('off')\n", "# plt.show()\n", "\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "cd48ecdc", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.489624Z", "iopub.status.busy": "2025-09-29T03:52:18.489357Z", "iopub.status.idle": "2025-09-29T03:52:18.494641Z", "shell.execute_reply": "2025-09-29T03:52:18.493650Z" }, "papermill": { "duration": 0.011092, "end_time": "2025-09-29T03:52:18.495952", "exception": false, "start_time": "2025-09-29T03:52:18.484860", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", "\n", "X_train, X_test, y_train, y_test = train_test_split(df['Patient Question'].values,\n", " df['Dominant Distortion Encoded'].values,\n", " test_size=0.2, random_state=42)" ] }, { "cell_type": "code", "execution_count": 11, "id": "a5c6c9cd", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.504805Z", "iopub.status.busy": "2025-09-29T03:52:18.504562Z", "iopub.status.idle": "2025-09-29T03:52:18.509148Z", "shell.execute_reply": "2025-09-29T03:52:18.508343Z" }, "papermill": { "duration": 0.010425, "end_time": "2025-09-29T03:52:18.510499", "exception": false, "start_time": "2025-09-29T03:52:18.500074", "status": "completed" }, "tags": [] }, "outputs": [ { "data": { "text/plain": [ "array([1, 1, 1, ..., 1, 0, 0])" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_train" ] }, { "cell_type": "code", "execution_count": 12, "id": "ca64a24f", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:18.519582Z", "iopub.status.busy": "2025-09-29T03:52:18.519345Z", "iopub.status.idle": "2025-09-29T03:52:38.984259Z", "shell.execute_reply": "2025-09-29T03:52:38.983492Z" }, "papermill": { "duration": 20.471052, "end_time": "2025-09-29T03:52:38.985827", "exception": false, "start_time": "2025-09-29T03:52:18.514775", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import torch\n", "from torch.optim import AdamW # ✅ Sửa tại đây\n", "from torch.utils.data import Dataset, DataLoader\n", "from transformers import RobertaTokenizer, RobertaForSequenceClassification\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import accuracy_score\n", "from transformers import AutoTokenizer, AutoModel" ] }, { "cell_type": "code", "execution_count": 13, "id": "7623d594", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:38.995659Z", "iopub.status.busy": "2025-09-29T03:52:38.995122Z", "iopub.status.idle": "2025-09-29T03:52:38.999547Z", "shell.execute_reply": "2025-09-29T03:52:38.998744Z" }, "papermill": { "duration": 0.010439, "end_time": "2025-09-29T03:52:39.000804", "exception": false, "start_time": "2025-09-29T03:52:38.990365", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.47.0\n" ] } ], "source": [ "import transformers\n", "\n", "print(transformers.__version__)" ] }, { "cell_type": "code", "execution_count": 14, "id": "c06d0ef3", "metadata": { "execution": { "iopub.execute_input": "2025-09-29T03:52:39.010246Z", "iopub.status.busy": "2025-09-29T03:52:39.009943Z", "iopub.status.idle": "2025-09-29T03:52:40.957564Z", "shell.execute_reply": "2025-09-29T03:52:40.956570Z" }, "papermill": { "duration": 1.954124, "end_time": "2025-09-29T03:52:40.959317", "exception": false, "start_time": "2025-09-29T03:52:39.005193", "status": "completed" }, "tags": [] }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "81d6d531b8bf46208b1dbf3a07b3da7b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer_config.json: 0%| | 0.00/52.0 [00:00