{ "cells": [ { "cell_type": "code", "execution_count": 6, "id": "7e1651a1", "metadata": {}, "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", "
InputTags
0Title: What is the effective differencial effe...['electronics']
1Title: Heat sensor with fan cooling Body: Can ...['electronics']
2Title: Outlet Installation--more wires than my...['electronics']
3Title: Buck Converter Operation Question Body:...['electronics']
4Title: Urgent help in area of ASIC design, ver...['electronics']
\n", "
" ], "text/plain": [ " Input Tags\n", "0 Title: What is the effective differencial effe... ['electronics']\n", "1 Title: Heat sensor with fan cooling Body: Can ... ['electronics']\n", "2 Title: Outlet Installation--more wires than my... ['electronics']\n", "3 Title: Buck Converter Operation Question Body:... ['electronics']\n", "4 Title: Urgent help in area of ASIC design, ver... ['electronics']" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "# Read the CSV file\n", "data = pd.read_csv('data/all_combined_data.csv')\n", "\n", "# Display the first few rows of the data\n", "data.head()" ] }, { "cell_type": "code", "execution_count": 7, "id": "c9057558", "metadata": {}, "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", "
InputTags
162648Title: Is there an optimal strategy for placi...['algorithms', 'efficiency']
162649Title: Handling Events Across Multi-Server Ap...['c#', 'application-design']
162650Title: Is it good practice to use try catch f...['design', 'engineering']
162651Title: What do you call a process which trans...['python', 'naming', 'parsing', 'serialization']
162652Title: Testing : Why is it necessary?Body: He...['testing']
\n", "
" ], "text/plain": [ " Input \\\n", "162648 Title: Is there an optimal strategy for placi... \n", "162649 Title: Handling Events Across Multi-Server Ap... \n", "162650 Title: Is it good practice to use try catch f... \n", "162651 Title: What do you call a process which trans... \n", "162652 Title: Testing : Why is it necessary?Body: He... \n", "\n", " Tags \n", "162648 ['algorithms', 'efficiency'] \n", "162649 ['c#', 'application-design'] \n", "162650 ['design', 'engineering'] \n", "162651 ['python', 'naming', 'parsing', 'serialization'] \n", "162652 ['testing'] " ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.tail()" ] }, { "cell_type": "code", "execution_count": null, "id": "297d09db", "metadata": {}, "outputs": [], "source": [ "data['Tags'] = data['Tags'].apply(lambda tags: tags + ['ignore'] if len(tags) == 1 else tags)" ] }, { "cell_type": "code", "execution_count": 5, "id": "e3d5ffe0", "metadata": {}, "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", "
InputTags
0Title: What is the effective differencial effe...['electronics']
1Title: Heat sensor with fan cooling Body: Can ...['electronics']
2Title: Outlet Installation--more wires than my...['electronics']
3Title: Buck Converter Operation Question Body:...['electronics']
4Title: Urgent help in area of ASIC design, ver...['electronics']
\n", "
" ], "text/plain": [ " Input Tags\n", "0 Title: What is the effective differencial effe... ['electronics']\n", "1 Title: Heat sensor with fan cooling Body: Can ... ['electronics']\n", "2 Title: Outlet Installation--more wires than my... ['electronics']\n", "3 Title: Buck Converter Operation Question Body:... ['electronics']\n", "4 Title: Urgent help in area of ASIC design, ver... ['electronics']" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.head()" ] }, { "cell_type": "code", "execution_count": 13, "id": "9a1cba07", "metadata": {}, "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", "
InputTags
0Title: What is the effective differencial effe...[electronics, ignore]
1Title: Heat sensor with fan cooling Body: Can ...[electronics, ignore]
2Title: Outlet Installation--more wires than my...[electronics, ignore]
3Title: Buck Converter Operation Question Body:...[electronics, ignore]
4Title: Urgent help in area of ASIC design, ver...[electronics, ignore]
\n", "
" ], "text/plain": [ " Input Tags\n", "0 Title: What is the effective differencial effe... [electronics, ignore]\n", "1 Title: Heat sensor with fan cooling Body: Can ... [electronics, ignore]\n", "2 Title: Outlet Installation--more wires than my... [electronics, ignore]\n", "3 Title: Buck Converter Operation Question Body:... [electronics, ignore]\n", "4 Title: Urgent help in area of ASIC design, ver... [electronics, ignore]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "6b6a6eba", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'data' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[1], line 9\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01msklearn\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mmodel_selection\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m train_test_split\n\u001b[1;32m 6\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01msklearn\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mmetrics\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m classification_report\n\u001b[0;32m----> 9\u001b[0m df \u001b[38;5;241m=\u001b[39m \u001b[43mdata\u001b[49m[[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mInput\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mTags\u001b[39m\u001b[38;5;124m'\u001b[39m]]\u001b[38;5;241m.\u001b[39mcopy()\n\u001b[1;32m 10\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mast\u001b[39;00m\n\u001b[1;32m 12\u001b[0m df[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTags\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m df[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTags\u001b[39m\u001b[38;5;124m\"\u001b[39m]\u001b[38;5;241m.\u001b[39mapply(ast\u001b[38;5;241m.\u001b[39mliteral_eval)\n", "\u001b[0;31mNameError\u001b[0m: name 'data' is not defined" ] } ], "source": [ "from sklearn.preprocessing import MultiLabelBinarizer\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.multioutput import MultiOutputClassifier\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import classification_report\n", "\n", "\n", "df = data[['Input', 'Tags']].copy()\n", "import ast\n", "\n", "df[\"Tags\"] = df[\"Tags\"].apply(ast.literal_eval)\n", "\n", "# Step 1: One-hot encode the tags\n", "mlb = MultiLabelBinarizer()\n", "y = mlb.fit_transform(df[\"Tags\"])\n", "\n", "# Step 2: TF-IDF on Input column\n", "tfidf = TfidfVectorizer(max_features=5000)\n", "X = tfidf.fit_transform(df[\"Input\"])\n", "\n", "# Step 3: Train-test split\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "# Step 4: Train Random Forest in MultiOutputClassifier\n", "rf = RandomForestClassifier(n_estimators=100, random_state=42)\n", "multi_rf = MultiOutputClassifier(rf)\n", "multi_rf.fit(X_train, y_train)\n", "\n", "# Step 5: Predict and evaluate\n", "y_pred = multi_rf.predict(X_test)\n", "print(classification_report(y_test, y_pred, target_names=mlb.classes_))\n", "# Step 6: Save the model\n", "import joblib\n", "joblib.dump(multi_rf, 'multi_rf_model.pkl')\n", "# Step 7: Save the TF-IDF vectorizer\n", "joblib.dump(tfidf, 'tfidf_vectorizer.pkl')\n", "# Step 8: Save the label binarizer\n", "joblib.dump(mlb, 'mlb.pkl')\n", "# Step 9: Load the model and vectorizer\n", "loaded_model = joblib.load('multi_rf_model.pkl')\n", "loaded_vectorizer = joblib.load('tfidf_vectorizer.pkl')\n", "loaded_mlb = joblib.load('mlb.pkl')\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9a11d48f", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 27, "id": "6312830d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Decoded tags: ('electronics',)\n" ] } ], "source": [ "import numpy as np\n", "\n", "print(\"Decoded tags:\", mlb.inverse_transform(np.array([y[0]]))[0])\n" ] }, { "cell_type": "code", "execution_count": 21, "id": "bba02bd6", "metadata": {}, "outputs": [], "source": [ "import ast\n", "\n", "df[\"Tags\"] = df[\"Tags\"].apply(ast.literal_eval)\n" ] }, { "cell_type": "code", "execution_count": 22, "id": "260ee444", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 [electronics]\n", "1 [electronics]\n", "2 [electronics]\n", "3 [electronics]\n", "4 [electronics]\n", "Name: Tags, dtype: object\n", "\n" ] } ], "source": [ "print(df[\"Tags\"].head())\n", "print(type(df[\"Tags\"].iloc[0]))\n" ] }, { "cell_type": "code", "execution_count": 23, "id": "61f2205b", "metadata": {}, "outputs": [], "source": [ "y = mlb.fit_transform(df[\"Tags\"])\n" ] }, { "cell_type": "code", "execution_count": 24, "id": "b6edbea6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Decoded tags: ('electronics',)\n" ] } ], "source": [ "print(\"Decoded tags:\", mlb.inverse_transform(np.array([y[0]]))[0])\n" ] }, { "cell_type": "code", "execution_count": 26, "id": "60b80231", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([0, 0, 0, ..., 0, 0, 0], shape=(13158,))" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y[0]" ] }, { "cell_type": "code", "execution_count": 25, "id": "30981b76", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Input object\n", "Tags object\n", "dtype: object" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.dtypes" ] }, { "cell_type": "code", "execution_count": 9, "id": "132c7bfc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Average Accuracy: 0.9140289373926052\n" ] } ], "source": [ "from sklearn.metrics import accuracy_score\n", "\n", "# Calculate accuracy for each label and then average\n", "accuracies = [accuracy_score(y_test[:, i], y_pred[:, i]) for i in range(y_test.shape[1])]\n", "average_accuracy = sum(accuracies) / len(accuracies)\n", "\n", "print(f\"Average Accuracy: {average_accuracy}\")" ] }, { "cell_type": "code", "execution_count": 14, "id": "e09ede12", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Empty DataFrame\n", "Columns: [Input, Tags]\n", "Index: []\n" ] } ], "source": [ "single_tag_rows = df[df['Tags'].apply(len) <= 3]\n", "print(single_tag_rows)" ] }, { "cell_type": "code", "execution_count": 1, "id": "644cd3c3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " precision recall f1-score support\n", "\n", " 0 0.35 0.67 0.46 9\n", " 1 1.00 0.09 0.17 11\n", " 2 0.91 0.71 0.80 14\n", "\n", " micro avg 0.59 0.50 0.54 34\n", " macro avg 0.75 0.49 0.48 34\n", "weighted avg 0.79 0.50 0.51 34\n", " samples avg 0.51 0.48 0.45 34\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/home/darth/.pyenv/versions/3.10.12/envs/major02/lib/python3.10/site-packages/sklearn/metrics/_classification.py:1565: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in samples with no predicted labels. Use `zero_division` parameter to control this behavior.\n", " _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n", "/home/darth/.pyenv/versions/3.10.12/envs/major02/lib/python3.10/site-packages/sklearn/metrics/_classification.py:1565: UndefinedMetricWarning: Recall is ill-defined and being set to 0.0 in samples with no true labels. Use `zero_division` parameter to control this behavior.\n", " _warn_prf(average, modifier, f\"{metric.capitalize()} is\", len(result))\n" ] } ], "source": [ "from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.multioutput import MultiOutputClassifier\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import classification_report\n", "import numpy as np\n", "\n", "# Example: X has 100 samples, 20 features; y has 100 samples, 3 possible labels per sample\n", "X = np.random.rand(100, 20)\n", "y = np.random.randint(2, size=(100, 3)) # Binary presence/absence for 3 labels\n", "\n", "# Train-test split\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "# Initialize base RandomForest classifier\n", "rf = RandomForestClassifier(n_estimators=100, random_state=42)\n", "\n", "# Wrap it for multi-label classification\n", "multi_rf = MultiOutputClassifier(rf)\n", "\n", "# Train the model\n", "multi_rf.fit(X_train, y_train)\n", "\n", "# Predict\n", "y_pred = multi_rf.predict(X_test)\n", "\n", "# Evaluate\n", "print(classification_report(y_test, y_pred))\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "32e4d5bc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([0, 1, 1])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_train[3]" ] }, { "cell_type": "code", "execution_count": null, "id": "a2477b56", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "major02", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }