{ "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 CountVectorizer\n", "from sklearn.naive_bayes import GaussianNB" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "dbpedia_df = pd.read_csv('../building-features-from-text-data/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\n", "\n" ] }, { "attachments": {}, "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": [ "
\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
LabelNameText
38061610Stilifer akahitodeStilifer akahitode is a species of sea snail ...
50019813Ip Man 2Ip Man 2 is a 2010 Hong Kong biographical mar...
883773Achuta ManasaAchuta Manasa is an Indian kuchipudi dancer.
37714510Bombyx incompositaBombyx incomposita is a moth in the Bombycida...
290601W. W. GreenerW.W. Greener is a sporting shotgun and rifle ...
1987495Robert E. HolmesRobert Edward Holmes (November 14 1922 – July...
48865313My GiantMy Giant is a 1998 comedy drama film starring...
3207659Lockland OhioLockland is a village in Hamilton County Ohio...
75831Fresh to OrderFresh to Order (f2o) is an Atlanta Fine fast ...
951133Donald DeskeyDonald Deskey (November 23 1894 – April 29 19...
\n", "
" ], "text/plain": [ " Label Name \\\n", "380616 10 Stilifer akahitode \n", "500198 13 Ip Man 2 \n", "88377 3 Achuta Manasa \n", "377145 10 Bombyx incomposita \n", "29060 1 W. W. Greener \n", "198749 5 Robert E. Holmes \n", "488653 13 My Giant \n", "320765 9 Lockland Ohio \n", "7583 1 Fresh to Order \n", "95113 3 Donald Deskey \n", "\n", " Text \n", "380616 Stilifer akahitode is a species of sea snail ... \n", "500198 Ip Man 2 is a 2010 Hong Kong biographical mar... \n", "88377 Achuta Manasa is an Indian kuchipudi dancer. \n", "377145 Bombyx incomposita is a moth in the Bombycida... \n", "29060 W.W. Greener is a sporting shotgun and rifle ... \n", "198749 Robert Edward Holmes (November 14 1922 – July... \n", "488653 My Giant is a 1998 comedy drama film starring... \n", "320765 Lockland is a village in Hamilton County Ohio... \n", "7583 Fresh to Order (f2o) is an Atlanta Fine fast ... \n", "95113 Donald Deskey (November 23 1894 – April 29 19... " ] }, "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": [ "37295 Malibu Comics (also known as Malibu Graphics)...\n", "543193 Data & Knowledge Engineering (DKE) is a journ...\n", "221689 USS Swordfish (SS-193) a Sargo-class submarin...\n", "374962 Dioryctria is a genus of snout moths. It was ...\n", "240744 Midsummer House is a restaurant located in Ca...\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": [ "37295 1\n", "543193 14\n", "221689 6\n", "374962 10\n", "240744 7\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": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10000, 47912)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count_vectorizer = CountVectorizer()\n", "\n", "feature_vector = count_vectorizer.fit_transform(X)\n", "\n", "feature_vector.shape" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " (0, 25727)\t4\n", " (0, 10069)\t3\n", " (0, 3015)\t1\n", " (0, 22973)\t2\n", " (0, 4138)\t1\n", " (0, 17865)\t1\n", " (0, 44316)\t2\n", " (0, 3249)\t1\n", " (0, 3150)\t1\n", " (0, 10066)\t1\n", " (0, 6616)\t1\n", " (0, 33404)\t1\n", " (0, 2204)\t1\n", " (0, 20470)\t3\n", " (0, 41304)\t5\n", " (0, 23891)\t1\n", " (0, 793)\t1\n", " (0, 3321)\t3\n", " (0, 13674)\t1\n", " (0, 806)\t1\n", " (0, 5866)\t1\n", " (0, 16106)\t1\n", " (0, 21167)\t1\n", " (0, 42818)\t1\n", " (0, 24564)\t1\n", " (0, 29944)\t1\n", " (0, 40128)\t1\n", " (0, 41698)\t2\n", " (0, 29511)\t1\n", " (0, 42877)\t1\n", " (0, 23582)\t1\n", " (0, 20509)\t2\n", " (0, 26866)\t1\n", " (0, 6248)\t2\n", " (0, 42815)\t1\n", " (0, 29227)\t1\n", " (0, 25786)\t1\n", " (0, 14980)\t1\n", " (0, 37256)\t1\n", " (0, 10150)\t1\n", " (0, 18936)\t1\n", " (0, 7837)\t1\n", " (0, 7874)\t1\n", " (0, 20452)\t1\n", " (0, 2632)\t1\n", " (0, 14758)\t1\n" ] } ], "source": [ "print(feature_vector[0])" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "X_dense = feature_vector.todense()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10000, 47912)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_dense.shape" ] }, { "cell_type": "code", "execution_count": 16, "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": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "((8000, 47912), (2000, 47912))" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x_train.shape, x_test.shape" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "((8000,), (2000,))" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_train.shape, y_test.shape" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "np.matrix is not supported. Please convert to a numpy array with np.asarray. For more information see: https://numpy.org/doc/stable/reference/generated/numpy.matrix.html", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[19], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m clf \u001b[39m=\u001b[39m GaussianNB()\u001b[39m.\u001b[39;49mfit(x_train, y_train)\n", "File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/sklearn/naive_bayes.py:267\u001b[0m, in \u001b[0;36mGaussianNB.fit\u001b[0;34m(self, X, y, sample_weight)\u001b[0m\n\u001b[1;32m 265\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_validate_params()\n\u001b[1;32m 266\u001b[0m y \u001b[39m=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_validate_data(y\u001b[39m=\u001b[39my)\n\u001b[0;32m--> 267\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_partial_fit(\n\u001b[1;32m 268\u001b[0m X, y, np\u001b[39m.\u001b[39;49munique(y), _refit\u001b[39m=\u001b[39;49m\u001b[39mTrue\u001b[39;49;00m, sample_weight\u001b[39m=\u001b[39;49msample_weight\n\u001b[1;32m 269\u001b[0m )\n", "File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/sklearn/naive_bayes.py:428\u001b[0m, in \u001b[0;36mGaussianNB._partial_fit\u001b[0;34m(self, X, y, classes, _refit, sample_weight)\u001b[0m\n\u001b[1;32m 425\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mclasses_ \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[1;32m 427\u001b[0m first_call \u001b[39m=\u001b[39m _check_partial_fit_first_call(\u001b[39mself\u001b[39m, classes)\n\u001b[0;32m--> 428\u001b[0m X, y \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_validate_data(X, y, reset\u001b[39m=\u001b[39;49mfirst_call)\n\u001b[1;32m 429\u001b[0m \u001b[39mif\u001b[39;00m sample_weight \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 430\u001b[0m sample_weight \u001b[39m=\u001b[39m _check_sample_weight(sample_weight, X)\n", "File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/sklearn/base.py:584\u001b[0m, in \u001b[0;36mBaseEstimator._validate_data\u001b[0;34m(self, X, y, reset, validate_separately, **check_params)\u001b[0m\n\u001b[1;32m 582\u001b[0m y \u001b[39m=\u001b[39m check_array(y, input_name\u001b[39m=\u001b[39m\u001b[39m\"\u001b[39m\u001b[39my\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mcheck_y_params)\n\u001b[1;32m 583\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m--> 584\u001b[0m X, y \u001b[39m=\u001b[39m check_X_y(X, y, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mcheck_params)\n\u001b[1;32m 585\u001b[0m out \u001b[39m=\u001b[39m X, y\n\u001b[1;32m 587\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m no_val_X \u001b[39mand\u001b[39;00m check_params\u001b[39m.\u001b[39mget(\u001b[39m\"\u001b[39m\u001b[39mensure_2d\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39mTrue\u001b[39;00m):\n", "File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/sklearn/utils/validation.py:1106\u001b[0m, in \u001b[0;36mcheck_X_y\u001b[0;34m(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)\u001b[0m\n\u001b[1;32m 1101\u001b[0m estimator_name \u001b[39m=\u001b[39m _check_estimator_name(estimator)\n\u001b[1;32m 1102\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 1103\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m{\u001b[39;00mestimator_name\u001b[39m}\u001b[39;00m\u001b[39m requires y to be passed, but the target y is None\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1104\u001b[0m )\n\u001b[0;32m-> 1106\u001b[0m X \u001b[39m=\u001b[39m check_array(\n\u001b[1;32m 1107\u001b[0m X,\n\u001b[1;32m 1108\u001b[0m accept_sparse\u001b[39m=\u001b[39;49maccept_sparse,\n\u001b[1;32m 1109\u001b[0m accept_large_sparse\u001b[39m=\u001b[39;49maccept_large_sparse,\n\u001b[1;32m 1110\u001b[0m dtype\u001b[39m=\u001b[39;49mdtype,\n\u001b[1;32m 1111\u001b[0m order\u001b[39m=\u001b[39;49morder,\n\u001b[1;32m 1112\u001b[0m copy\u001b[39m=\u001b[39;49mcopy,\n\u001b[1;32m 1113\u001b[0m force_all_finite\u001b[39m=\u001b[39;49mforce_all_finite,\n\u001b[1;32m 1114\u001b[0m ensure_2d\u001b[39m=\u001b[39;49mensure_2d,\n\u001b[1;32m 1115\u001b[0m allow_nd\u001b[39m=\u001b[39;49mallow_nd,\n\u001b[1;32m 1116\u001b[0m ensure_min_samples\u001b[39m=\u001b[39;49mensure_min_samples,\n\u001b[1;32m 1117\u001b[0m ensure_min_features\u001b[39m=\u001b[39;49mensure_min_features,\n\u001b[1;32m 1118\u001b[0m estimator\u001b[39m=\u001b[39;49mestimator,\n\u001b[1;32m 1119\u001b[0m input_name\u001b[39m=\u001b[39;49m\u001b[39m\"\u001b[39;49m\u001b[39mX\u001b[39;49m\u001b[39m\"\u001b[39;49m,\n\u001b[1;32m 1120\u001b[0m )\n\u001b[1;32m 1122\u001b[0m y \u001b[39m=\u001b[39m _check_y(y, multi_output\u001b[39m=\u001b[39mmulti_output, y_numeric\u001b[39m=\u001b[39my_numeric, estimator\u001b[39m=\u001b[39mestimator)\n\u001b[1;32m 1124\u001b[0m check_consistent_length(X, y)\n", "File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/sklearn/utils/validation.py:737\u001b[0m, in \u001b[0;36mcheck_array\u001b[0;34m(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)\u001b[0m\n\u001b[1;32m 646\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"Input validation on an array, list, sparse matrix or similar.\u001b[39;00m\n\u001b[1;32m 647\u001b[0m \n\u001b[1;32m 648\u001b[0m \u001b[39mBy default, the input is checked to be a non-empty 2D array containing\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 734\u001b[0m \u001b[39m The converted and validated array.\u001b[39;00m\n\u001b[1;32m 735\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 736\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39misinstance\u001b[39m(array, np\u001b[39m.\u001b[39mmatrix):\n\u001b[0;32m--> 737\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mTypeError\u001b[39;00m(\n\u001b[1;32m 738\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mnp.matrix is not supported. Please convert to a numpy array with \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 739\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mnp.asarray. For more information see: \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 740\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mhttps://numpy.org/doc/stable/reference/generated/numpy.matrix.html\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 741\u001b[0m )\n\u001b[1;32m 743\u001b[0m xp, is_array_api \u001b[39m=\u001b[39m get_namespace(array)\n\u001b[1;32m 745\u001b[0m \u001b[39m# store reference to original array to check if copy is needed when\u001b[39;00m\n\u001b[1;32m 746\u001b[0m \u001b[39m# function returns\u001b[39;00m\n", "\u001b[0;31mTypeError\u001b[0m: np.matrix is not supported. Please convert to a numpy array with np.asarray. For more information see: https://numpy.org/doc/stable/reference/generated/numpy.matrix.html" ] } ], "source": [ "clf = GaussianNB().fit(x_train, y_train)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([ 5, 10, 4, ..., 5, 1, 14])" ] }, "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 : 1464\n", "accuracy_score : 0.732\n", "precision_score : 0.7480649828741391\n", "recall_score : 0.732\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.9.7" } }, "nbformat": 4, "nbformat_minor": 2 }