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

582 lines
14 KiB
Text

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"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 nltk.stem.snowball import SnowballStemmer\n",
"from sklearn.naive_bayes import GaussianNB"
]
},
{
"cell_type": "code",
"execution_count": 2,
"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": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(559999, 3)"
]
},
"execution_count": 3,
"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": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df['Label'].unique()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"dbpedia_df = dbpedia_df.sample(10000, replace=False)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"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>328754</th>\n",
" <td>9</td>\n",
" <td>Sadabad-e Sofla</td>\n",
" <td>Sadabad-e Sofla (Persian: سعدابادسفلي‎ also R...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>268204</th>\n",
" <td>7</td>\n",
" <td>Westgate Mall (Spartanburg)</td>\n",
" <td>Westgate Mall is a shopping mall in Spartanbu...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>53524</th>\n",
" <td>2</td>\n",
" <td>North Rockland High School</td>\n",
" <td>North Rockland High School is a high school l...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>435646</th>\n",
" <td>11</td>\n",
" <td>Tillandsia diguetii</td>\n",
" <td>Tillandsia diguetii is a species of the genus...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>254752</th>\n",
" <td>7</td>\n",
" <td>Palais Wilczek</td>\n",
" <td>Palais Wilczek is a palace in Vienna Austria....</td>\n",
" </tr>\n",
" <tr>\n",
" <th>29074</th>\n",
" <td>1</td>\n",
" <td>Canfor</td>\n",
" <td>Canfor Corporation is a Canadian integrated f...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>155059</th>\n",
" <td>4</td>\n",
" <td>Gerry Rioux</td>\n",
" <td>Gerard Rioux (born February 17 1959) is a Can...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>137451</th>\n",
" <td>4</td>\n",
" <td>Jerry DePoyster</td>\n",
" <td>Jerry Dean DePoyster (born July 6 1946 in Oma...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>363022</th>\n",
" <td>10</td>\n",
" <td>Pieris (butterfly)</td>\n",
" <td>Pieris the whites or garden whites is a wides...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>499846</th>\n",
" <td>13</td>\n",
" <td>Gunah Aur Kanoon</td>\n",
" <td>Gunah Aur Kanoon is a 1970 Bollywood drama fi...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"328754 9 Sadabad-e Sofla \n",
"268204 7 Westgate Mall (Spartanburg) \n",
"53524 2 North Rockland High School \n",
"435646 11 Tillandsia diguetii \n",
"254752 7 Palais Wilczek \n",
"29074 1 Canfor \n",
"155059 4 Gerry Rioux \n",
"137451 4 Jerry DePoyster \n",
"363022 10 Pieris (butterfly) \n",
"499846 13 Gunah Aur Kanoon \n",
"\n",
" Text \n",
"328754 Sadabad-e Sofla (Persian: سعدابادسفلي‎ also R... \n",
"268204 Westgate Mall is a shopping mall in Spartanbu... \n",
"53524 North Rockland High School is a high school l... \n",
"435646 Tillandsia diguetii is a species of the genus... \n",
"254752 Palais Wilczek is a palace in Vienna Austria.... \n",
"29074 Canfor Corporation is a Canadian integrated f... \n",
"155059 Gerard Rioux (born February 17 1959) is a Can... \n",
"137451 Jerry Dean DePoyster (born July 6 1946 in Oma... \n",
"363022 Pieris the whites or garden whites is a wides... \n",
"499846 Gunah Aur Kanoon is a 1970 Bollywood drama fi... "
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.sample(10)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 3)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"X = dbpedia_df['Text']\n",
"\n",
"Y = dbpedia_df['Label']"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"346354 Hoseynabad-e Sarzeh (Persian: حسين ابادسرزه‎ ...\n",
"198538 Milton Berkes (born September 29 1924) is a f...\n",
"550592 R.M. Williams Outback (or simply Outback) is ...\n",
"387637 Metasia carnealis is a species of moth in the...\n",
"366618 The Father Basilio's Striped Mouse or Bioko H...\n",
"Name: Text, dtype: object"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X.head()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"346354 9\n",
"198538 5\n",
"550592 14\n",
"387637 10\n",
"366618 10\n",
"Name: Label, dtype: int64"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y.head()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"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": [],
"source": [
"stemmer = SnowballStemmer('english')\n",
"analyzer = HashingVectorizer().build_analyzer()\n",
"\n",
"def stemmed_words(doc):\n",
" return (stemmer.stem(w) for w in analyzer(doc))"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 1024)"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stem_vectorizer = HashingVectorizer(n_features=2**10, norm='l2', analyzer=stemmed_words)\n",
"\n",
"feature_vector = stem_vectorizer.transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 21)\t0.25607375986579195\n",
" (0, 24)\t-0.12803687993289598\n",
" (0, 27)\t0.12803687993289598\n",
" (0, 61)\t-0.12803687993289598\n",
" (0, 62)\t0.12803687993289598\n",
" (0, 69)\t-0.12803687993289598\n",
" (0, 71)\t-0.25607375986579195\n",
" (0, 145)\t-0.12803687993289598\n",
" (0, 158)\t-0.12803687993289598\n",
" (0, 215)\t0.12803687993289598\n",
" (0, 273)\t0.25607375986579195\n",
" (0, 301)\t-0.12803687993289598\n",
" (0, 304)\t0.12803687993289598\n",
" (0, 355)\t0.12803687993289598\n",
" (0, 365)\t0.12803687993289598\n",
" (0, 424)\t-0.12803687993289598\n",
" (0, 540)\t0.25607375986579195\n",
" (0, 550)\t-0.12803687993289598\n",
" (0, 569)\t0.12803687993289598\n",
" (0, 595)\t-0.3841106397986879\n",
" (0, 643)\t0.12803687993289598\n",
" (0, 659)\t0.12803687993289598\n",
" (0, 697)\t0.12803687993289598\n",
" (0, 745)\t-0.12803687993289598\n",
" (0, 758)\t-0.12803687993289598\n",
" (0, 799)\t0.12803687993289598\n",
" (0, 832)\t-0.12803687993289598\n",
" (0, 877)\t0.12803687993289598\n",
" (0, 883)\t0.12803687993289598\n",
" (0, 884)\t-0.12803687993289598\n",
" (0, 885)\t0.25607375986579195\n",
" (0, 913)\t0.12803687993289598\n",
" (0, 914)\t-0.12803687993289598\n",
" (0, 971)\t-0.25607375986579195\n",
" (0, 983)\t-0.12803687993289598\n"
]
}
],
"source": [
"print(feature_vector[0])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 1024)"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 28,
"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": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((8000, 1024), (2000, 1024))"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x_train.shape, x_test.shape"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((8000,), (2000,))"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_train.shape, y_test.shape"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 3, 3, 11, ..., 2, 2, 4])"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1120\n",
"accuracy_score : 0.56\n",
"precision_score : 0.5663465185830068\n",
"recall_score : 0.56\n"
]
}
],
"source": [
"summarize_classification(y_test, y_pred)"
]
},
{
"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
}