thesis-prediction-ml/building-features-from-text-data/12a-HashingVectorizer_NaiveBayesClassifier.ipynb
2023-06-18 14:45:35 +02:00

711 lines
17 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dataset link : https://github.com/pyk/dbpedia_csv"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"from sklearn.metrics import accuracy_score\n",
"from sklearn.metrics import precision_score\n",
"from sklearn.metrics import recall_score\n",
"\n",
"from sklearn.feature_extraction.text import HashingVectorizer\n",
"from sklearn.naive_bayes import GaussianNB"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"dbpedia_df = pd.read_csv('./datasets/dbpedia_csv/train.csv', \n",
" skiprows=1, names = ['Label', 'Name', 'Text'])"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(559999, 3)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### DBPedia classes\n",
"\n",
"- Company\n",
"- EducationalInstitution\n",
"- Artist\n",
"- Athlete\n",
"- OfficeHolder\n",
"- MeanOfTransportation\n",
"- Building\n",
"- NaturalPlace\n",
"- Village\n",
"- Animal\n",
"- Plant\n",
"- Album\n",
"- Film\n",
"- WrittenWork"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df['Label'].unique()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"dbpedia_df = dbpedia_df.sample(10000, replace=False)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Label</th>\n",
" <th>Name</th>\n",
" <th>Text</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>494483</th>\n",
" <td>13</td>\n",
" <td>A Wedding Suit</td>\n",
" <td>A Wedding Suit (Persian: لباسی برای عروسی‎ Le...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>548491</th>\n",
" <td>14</td>\n",
" <td>Into Thin Air</td>\n",
" <td>Into Thin Air: A Personal Account of the Mt. ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>339369</th>\n",
" <td>9</td>\n",
" <td>Banavchan</td>\n",
" <td>Banavchan (Persian: بناوچان‎ also Romanized a...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>295828</th>\n",
" <td>8</td>\n",
" <td>Icalma Lake</td>\n",
" <td>Icalma Lake is a lake located in the Andes of...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>416552</th>\n",
" <td>11</td>\n",
" <td>Pouteria sandwicensis</td>\n",
" <td>Pouteria sandwicensis is a species of floweri...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>503849</th>\n",
" <td>13</td>\n",
" <td>Pepo (film)</td>\n",
" <td>Pepo (Armenian: Պեպո) is a 1935 Soviet film d...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>364384</th>\n",
" <td>10</td>\n",
" <td>Puebla deer mouse</td>\n",
" <td>The Puebla deer mouse (Peromyscus mekisturus)...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>265465</th>\n",
" <td>7</td>\n",
" <td>Waleffe Castle</td>\n",
" <td>Waleffe Castle is a castle in Belgium.</td>\n",
" </tr>\n",
" <tr>\n",
" <th>528364</th>\n",
" <td>14</td>\n",
" <td>Through the Arc of the Rain Forest</td>\n",
" <td>Through the Arc of the Rain Forest is a novel...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>423816</th>\n",
" <td>11</td>\n",
" <td>Guarianthe</td>\n",
" <td>Guarianthe abbreviated Gur. in the horticultu...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"494483 13 A Wedding Suit \n",
"548491 14 Into Thin Air \n",
"339369 9 Banavchan \n",
"295828 8 Icalma Lake \n",
"416552 11 Pouteria sandwicensis \n",
"503849 13 Pepo (film) \n",
"364384 10 Puebla deer mouse \n",
"265465 7 Waleffe Castle \n",
"528364 14 Through the Arc of the Rain Forest \n",
"423816 11 Guarianthe \n",
"\n",
" Text \n",
"494483 A Wedding Suit (Persian: لباسی برای عروسی‎ Le... \n",
"548491 Into Thin Air: A Personal Account of the Mt. ... \n",
"339369 Banavchan (Persian: بناوچان‎ also Romanized a... \n",
"295828 Icalma Lake is a lake located in the Andes of... \n",
"416552 Pouteria sandwicensis is a species of floweri... \n",
"503849 Pepo (Armenian: Պեպո) is a 1935 Soviet film d... \n",
"364384 The Puebla deer mouse (Peromyscus mekisturus)... \n",
"265465 Waleffe Castle is a castle in Belgium. \n",
"528364 Through the Arc of the Rain Forest is a novel... \n",
"423816 Guarianthe abbreviated Gur. in the horticultu... "
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.sample(10)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 3)"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"X = dbpedia_df['Text']\n",
"\n",
"Y = dbpedia_df['Label']"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"187313 Bruce Cameron Young is an Australian Liberal ...\n",
"94935 Daniel Douglas Orlando (born May 29 1981) als...\n",
"93329 John Hultberg (February 8 1922 – April 15 200...\n",
"530642 The Oxford University Commonwealth Law Journa...\n",
"361874 Stensioella heintzi (Heintz's Little Stensio)...\n",
"Name: Text, dtype: object"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X.head()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"187313 5\n",
"94935 3\n",
"93329 3\n",
"530642 14\n",
"361874 10\n",
"Name: Label, dtype: int64"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y.head()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"def summarize_classification(y_test, y_pred):\n",
"\n",
" acc = accuracy_score(y_test, y_pred, normalize=True)\n",
" num_acc = accuracy_score(y_test, y_pred, normalize=False)\n",
" prec = precision_score(y_test, y_pred, average='weighted')\n",
" recall = recall_score(y_test, y_pred, average='weighted')\n",
" \n",
" print(\"Length of testing data: \", len(y_test))\n",
" print(\"accuracy_count : \" , num_acc)\n",
" print(\"accuracy_score : \" , acc)\n",
" print(\"precision_score : \" , prec)\n",
" print(\"recall_score : \", recall)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 1024)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vectorizer = HashingVectorizer(n_features=2**10, norm='l2')\n",
"\n",
"feature_vector = vectorizer.transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 39)\t0.15811388300841897\n",
" (0, 53)\t-0.15811388300841897\n",
" (0, 54)\t0.15811388300841897\n",
" (0, 61)\t-0.15811388300841897\n",
" (0, 152)\t0.15811388300841897\n",
" (0, 158)\t-0.4743416490252569\n",
" (0, 175)\t-0.15811388300841897\n",
" (0, 203)\t-0.15811388300841897\n",
" (0, 300)\t0.31622776601683794\n",
" (0, 308)\t-0.15811388300841897\n",
" (0, 311)\t-0.15811388300841897\n",
" (0, 352)\t-0.15811388300841897\n",
" (0, 362)\t-0.15811388300841897\n",
" (0, 363)\t0.15811388300841897\n",
" (0, 365)\t0.31622776601683794\n",
" (0, 399)\t0.15811388300841897\n",
" (0, 426)\t0.15811388300841897\n",
" (0, 470)\t0.15811388300841897\n",
" (0, 513)\t-0.15811388300841897\n",
" (0, 534)\t0.15811388300841897\n",
" (0, 540)\t-0.15811388300841897\n",
" (0, 663)\t-0.15811388300841897\n",
" (0, 665)\t-0.15811388300841897\n",
" (0, 819)\t-0.15811388300841897\n",
" (0, 1002)\t-0.15811388300841897\n",
" (0, 1011)\t-0.15811388300841897\n"
]
}
],
"source": [
"print(feature_vector[0])"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 1024)"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"x_train, x_test, y_train, y_test = train_test_split(X_dense, Y, test_size = 0.2)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((8000, 1024), (2000, 1024))"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x_train.shape, x_test.shape"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((8000,), (2000,))"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_train.shape, y_test.shape"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 7, 11, 13, ..., 5, 6, 7])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1153\n",
"accuracy_score : 0.5765\n",
"precision_score : 0.5891110304184962\n",
"recall_score : 0.5765\n"
]
}
],
"source": [
"summarize_classification(y_test, y_pred)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"267097 7\n",
"364326 10\n",
"509624 13\n",
"466990 12\n",
"145918 4\n",
"Name: Label, dtype: int64"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_test.head()"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"y_test = np.array(y_test)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>y_test</th>\n",
" <th>y_pred</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>1486</th>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>494</th>\n",
" <td>9</td>\n",
" <td>8</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1039</th>\n",
" <td>3</td>\n",
" <td>3</td>\n",
" </tr>\n",
" <tr>\n",
" <th>985</th>\n",
" <td>9</td>\n",
" <td>9</td>\n",
" </tr>\n",
" <tr>\n",
" <th>711</th>\n",
" <td>8</td>\n",
" <td>10</td>\n",
" </tr>\n",
" <tr>\n",
" <th>532</th>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1249</th>\n",
" <td>11</td>\n",
" <td>10</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1746</th>\n",
" <td>8</td>\n",
" <td>11</td>\n",
" </tr>\n",
" <tr>\n",
" <th>766</th>\n",
" <td>1</td>\n",
" <td>7</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1851</th>\n",
" <td>12</td>\n",
" <td>4</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" y_test y_pred\n",
"1486 1 1\n",
"494 9 8\n",
"1039 3 3\n",
"985 9 9\n",
"711 8 10\n",
"532 1 1\n",
"1249 11 10\n",
"1746 8 11\n",
"766 1 7\n",
"1851 12 4"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pred_results = pd.DataFrame({'y_test': pd.Series(y_test),\n",
" 'y_pred': pd.Series(y_pred)})\n",
"\n",
"pred_results.sample(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}