{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":87232,"databundleVersionId":9912598,"sourceType":"competition"}],"dockerImageVersionId":30823,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-24T15:03:56.206784Z","iopub.execute_input":"2024-12-24T15:03:56.207206Z","iopub.status.idle":"2024-12-24T15:03:56.596623Z","shell.execute_reply.started":"2024-12-24T15:03:56.207165Z","shell.execute_reply":"2024-12-24T15:03:56.595589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Input\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.metrics import classification_report\nimport nltk\n\n# Global parameters\nMAX_FEATURES = 1000\nEPOCHS = 10\nBATCH_SIZE = 32\n\n# Download NLTK resources\nnltk.download('stopwords', quiet=True)\nnltk.download('punkt', quiet=True)\n\ndef preprocess_text_batch(df, column):\n    import re\n    from nltk.corpus import stopwords\n\n    stop_words = set(stopwords.words('english'))\n    df[column] = df[column].str.lower()  # Convert to lowercase\n    df[column] = df[column].str.replace(r'@\\w+', '', regex=True)  # Remove mentions\n    df[column] = df[column].str.replace(r'http\\S+|www.\\S+', '', regex=True)  # Remove URLs\n    df[column] = df[column].str.replace(r'[^a-zA-Z\\s]', '', regex=True)  # Remove non-alphabetic\n    df[column] = df[column].apply(lambda x: ' '.join(\n        [word for word in x.split() if word not in stop_words]\n    ))  # Remove stopwords\n    return df\n\ndef load_and_preprocess_data():\n    # Load data\n    tweets_dm = pd.read_json(\"/kaggle/input/dm-2024-isa-5810-lab-2-homework/tweets_DM.json\", lines=True)\n    emotion = pd.read_csv(\"/kaggle/input/dm-2024-isa-5810-lab-2-homework/emotion.csv\")\n\n    # Extract tweet details\n    tweets_dm['tweet_id'] = tweets_dm['_source'].apply(lambda x: x['tweet']['tweet_id'])\n    tweets_dm['text'] = tweets_dm['_source'].apply(lambda x: x['tweet']['text'])\n\n    # Merge with emotion data\n    emotion_tweets = tweets_dm.merge(emotion, on='tweet_id', how='left')\n\n    # Clean text\n    emotion_tweets = preprocess_text_batch(emotion_tweets, 'text')\n    emotion_tweets.rename(columns={'text': 'text_cleaned'}, inplace=True)\n\n    return emotion_tweets\n\ndef prepare_data(emotion_tweets):\n    # Separate tweets with and without emotion labels\n    df_with_emotion = emotion_tweets[emotion_tweets['emotion'].notna()]\n    df_without_emotion = emotion_tweets[emotion_tweets['emotion'].isna()]\n\n    # Prepare training data\n    X_text = df_with_emotion['text_cleaned']\n    y_emotion = df_with_emotion['emotion']\n\n    # Vectorize text\n    vectorizer = TfidfVectorizer(max_features=MAX_FEATURES, stop_words='english')\n    X_tfidf = vectorizer.fit_transform(X_text)\n\n    # Encode labels\n    label_encoder = LabelEncoder()\n    y_encoded = label_encoder.fit_transform(y_emotion)\n\n    # Split data\n    X_train, X_test, y_train, y_test = train_test_split(\n        X_tfidf, y_encoded, test_size=0.2, random_state=42\n    )\n\n    # Convert to dense arrays to save memory\n    X_train = X_train.toarray()\n    X_test = X_test.toarray()\n\n    # Convert labels to categorical\n    y_train_cat = tf.keras.utils.to_categorical(y_train)\n    y_test_cat = tf.keras.utils.to_categorical(y_test)\n\n    return (X_train, y_train_cat, X_test, y_test_cat, \n            vectorizer, label_encoder, df_without_emotion)\n\ndef create_model(input_dim, num_classes):\n    model = Sequential([\n        Input(shape=(input_dim,)),\n        Dense(128, activation='relu'),\n        Dropout(0.3),\n        Dense(64, activation='relu'),\n        Dropout(0.3),\n        Dense(num_classes, activation='softmax')\n    ])\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    return model\n\ndef train_and_predict():\n    # Load and preprocess data\n    emotion_tweets = load_and_preprocess_data()\n\n    # Prepare data\n    (X_train, y_train_cat, X_test, y_test_cat, \n     vectorizer, label_encoder, df_without_emotion) = prepare_data(emotion_tweets)\n\n    # Create and train model\n    early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n    \n    model = create_model(X_train.shape[1], y_train_cat.shape[1])\n\n    model.fit(\n        X_train, y_train_cat,\n        validation_data=(X_test, y_test_cat),\n        epochs=EPOCHS,\n        batch_size=BATCH_SIZE,\n        callbacks=[early_stopping],\n        verbose=1\n    )\n\n    # Evaluate model\n    y_test_pred = model.predict(X_test).argmax(axis=1)\n    print(\"\\nClassification Report:\\n\")\n    print(classification_report(y_test_cat.argmax(axis=1), y_test_pred, target_names=label_encoder.classes_))\n\n    # Predict for tweets without emotion\n    X_predict_text = df_without_emotion['text_cleaned']\n    X_predict_tfidf = vectorizer.transform(X_predict_text).toarray()\n\n    predictions = model.predict(X_predict_tfidf)\n    predicted_classes = predictions.argmax(axis=1)\n\n    # Decode predicted labels\n    predicted_emotions = label_encoder.inverse_transform(predicted_classes)\n\n    # Prepare submission\n    submission = pd.DataFrame({\n        'id': df_without_emotion['tweet_id'],\n        'emotion': predicted_emotions\n    })\n\n    # Save submission\n    output_path = \"/kaggle/working/submission.csv\"\n    submission.to_csv(output_path, index=False)\n    print(f\"Submission file created: {output_path}\")\n\n    return submission\n\n# Run the entire process\nsubmission = train_and_predict()\nprint(submission.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-24T15:17:08.712301Z","iopub.execute_input":"2024-12-24T15:17:08.712575Z","iopub.status.idle":"2024-12-24T15:29:34.374092Z","shell.execute_reply.started":"2024-12-24T15:17:08.712544Z","shell.execute_reply":"2024-12-24T15:29:34.373010Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}