This commit is contained in:
shoney 2023-06-21 09:03:01 +00:00
parent b05aa0c251
commit 861fe965c0
32 changed files with 5 additions and 22308 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,658 +0,0 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tokenize text into words and sentences"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python pip intstall -U nltk"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.25.0\n"
]
}
],
"source": [
"import numpy\n",
"\n",
"print(numpy.__version__)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.8.1\n"
]
}
],
"source": [
"import nltk\n",
"\n",
"print(nltk.__version__)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Uses NLTK's recommended sentence tokenizer, the PunktSentenceTokenizer\n",
"#### Uses NLTK's recommended word tokenizer, the TreebankWordTokenizer and the PunktSentencetokenizer"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"from nltk.tokenize import word_tokenize\n",
"from nltk.tokenize import sent_tokenize"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package punkt to /home/shoney/nltk_data...\n",
"[nltk_data] Unzipping tokenizers/punkt.zip.\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('punkt')"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Does this tokenizer work?', 'These are two different sentences']\n"
]
}
],
"source": [
"sent_tokens = sent_tokenize('Does this tokenizer work? These are two different sentences')\n",
"\n",
"print(sent_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Does', 'this', 'tokenizer', 'work', '?']\n"
]
}
],
"source": [
"word_tokens = word_tokenize('Does this tokenizer work?')\n",
"\n",
"print(word_tokens)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Punkt tokenizer\n",
"\n",
"https://www.nltk.org/_modules/nltk/tokenize/punkt.html\n",
"http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.punkt\n",
"\n",
"A sentence tokenizer which uses an unsupervised algorithm to build a model for abbreviation words, collocations, and words that start sentences; and then uses that model to find sentence boundaries. This approach has been shown to work well for many European languages.\n",
"\n",
"It must be trained on a large collection of plaintext in the target language before it can be used.\n",
"\n",
"The NLTK data package includes a pre-trained Punkt tokenizer for English."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package punkt to /home/shoney/nltk_data...\n",
"[nltk_data] Package punkt is already up-to-date!\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('punkt')"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Does this tokenizer work?', 'These are two different sentences']\n"
]
}
],
"source": [
"sent_tokens = sent_tokenize('Does this tokenizer work? These are two different sentences')\n",
"\n",
"print(sent_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Does', 'this', 'tokenizer', 'work', '?']\n"
]
}
],
"source": [
"word_tokens = word_tokenize('Does this tokenizer work?')\n",
"\n",
"print(word_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['A', 'bird', 'in', 'hand', 'is', 'worth', 'two', 'in', 'the', 'bush', '.', 'Good', 'things', 'come', 'to', 'those', 'who', 'wait', '.', 'These', 'watches', 'cost', '$', '1500', '!', 'The', 'ball', 'is', 'in', 'your', 'court', '.', 'Mr.', 'Smith', 'Goes', 'to', 'Washington', 'Doogie', 'Howser', 'M.D', '.']\n"
]
}
],
"source": [
"text = \"A bird in hand is worth two in the bush. \" +\\\n",
" \"Good things come to those who wait. \" +\\\n",
" \"These watches cost $1500! \" +\\\n",
" \"The ball is in your court. \" +\\\n",
" \"Mr. Smith Goes to Washington \" +\\\n",
" \"Doogie Howser M.D.\"\n",
"\n",
"word_tokens = word_tokenize(text, language='english')\n",
"print(word_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"41"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(word_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['hand', 'is', 'worth', 'two', 'in']"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"word_tokens[3:8]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from nltk.tokenize.punkt import PunktSentenceTokenizer"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"pst = PunktSentenceTokenizer()"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['A bird in hand is worth two in the bush.', 'Good things come to those who wait.', 'These watches cost $1500!', 'The ball is in your court.', 'Mr.', 'Smith Goes to Washington Doogie Howser M.D.']\n"
]
}
],
"source": [
"sent_tokens = pst.tokenize(text)\n",
"\n",
"print(sent_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(0, 40), (41, 76), (77, 102), (103, 129), (130, 133), (134, 177)]\n"
]
}
],
"source": [
"span_tokens = pst.span_tokenize(text)\n",
"\n",
"print(list(span_tokens))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['A', 'bird', 'in', 'hand', 'is', 'worth', 'two', 'in', 'the', 'bush', '.'],\n",
" ['Good', 'things', 'come', 'to', 'those', 'who', 'wait', '.'],\n",
" ['These', 'watches', 'cost', '$', '1500', '!'],\n",
" ['The', 'ball', 'is', 'in', 'your', 'court', '.'],\n",
" ['Mr.'],\n",
" ['Smith', 'Goes', 'to', 'Washington', 'Doogie', 'Howser', 'M.D', '.']]"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentences = pst.sentences_from_tokens(word_tokens)\n",
"\n",
"list(sentences)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"from nltk.tokenize import WhitespaceTokenizer"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"wt = WhitespaceTokenizer()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['A', 'bird', 'in', 'hand', 'is', 'worth', 'two', 'in', 'the', 'bush.', 'Good', 'things', 'come', 'to', 'those', 'who', 'wait.', 'These', 'watches', 'cost', '$1500!', 'The', 'ball', 'is', 'in', 'your', 'court.', 'Mr.', 'Smith', 'Goes', 'to', 'Washington', 'Doogie', 'Howser', 'M.D.']\n"
]
}
],
"source": [
"word_tokens = wt.tokenize(text)\n",
"\n",
"print(word_tokens)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reading Local Files"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: '/datasets/biography.txt'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[24], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[39mwith\u001b[39;00m \u001b[39mopen\u001b[39;49m(\u001b[39m'\u001b[39;49m\u001b[39m/datasets/biography.txt\u001b[39;49m\u001b[39m'\u001b[39;49m, \u001b[39m'\u001b[39;49m\u001b[39mr\u001b[39;49m\u001b[39m'\u001b[39;49m) \u001b[39mas\u001b[39;00m f:\n\u001b[1;32m 2\u001b[0m file_contents \u001b[39m=\u001b[39m f\u001b[39m.\u001b[39mread()\n\u001b[1;32m 4\u001b[0m \u001b[39mprint\u001b[39m(file_contents)\n",
"File \u001b[0;32m~/dev/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py:284\u001b[0m, in \u001b[0;36m_modified_open\u001b[0;34m(file, *args, **kwargs)\u001b[0m\n\u001b[1;32m 277\u001b[0m \u001b[39mif\u001b[39;00m file \u001b[39min\u001b[39;00m {\u001b[39m0\u001b[39m, \u001b[39m1\u001b[39m, \u001b[39m2\u001b[39m}:\n\u001b[1;32m 278\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 279\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mIPython won\u001b[39m\u001b[39m'\u001b[39m\u001b[39mt let you open fd=\u001b[39m\u001b[39m{\u001b[39;00mfile\u001b[39m}\u001b[39;00m\u001b[39m by default \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 280\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 281\u001b[0m \u001b[39m\"\u001b[39m\u001b[39myou can use builtins\u001b[39m\u001b[39m'\u001b[39m\u001b[39m open.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 282\u001b[0m )\n\u001b[0;32m--> 284\u001b[0m \u001b[39mreturn\u001b[39;00m io_open(file, \u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '/datasets/biography.txt'"
]
}
],
"source": [
"with open('/datasets/biography.txt', 'r') as f:\n",
" file_contents = f.read()\n",
"\n",
"print(file_contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"word_tokens = word_tokenize(file_contents)\n",
"\n",
"print(word_tokens)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Frequency distributions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nltk.probability import FreqDist"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist = FreqDist(word_tokens)\n",
"\n",
"print(freq_dist)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist.most_common(20)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Return the frequency of a given sample. The frequency of a sample is defined as the count of that sample divided by the total number of sample outcomes that have been recorded by this FreqDist. The count of a sample is defined as the number of times that sample outcome was recorded by this FreqDist. Frequencies are always real numbers in the range [0, 1]."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist.freq('the')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist.freq('exposure')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"fig, ax = plt.subplots(figsize=(12, 8))\n",
"\n",
"freq_dist.plot(20, cumulative=False)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"file_contents = file_contents.lower()\n",
"\n",
"word_tokens = wt.tokenize(file_contents)\n",
"\n",
"print(word_tokens)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nltk.download('stopwords')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nltk.corpus import stopwords\n",
"\n",
"stop_words = set(stopwords.words('english'))\n",
"stop_words.update(['.', ',', 'The'])\n",
"\n",
"print(stop_words)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"filtered_words = []\n",
"\n",
"for w in word_tokens:\n",
" if w not in stop_words:\n",
" filtered_words.append(w)\n",
" \n",
"print(filtered_words)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist = FreqDist(filtered_words)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"freq_dist.most_common(20)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(12, 8))\n",
"\n",
"freq_dist.plot(20, cumulative=False)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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
}

View file

@ -1,744 +0,0 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Vectorize text as a bag-of-words"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.20.3\n"
]
}
],
"source": [
"import sklearn\n",
"\n",
"print(sklearn.__version__)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import CountVectorizer"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"train_text = [\"A bird in hand is worth two in the bush.\",\n",
" \"Good things come to those who wait.\",\n",
" \"These watches cost $1500! \",\n",
" \"There are other fish in the sea.\",\n",
" \"The ball is in your court.\",\n",
" \"Mr. Smith Goes to Washington \",\n",
" \"Doogie Howser M.D.\"]\n",
"\n",
"count_vectorizer = CountVectorizer()"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n",
" dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n",
" lowercase=True, max_df=1.0, max_features=None, min_df=1,\n",
" ngram_range=(1, 1), preprocessor=None, stop_words=None,\n",
" strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n",
" tokenizer=None, vocabulary=None)"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.fit(train_text)"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['1500',\n",
" 'are',\n",
" 'ball',\n",
" 'bird',\n",
" 'bush',\n",
" 'come',\n",
" 'cost',\n",
" 'court',\n",
" 'doogie',\n",
" 'fish',\n",
" 'goes',\n",
" 'good',\n",
" 'hand',\n",
" 'howser',\n",
" 'in',\n",
" 'is',\n",
" 'mr',\n",
" 'other',\n",
" 'sea',\n",
" 'smith',\n",
" 'the',\n",
" 'there',\n",
" 'these',\n",
" 'things',\n",
" 'those',\n",
" 'to',\n",
" 'two',\n",
" 'wait',\n",
" 'washington',\n",
" 'watches',\n",
" 'who',\n",
" 'worth',\n",
" 'your']"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.get_feature_names()"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"count_vectorizer.get_stop_words()"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'bird': 3,\n",
" 'in': 14,\n",
" 'hand': 12,\n",
" 'is': 15,\n",
" 'worth': 31,\n",
" 'two': 26,\n",
" 'the': 20,\n",
" 'bush': 4,\n",
" 'good': 11,\n",
" 'things': 23,\n",
" 'come': 5,\n",
" 'to': 25,\n",
" 'those': 24,\n",
" 'who': 30,\n",
" 'wait': 27,\n",
" 'these': 22,\n",
" 'watches': 29,\n",
" 'cost': 6,\n",
" '1500': 0,\n",
" 'there': 21,\n",
" 'are': 1,\n",
" 'other': 17,\n",
" 'fish': 9,\n",
" 'sea': 18,\n",
" 'ball': 2,\n",
" 'your': 32,\n",
" 'court': 7,\n",
" 'mr': 16,\n",
" 'smith': 19,\n",
" 'goes': 10,\n",
" 'washington': 28,\n",
" 'doogie': 8,\n",
" 'howser': 13}"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.vocabulary_"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"28"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.vocabulary_.get('things')"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['A bird in hand is worth two in the bush.',\n",
" 'Good things come to those who wait.',\n",
" 'These watches cost $1500! ',\n",
" 'There are other fish in the sea.',\n",
" 'The ball is in your court.',\n",
" 'Mr. Smith Goes to Washington ',\n",
" 'Doogie Howser M.D.']"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_text"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"transformed_vector = count_vectorizer.transform(train_text)"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(7, 33)\n"
]
}
],
"source": [
"print(transformed_vector.shape)"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 0 0 1 1 0 0 0 0 0 0 0 1 0 2 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0]\n",
" [0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 0 1 0 0]\n",
" [1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0]\n",
" [0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0]\n",
" [0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1]\n",
" [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0]\n",
" [0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]\n"
]
}
],
"source": [
"print(transformed_vector.toarray())"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_text = [\"Every cloud has a silver lining.\"]\n",
"\n",
"count_vectorizer.transform(test_text).toarray()"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CountVectorizer(analyzer='word', binary=False, decode_error='strict',\n",
" dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',\n",
" lowercase=True, max_df=1.0, max_features=None, min_df=1,\n",
" ngram_range=(1, 1), preprocessor=None, stop_words=None,\n",
" strip_accents=None, token_pattern='(?u)\\\\b\\\\w\\\\w+\\\\b',\n",
" tokenizer=None, vocabulary=None)"
]
},
"execution_count": 79,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.fit(train_text + test_text)"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'bird': 3, 'in': 17, 'hand': 14, 'is': 18, 'worth': 36, 'two': 31, 'the': 25, 'bush': 4, 'good': 13, 'things': 28, 'come': 6, 'to': 30, 'those': 29, 'who': 35, 'wait': 32, 'these': 27, 'watches': 34, 'cost': 7, '1500': 0, 'there': 26, 'are': 1, 'other': 21, 'fish': 11, 'sea': 22, 'ball': 2, 'your': 37, 'court': 8, 'mr': 20, 'smith': 24, 'goes': 12, 'washington': 33, 'doogie': 9, 'howser': 16, 'every': 10, 'cloud': 5, 'has': 15, 'silver': 23, 'lining': 19}\n"
]
}
],
"source": [
"print(count_vectorizer.vocabulary_)"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,\n",
" 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])"
]
},
"execution_count": 81,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.transform(test_text).toarray()"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<3x38 sparse matrix of type '<class 'numpy.int64'>'\n",
"\twith 9 stored elements in Compressed Sparse Row format>"
]
},
"execution_count": 86,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = [\"That bird is sitting in the bush and this bird is in hand.\",\n",
" \"Wait and then walk\",\n",
" \"Watches are cool \"]\n",
"\n",
"transformed_vector = count_vectorizer.transform(text)\n",
"\n",
"transformed_vector"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 3)\t2\n",
" (0, 4)\t1\n",
" (0, 14)\t1\n",
" (0, 17)\t2\n",
" (0, 18)\t2\n",
" (0, 25)\t1\n",
" (1, 32)\t1\n",
" (2, 1)\t1\n",
" (2, 34)\t1\n"
]
}
],
"source": [
"print(transformed_vector)"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(3, 38)"
]
},
"execution_count": 88,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"transformed_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 0 0 2 1 0 0 0 0 0 0 0 0 0 1 0 0 2 2 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0\n",
" 0 0]\n",
" [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0\n",
" 0 0]\n",
" [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0\n",
" 0 0]]\n"
]
}
],
"source": [
"print(transformed_vector.toarray())"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### CountVectorizer on text file"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Marie Curie was a Polish-born physicist and chemist and one of the most famous scientists of her time.\n",
"Together with her husband Pierre, she was awarded the Nobel Prize in 1903, and she went on to win another in 1911.\n",
"Marie Sklodowska was born in Warsaw on 7 November 1867, the daughter of a teacher.\n",
"In 1891, she went to Paris to study physics and mathematics at the Sorbonne where she met Pierre Curie, professor of the School of Physics.\n",
"They were married in 1895.\n",
"The Curies worked together investigating radioactivity, building on the work of the German physicist Roentgen and the French physicist Becquerel.\n",
"In July 1898, the Curies announced the discovery of a new chemical element, polonium.\n",
"At the end of the year, they announced the discovery of another, radium.\n",
"The Curies, along with Becquerel, were awarded the Nobel Prize for Physics in 1903.\n",
"Pierre's life was cut short in 1906 when he was knocked down and killed by a carriage.\n",
"Marie took over his teaching post, becoming the first woman to teach at the Sorbonne, and devoted herself to continuing the work that they had begun together.\n",
"She received a second Nobel Prize, for Chemistry, in 1911.\n",
"The Curie's research was crucial in the development of x-rays in surgery.\n",
"During World War One Curie helped to equip ambulances with x-ray equipment, which she herself drove to the front lines.\n",
"The International Red Cross made her head of its radiological service and she held training courses for medical orderlies and doctors in the new techniques.\n",
"Despite her success, Marie continued to face great opposition from male scientists in France, and she never received significant financial benefits from her work.\n",
"By the late 1920s her health was beginning to deteriorate.\n",
"She died on 4 July 1934 from leukaemia, caused by exposure to high-energy radiation from her research.\n",
"The Curies' eldest daughter Irene was herself a scientist and winner of the Nobel Prize for Chemistry.\n"
]
}
],
"source": [
"with open('./datasets/biography.txt', 'r') as f:\n",
" file_contents = f.read()\n",
"\n",
"print(file_contents)"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Marie Curie was a Polish-born physicist and chemist and one of the most famous scientists of her time.', 'Together with her husband Pierre, she was awarded the Nobel Prize in 1903, and she went on to win another in 1911.', 'Marie Sklodowska was born in Warsaw on 7 November 1867, the daughter of a teacher.', 'In 1891, she went to Paris to study physics and mathematics at the Sorbonne where she met Pierre Curie, professor of the School of Physics.', 'They were married in 1895.', 'The Curies worked together investigating radioactivity, building on the work of the German physicist Roentgen and the French physicist Becquerel.', 'In July 1898, the Curies announced the discovery of a new chemical element, polonium.', 'At the end of the year, they announced the discovery of another, radium.', 'The Curies, along with Becquerel, were awarded the Nobel Prize for Physics in 1903.', \"Pierre's life was cut short in 1906 when he was knocked down and killed by a carriage.\", 'Marie took over his teaching post, becoming the first woman to teach at the Sorbonne, and devoted herself to continuing the work that they had begun together.', 'She received a second Nobel Prize, for Chemistry, in 1911.', \"The Curie's research was crucial in the development of x-rays in surgery.\", 'During World War One Curie helped to equip ambulances with x-ray equipment, which she herself drove to the front lines.', 'The International Red Cross made her head of its radiological service and she held training courses for medical orderlies and doctors in the new techniques.', 'Despite her success, Marie continued to face great opposition from male scientists in France, and she never received significant financial benefits from her work.', 'By the late 1920s her health was beginning to deteriorate.', 'She died on 4 July 1934 from leukaemia, caused by exposure to high-energy radiation from her research.', \"The Curies' eldest daughter Irene was herself a scientist and winner of the Nobel Prize for Chemistry.\"]\n"
]
}
],
"source": [
"sentences = file_contents.split('\\n')\n",
" \n",
"print(sentences)"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(19, 167)"
]
},
"execution_count": 97,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"transformed_vector = count_vectorizer.fit_transform(sentences)\n",
"\n",
"transformed_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 146)\t1\n",
" (0, 72)\t1\n",
" (0, 128)\t1\n",
" (0, 56)\t1\n",
" (0, 96)\t1\n",
" (0, 144)\t1\n",
" (0, 101)\t2\n",
" (0, 103)\t1\n",
" (0, 27)\t1\n",
" (0, 11)\t2\n",
" (0, 108)\t1\n",
" (0, 21)\t1\n",
" (0, 111)\t1\n",
" (0, 153)\t1\n",
" (0, 34)\t1\n",
" (0, 91)\t1\n",
" (1, 6)\t1\n",
" (1, 13)\t1\n",
" (1, 159)\t1\n",
" (1, 147)\t1\n",
" (1, 102)\t1\n",
" (1, 154)\t1\n",
" (1, 4)\t1\n",
" (1, 77)\t2\n",
" (1, 114)\t1\n",
" :\t:\n",
" (17, 8)\t1\n",
" (17, 42)\t1\n",
" (17, 62)\t2\n",
" (17, 124)\t1\n",
" (17, 23)\t1\n",
" (17, 82)\t1\n",
" (17, 147)\t1\n",
" (17, 102)\t1\n",
" (17, 131)\t1\n",
" (17, 72)\t1\n",
" (18, 160)\t1\n",
" (18, 127)\t1\n",
" (18, 80)\t1\n",
" (18, 48)\t1\n",
" (18, 28)\t1\n",
" (18, 73)\t1\n",
" (18, 59)\t1\n",
" (18, 35)\t1\n",
" (18, 37)\t1\n",
" (18, 114)\t1\n",
" (18, 99)\t1\n",
" (18, 144)\t2\n",
" (18, 101)\t1\n",
" (18, 11)\t1\n",
" (18, 153)\t1\n"
]
}
],
"source": [
"print(transformed_vector)"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'marie': 91, 'curie': 34, 'was': 153, 'polish': 111, 'born': 21, 'physicist': 108, 'and': 11, 'chemist': 27, 'one': 103, 'of': 101, 'the': 144, 'most': 96, 'famous': 56, 'scientists': 128, 'her': 72, 'time': 146, 'together': 148, 'with': 161, 'husband': 76, 'pierre': 110, 'she': 131, 'awarded': 15, 'nobel': 99, 'prize': 114, 'in': 77, '1903': 4, 'went': 154, 'on': 102, 'to': 147, 'win': 159, 'another': 13, '1911': 6, 'sklodowska': 134, 'warsaw': 152, 'november': 100, '1867': 0, 'daughter': 37, 'teacher': 140, '1891': 1, 'paris': 107, 'study': 136, 'physics': 109, 'mathematics': 93, 'at': 14, 'sorbonne': 135, 'where': 157, 'met': 95, 'professor': 115, 'school': 126, 'they': 145, 'were': 155, 'married': 92, '1895': 2, 'curies': 35, 'worked': 164, 'investigating': 79, 'radioactivity': 117, 'building': 22, 'work': 163, 'german': 64, 'roentgen': 125, 'french': 61, 'becquerel': 17, 'july': 82, '1898': 3, 'announced': 12, 'discovery': 43, 'new': 98, 'chemical': 26, 'element': 49, 'polonium': 112, 'end': 50, 'year': 166, 'radium': 119, 'along': 9, 'for': 59, 'life': 87, 'cut': 36, 'short': 132, '1906': 5, 'when': 156, 'he': 67, 'knocked': 84, 'down': 45, 'killed': 83, 'by': 23, 'carriage': 24, 'took': 149, 'over': 106, 'his': 75, 'teaching': 141, 'post': 113, 'becoming': 16, 'first': 58, 'woman': 162, 'teach': 139, 'devoted': 41, 'herself': 73, 'continuing': 30, 'that': 143, 'had': 66, 'begun': 19, 'received': 122, 'second': 129, 'chemistry': 28, 'research': 124, 'crucial': 33, 'development': 40, 'rays': 121, 'surgery': 138, 'during': 47, 'world': 165, 'war': 151, 'helped': 71, 'equip': 52, 'ambulances': 10, 'ray': 120, 'equipment': 53, 'which': 158, 'drove': 46, 'front': 63, 'lines': 88, 'international': 78, 'red': 123, 'cross': 32, 'made': 89, 'head': 68, 'its': 81, 'radiological': 118, 'service': 130, 'held': 70, 'training': 150, 'courses': 31, 'medical': 94, 'orderlies': 105, 'doctors': 44, 'techniques': 142, 'despite': 38, 'success': 137, 'continued': 29, 'face': 55, 'great': 65, 'opposition': 104, 'from': 62, 'male': 90, 'france': 60, 'never': 97, 'significant': 133, 'financial': 57, 'benefits': 20, 'late': 85, '1920s': 7, 'health': 69, 'beginning': 18, 'deteriorate': 39, 'died': 42, '1934': 8, 'leukaemia': 86, 'caused': 25, 'exposure': 54, 'high': 74, 'energy': 51, 'radiation': 116, 'eldest': 48, 'irene': 80, 'scientist': 127, 'winner': 160}\n"
]
}
],
"source": [
"print(count_vectorizer.vocabulary_)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"We lost:\n",
"\n",
"* The meaning of text corpus\n",
"* The ordering of the words"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[array(['time', 'her', 'scientists', 'famous', 'most', 'the', 'of', 'one',\n",
" 'chemist', 'and', 'physicist', 'born', 'polish', 'was', 'curie',\n",
" 'marie'], dtype='<U13'),\n",
" array(['1911', 'another', 'win', 'to', 'on', 'went', '1903', 'in',\n",
" 'prize', 'nobel', 'awarded', 'she', 'pierre', 'husband', 'with',\n",
" 'together', 'her', 'the', 'and', 'was'], dtype='<U13'),\n",
" array(['teacher', 'daughter', '1867', 'november', 'warsaw', 'sklodowska',\n",
" 'on', 'in', 'the', 'of', 'born', 'was', 'marie'], dtype='<U13'),\n",
" array(['school', 'professor', 'met', 'where', 'sorbonne', 'at',\n",
" 'mathematics', 'physics', 'study', 'paris', '1891', 'to', 'went',\n",
" 'in', 'she', 'pierre', 'the', 'of', 'and', 'curie'], dtype='<U13'),\n",
" array(['1895', 'married', 'were', 'they', 'in'], dtype='<U13'),\n",
" array(['becquerel', 'french', 'roentgen', 'german', 'work', 'building',\n",
" 'radioactivity', 'investigating', 'worked', 'curies', 'on',\n",
" 'together', 'the', 'of', 'and', 'physicist'], dtype='<U13'),\n",
" array(['polonium', 'element', 'chemical', 'new', 'discovery', 'announced',\n",
" '1898', 'july', 'curies', 'in', 'the', 'of'], dtype='<U13'),\n",
" array(['radium', 'year', 'end', 'discovery', 'announced', 'they', 'at',\n",
" 'another', 'the', 'of'], dtype='<U13'),\n",
" array(['for', 'along', 'becquerel', 'curies', 'were', 'physics', '1903',\n",
" 'in', 'prize', 'nobel', 'awarded', 'with', 'the'], dtype='<U13'),\n",
" array(['carriage', 'by', 'killed', 'down', 'knocked', 'he', 'when',\n",
" '1906', 'short', 'cut', 'life', 'in', 'pierre', 'and', 'was'],\n",
" dtype='<U13'),\n",
" array(['begun', 'had', 'that', 'continuing', 'herself', 'devoted',\n",
" 'teach', 'woman', 'first', 'becoming', 'post', 'teaching', 'his',\n",
" 'over', 'took', 'work', 'they', 'sorbonne', 'at', 'to', 'together',\n",
" 'the', 'and', 'marie'], dtype='<U13'),\n",
" array(['chemistry', 'second', 'received', 'for', '1911', 'in', 'prize',\n",
" 'nobel', 'she'], dtype='<U13'),\n",
" array(['surgery', 'rays', 'development', 'crucial', 'research', 'in',\n",
" 'the', 'of', 'was', 'curie'], dtype='<U13'),\n",
" array(['lines', 'front', 'drove', 'which', 'equipment', 'ray',\n",
" 'ambulances', 'equip', 'helped', 'war', 'world', 'during',\n",
" 'herself', 'to', 'she', 'with', 'the', 'one', 'curie'],\n",
" dtype='<U13'),\n",
" array(['techniques', 'doctors', 'orderlies', 'medical', 'courses',\n",
" 'training', 'held', 'service', 'radiological', 'its', 'head',\n",
" 'made', 'cross', 'red', 'international', 'for', 'new', 'in', 'she',\n",
" 'her', 'the', 'of', 'and'], dtype='<U13'),\n",
" array(['benefits', 'financial', 'significant', 'never', 'france', 'male',\n",
" 'from', 'opposition', 'great', 'face', 'continued', 'success',\n",
" 'despite', 'received', 'work', 'to', 'in', 'she', 'her',\n",
" 'scientists', 'and', 'marie'], dtype='<U13'),\n",
" array(['deteriorate', 'beginning', 'health', '1920s', 'late', 'by', 'to',\n",
" 'her', 'the', 'was'], dtype='<U13'),\n",
" array(['radiation', 'energy', 'high', 'exposure', 'caused', 'leukaemia',\n",
" '1934', 'died', 'from', 'research', 'by', 'july', 'to', 'on',\n",
" 'she', 'her'], dtype='<U13'),\n",
" array(['winner', 'scientist', 'irene', 'eldest', 'chemistry', 'herself',\n",
" 'for', 'curies', 'daughter', 'prize', 'nobel', 'the', 'of', 'and',\n",
" 'was'], dtype='<U13')]"
]
},
"execution_count": 101,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.inverse_transform(transformed_vector)"
]
}
],
"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.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

File diff suppressed because one or more lines are too long

View file

@ -1,693 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<b>TfidfTransformer</b> :\n",
"\n",
"* Transform a count matrix to a normalized tf or tf-idf representation\n",
"* Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification.\n",
"\n",
"https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#sklearn.feature_extraction.text.TfidfTransformer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* A <b>Term Frequency</b> is a count of how many times a word occurs in a given document (synonymous with bag of words).\n",
"* The <b>Inverse Document Frequency</b> is the the number of times a word occurs in a corpus of documents."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first step is to create our training and testing document set and computing the term frequency matrix\n",
"\n",
"https://scikit-learn.org/stable/modules/feature_extraction.html#tfidf-term-weighting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating a count vector\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import CountVectorizer\n",
"\n",
"train_text = [\"A bird in hand is worth two in the bush.\",\n",
" \"Good things come to those who wait.\",\n",
" \"These watches cost $1500! \",\n",
" \"There are other fish in the sea.\",\n",
" \"The ball is in your court.\",\n",
" \"Mr. Smith Goes to Washington \",\n",
" \"Doogie Howser M.D.\"]"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"count_vectorizer = CountVectorizer()\n",
"\n",
"frequency_term_matrix = count_vectorizer.fit_transform(train_text)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"33"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(count_vectorizer.vocabulary_)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(7, 33)"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequency_term_matrix.shape"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 0, 0, 0, 0, 1, 0,\n",
" 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],\n",
" [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0],\n",
" [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n",
" [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n",
" [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0,\n",
" 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64)"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequency_term_matrix.toarray()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Building the tf-idf matrix\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import TfidfTransformer\n",
"\n",
"tfidf_transformer = TfidfTransformer()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(7, 33)"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vector1 = tfidf_transformer.fit_transform(frequency_term_matrix)\n",
"\n",
"tfidf_vector1.shape"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0. , 0. , 0. , 0.34908308, 0.34908308,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.34908308, 0. , 0.49536976,\n",
" 0.28976893, 0. , 0. , 0. , 0. ,\n",
" 0.24768488, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.34908308, 0. , 0. , 0. ,\n",
" 0. , 0.34908308, 0. ],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0.38665001, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.38665001, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0.38665001, 0.38665001,\n",
" 0.32095271, 0. , 0.38665001, 0. , 0. ,\n",
" 0.38665001, 0. , 0. ],\n",
" [0.5 , 0. , 0. , 0. , 0. ,\n",
" 0. , 0.5 , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.5 , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.5 ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0.40801493, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.40801493,\n",
" 0. , 0. , 0. , 0. , 0.28949879,\n",
" 0. , 0. , 0.40801493, 0.40801493, 0. ,\n",
" 0.28949879, 0.40801493, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0. , 0.46146654, 0. , 0. ,\n",
" 0. , 0. , 0.46146654, 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.3274243 ,\n",
" 0.38305686, 0. , 0. , 0. , 0. ,\n",
" 0.3274243 , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.46146654],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0.46180424, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.46180424, 0. , 0. , 0.46180424,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0.38333718, 0. , 0. , 0.46180424, 0. ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0.70710678, 0. ,\n",
" 0. , 0. , 0. , 0.70710678, 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. ]])"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vector1.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0. 0. 0. 0.34908308 0.34908308 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0.34908308 0. 0.49536976 0.28976893 0. 0.\n",
" 0. 0. 0.24768488 0. 0. 0.\n",
" 0. 0. 0.34908308 0. 0. 0.\n",
" 0. 0.34908308 0. ]\n",
" [0. 0. 0. 0. 0. 0.38665001\n",
" 0. 0. 0. 0. 0. 0.38665001\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0.38665001\n",
" 0.38665001 0.32095271 0. 0.38665001 0. 0.\n",
" 0.38665001 0. 0. ]\n",
" [0.5 0. 0. 0. 0. 0.\n",
" 0.5 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0.5 0.\n",
" 0. 0. 0. 0. 0. 0.5\n",
" 0. 0. 0. ]\n",
" [0. 0.40801493 0. 0. 0. 0.\n",
" 0. 0. 0. 0.40801493 0. 0.\n",
" 0. 0. 0.28949879 0. 0. 0.40801493\n",
" 0.40801493 0. 0.28949879 0.40801493 0. 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. ]\n",
" [0. 0. 0.46146654 0. 0. 0.\n",
" 0. 0.46146654 0. 0. 0. 0.\n",
" 0. 0. 0.3274243 0.38305686 0. 0.\n",
" 0. 0. 0.3274243 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0.46146654]\n",
" [0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0.46180424 0.\n",
" 0. 0. 0. 0. 0.46180424 0.\n",
" 0. 0.46180424 0. 0. 0. 0.\n",
" 0. 0.38333718 0. 0. 0.46180424 0.\n",
" 0. 0. 0. ]\n",
" [0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0.70710678 0. 0. 0.\n",
" 0. 0.70710678 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. ]]\n"
]
}
],
"source": [
"print(tfidf_vector1.toarray())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TfidfVectorizer = CountVectorizer + TfidfTransformer"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"\n",
"tfidf_vectorizer = TfidfVectorizer()"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'bird': 3,\n",
" 'in': 14,\n",
" 'hand': 12,\n",
" 'is': 15,\n",
" 'worth': 31,\n",
" 'two': 26,\n",
" 'the': 20,\n",
" 'bush': 4,\n",
" 'good': 11,\n",
" 'things': 23,\n",
" 'come': 5,\n",
" 'to': 25,\n",
" 'those': 24,\n",
" 'who': 30,\n",
" 'wait': 27,\n",
" 'these': 22,\n",
" 'watches': 29,\n",
" 'cost': 6,\n",
" '1500': 0,\n",
" 'there': 21,\n",
" 'are': 1,\n",
" 'other': 17,\n",
" 'fish': 9,\n",
" 'sea': 18,\n",
" 'ball': 2,\n",
" 'your': 32,\n",
" 'court': 7,\n",
" 'mr': 16,\n",
" 'smith': 19,\n",
" 'goes': 10,\n",
" 'washington': 28,\n",
" 'doogie': 8,\n",
" 'howser': 13}"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vector2 = tfidf_vectorizer.fit_transform(train_text)\n",
"\n",
"tfidf_vectorizer.vocabulary_"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(7, 33)"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vector2.shape"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2.38629436, 2.38629436, 2.38629436, 2.38629436, 2.38629436,\n",
" 2.38629436, 2.38629436, 2.38629436, 2.38629436, 2.38629436,\n",
" 2.38629436, 2.38629436, 2.38629436, 2.38629436, 1.69314718,\n",
" 1.98082925, 2.38629436, 2.38629436, 2.38629436, 2.38629436,\n",
" 1.69314718, 2.38629436, 2.38629436, 2.38629436, 2.38629436,\n",
" 1.98082925, 2.38629436, 2.38629436, 2.38629436, 2.38629436,\n",
" 2.38629436, 2.38629436, 2.38629436])"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vectorizer.idf_"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'1500': 2.386294361119891,\n",
" 'are': 2.386294361119891,\n",
" 'ball': 2.386294361119891,\n",
" 'bird': 2.386294361119891,\n",
" 'bush': 2.386294361119891,\n",
" 'come': 2.386294361119891,\n",
" 'cost': 2.386294361119891,\n",
" 'court': 2.386294361119891,\n",
" 'doogie': 2.386294361119891,\n",
" 'fish': 2.386294361119891,\n",
" 'goes': 2.386294361119891,\n",
" 'good': 2.386294361119891,\n",
" 'hand': 2.386294361119891,\n",
" 'howser': 2.386294361119891,\n",
" 'in': 1.6931471805599454,\n",
" 'is': 1.9808292530117262,\n",
" 'mr': 2.386294361119891,\n",
" 'other': 2.386294361119891,\n",
" 'sea': 2.386294361119891,\n",
" 'smith': 2.386294361119891,\n",
" 'the': 1.6931471805599454,\n",
" 'there': 2.386294361119891,\n",
" 'these': 2.386294361119891,\n",
" 'things': 2.386294361119891,\n",
" 'those': 2.386294361119891,\n",
" 'to': 1.9808292530117262,\n",
" 'two': 2.386294361119891,\n",
" 'wait': 2.386294361119891,\n",
" 'washington': 2.386294361119891,\n",
" 'watches': 2.386294361119891,\n",
" 'who': 2.386294361119891,\n",
" 'worth': 2.386294361119891,\n",
" 'your': 2.386294361119891}"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dict(zip(tfidf_vectorizer.get_feature_names(), tfidf_vectorizer.idf_))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Final scorings of each word from the other words in the vocabulary.\n",
"* The scores are normalized to values between 0 and 1"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0. , 0. , 0. , 0.34908308, 0.34908308,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.34908308, 0. , 0.49536976,\n",
" 0.28976893, 0. , 0. , 0. , 0. ,\n",
" 0.24768488, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.34908308, 0. , 0. , 0. ,\n",
" 0. , 0.34908308, 0. ],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0.38665001, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.38665001, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0.38665001, 0.38665001,\n",
" 0.32095271, 0. , 0.38665001, 0. , 0. ,\n",
" 0.38665001, 0. , 0. ],\n",
" [0.5 , 0. , 0. , 0. , 0. ,\n",
" 0. , 0.5 , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.5 , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.5 ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0.40801493, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.40801493,\n",
" 0. , 0. , 0. , 0. , 0.28949879,\n",
" 0. , 0. , 0.40801493, 0.40801493, 0. ,\n",
" 0.28949879, 0.40801493, 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0. , 0.46146654, 0. , 0. ,\n",
" 0. , 0. , 0.46146654, 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0.3274243 ,\n",
" 0.38305686, 0. , 0. , 0. , 0. ,\n",
" 0.3274243 , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0.46146654],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0.46180424, 0. , 0. , 0. , 0. ,\n",
" 0. , 0.46180424, 0. , 0. , 0.46180424,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0.38333718, 0. , 0. , 0.46180424, 0. ,\n",
" 0. , 0. , 0. ],\n",
" [0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0.70710678, 0. ,\n",
" 0. , 0. , 0. , 0.70710678, 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. , 0. , 0. ,\n",
" 0. , 0. , 0. ]])"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vector2.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 3)\t0.3490830767264469\n",
" (0, 14)\t0.49536975552604884\n",
" (0, 12)\t0.3490830767264469\n",
" (0, 15)\t0.2897689326921819\n",
" (0, 31)\t0.3490830767264469\n",
" (0, 26)\t0.3490830767264469\n",
" (0, 20)\t0.24768487776302442\n",
" (0, 4)\t0.3490830767264469\n",
" (1, 11)\t0.386650005027498\n",
" (1, 23)\t0.386650005027498\n",
" (1, 5)\t0.386650005027498\n",
" (1, 25)\t0.32095270940344806\n",
" (1, 24)\t0.386650005027498\n",
" (1, 30)\t0.386650005027498\n",
" (1, 27)\t0.386650005027498\n",
" (2, 22)\t0.5\n",
" (2, 29)\t0.5\n",
" (2, 6)\t0.5\n",
" (2, 0)\t0.5\n",
" (3, 14)\t0.2894987873064995\n",
" (3, 20)\t0.2894987873064995\n",
" (3, 21)\t0.40801492725049476\n",
" (3, 1)\t0.40801492725049476\n",
" (3, 17)\t0.40801492725049476\n",
" (3, 9)\t0.40801492725049476\n",
" (3, 18)\t0.40801492725049476\n",
" (4, 14)\t0.3274243027464032\n",
" (4, 15)\t0.38305685676572565\n",
" (4, 20)\t0.3274243027464032\n",
" (4, 2)\t0.4614665377636916\n",
" (4, 32)\t0.4614665377636916\n",
" (4, 7)\t0.4614665377636916\n",
" (5, 25)\t0.38333717539523177\n",
" (5, 16)\t0.4618042361109319\n",
" (5, 19)\t0.4618042361109319\n",
" (5, 10)\t0.4618042361109319\n",
" (5, 28)\t0.4618042361109319\n",
" (6, 8)\t0.7071067811865476\n",
" (6, 13)\t0.7071067811865476\n"
]
}
],
"source": [
"print(tfidf_vector2)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" (0, 31)\t0.34908307672644684\n",
" (0, 26)\t0.34908307672644684\n",
" (0, 20)\t0.2476848777630244\n",
" (0, 15)\t0.2897689326921819\n",
" (0, 14)\t0.4953697555260488\n",
" (0, 12)\t0.34908307672644684\n",
" (0, 4)\t0.34908307672644684\n",
" (0, 3)\t0.34908307672644684\n",
" (1, 30)\t0.386650005027498\n",
" (1, 27)\t0.386650005027498\n",
" (1, 25)\t0.32095270940344806\n",
" (1, 24)\t0.386650005027498\n",
" (1, 23)\t0.386650005027498\n",
" (1, 11)\t0.386650005027498\n",
" (1, 5)\t0.386650005027498\n",
" (2, 29)\t0.5\n",
" (2, 22)\t0.5\n",
" (2, 6)\t0.5\n",
" (2, 0)\t0.5\n",
" (3, 21)\t0.40801492725049476\n",
" (3, 20)\t0.2894987873064995\n",
" (3, 18)\t0.40801492725049476\n",
" (3, 17)\t0.40801492725049476\n",
" (3, 14)\t0.2894987873064995\n",
" (3, 9)\t0.40801492725049476\n",
" (3, 1)\t0.40801492725049476\n",
" (4, 32)\t0.4614665377636916\n",
" (4, 20)\t0.3274243027464032\n",
" (4, 15)\t0.38305685676572565\n",
" (4, 14)\t0.3274243027464032\n",
" (4, 7)\t0.4614665377636916\n",
" (4, 2)\t0.4614665377636916\n",
" (5, 28)\t0.4618042361109319\n",
" (5, 25)\t0.38333717539523177\n",
" (5, 19)\t0.4618042361109319\n",
" (5, 16)\t0.4618042361109319\n",
" (5, 10)\t0.4618042361109319\n",
" (6, 13)\t0.7071067811865476\n",
" (6, 8)\t0.7071067811865476\n"
]
}
],
"source": [
"print(tfidf_vector1)"
]
},
{
"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
}

File diff suppressed because one or more lines are too long

View file

@ -1,530 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lemmatizing Words Using WordNet\n",
"* Part-of-speech constants:\n",
"* ADJ: a\n",
"* ADV: r\n",
"* NOUN: n\n",
"* VERB: v"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"import nltk\n",
"\n",
"from nltk.stem import *\n",
"\n",
"import pandas as pd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Stemming words"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"definit\n"
]
}
],
"source": [
"from nltk.stem import PorterStemmer \n",
"\n",
"stemmer = PorterStemmer() \n",
"print(stemmer.stem('definitions'))"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package wordnet to\n",
"[nltk_data] /Users/loonycorn/nltk_data...\n",
"[nltk_data] Package wordnet is already up-to-date!\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('wordnet')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Lemmatizing Words"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"definition\n"
]
}
],
"source": [
"from nltk.stem import WordNetLemmatizer\n",
"\n",
"wnl = WordNetLemmatizer()\n",
"print(wnl.lemmatize('definitions'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Lemmatizing words by specifying parts-of-speech"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Adjective: running\n",
"Adverb: running\n",
"Noun: running\n",
"Verb: run\n"
]
}
],
"source": [
"print('Adjective: ', wnl.lemmatize('running', pos='a'))\n",
"print('Adverb: ', wnl.lemmatize('running', pos='r'))\n",
"print('Noun: ', wnl.lemmatize('running', pos='n'))\n",
"print('Verb: ', wnl.lemmatize('running', pos='v'))"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"input_tokens = ['dictionaries', 'dictionary', \n",
" 'hushed', 'hush', 'hushing',\n",
" 'functional', 'functionally',\n",
" 'lying', 'lied', 'lies',\n",
" 'flawed', 'flaws', 'flawless', \n",
" 'friendship', 'friendships', 'friendly', 'friendless', \n",
" 'definitions', 'definition', 'definitely', \n",
" 'the', 'these', 'those',\n",
" 'motivational', 'motivate', 'motivating']"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [],
"source": [
"ss = SnowballStemmer('english')\n",
"\n",
"ss_stemmed_tokens = []\n",
"for token in input_tokens:\n",
" ss_stemmed_tokens.append(ss.stem(token))"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"wnl_lemmatized_tokens = []\n",
"for token in input_tokens:\n",
" wnl_lemmatized_tokens.append(wnl.lemmatize(token, pos='v'))"
]
},
{
"cell_type": "code",
"execution_count": 75,
"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>words</th>\n",
" <th>Snowball Stemmer</th>\n",
" <th>WordNet Lemmatizer</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>dictionaries</td>\n",
" <td>dictionari</td>\n",
" <td>dictionaries</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>dictionary</td>\n",
" <td>dictionari</td>\n",
" <td>dictionary</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>hushed</td>\n",
" <td>hush</td>\n",
" <td>hush</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>hush</td>\n",
" <td>hush</td>\n",
" <td>hush</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>hushing</td>\n",
" <td>hush</td>\n",
" <td>hush</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>functional</td>\n",
" <td>function</td>\n",
" <td>functional</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>functionally</td>\n",
" <td>function</td>\n",
" <td>functionally</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>lying</td>\n",
" <td>lie</td>\n",
" <td>lie</td>\n",
" </tr>\n",
" <tr>\n",
" <th>8</th>\n",
" <td>lied</td>\n",
" <td>lie</td>\n",
" <td>lie</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9</th>\n",
" <td>lies</td>\n",
" <td>lie</td>\n",
" <td>lie</td>\n",
" </tr>\n",
" <tr>\n",
" <th>10</th>\n",
" <td>flawed</td>\n",
" <td>flaw</td>\n",
" <td>flaw</td>\n",
" </tr>\n",
" <tr>\n",
" <th>11</th>\n",
" <td>flaws</td>\n",
" <td>flaw</td>\n",
" <td>flaw</td>\n",
" </tr>\n",
" <tr>\n",
" <th>12</th>\n",
" <td>flawless</td>\n",
" <td>flawless</td>\n",
" <td>flawless</td>\n",
" </tr>\n",
" <tr>\n",
" <th>13</th>\n",
" <td>friendship</td>\n",
" <td>friendship</td>\n",
" <td>friendship</td>\n",
" </tr>\n",
" <tr>\n",
" <th>14</th>\n",
" <td>friendships</td>\n",
" <td>friendship</td>\n",
" <td>friendships</td>\n",
" </tr>\n",
" <tr>\n",
" <th>15</th>\n",
" <td>friendly</td>\n",
" <td>friend</td>\n",
" <td>friendly</td>\n",
" </tr>\n",
" <tr>\n",
" <th>16</th>\n",
" <td>friendless</td>\n",
" <td>friendless</td>\n",
" <td>friendless</td>\n",
" </tr>\n",
" <tr>\n",
" <th>17</th>\n",
" <td>definitions</td>\n",
" <td>definit</td>\n",
" <td>definitions</td>\n",
" </tr>\n",
" <tr>\n",
" <th>18</th>\n",
" <td>definition</td>\n",
" <td>definit</td>\n",
" <td>definition</td>\n",
" </tr>\n",
" <tr>\n",
" <th>19</th>\n",
" <td>definitely</td>\n",
" <td>definit</td>\n",
" <td>definitely</td>\n",
" </tr>\n",
" <tr>\n",
" <th>20</th>\n",
" <td>the</td>\n",
" <td>the</td>\n",
" <td>the</td>\n",
" </tr>\n",
" <tr>\n",
" <th>21</th>\n",
" <td>these</td>\n",
" <td>these</td>\n",
" <td>these</td>\n",
" </tr>\n",
" <tr>\n",
" <th>22</th>\n",
" <td>those</td>\n",
" <td>those</td>\n",
" <td>those</td>\n",
" </tr>\n",
" <tr>\n",
" <th>23</th>\n",
" <td>motivational</td>\n",
" <td>motiv</td>\n",
" <td>motivational</td>\n",
" </tr>\n",
" <tr>\n",
" <th>24</th>\n",
" <td>motivate</td>\n",
" <td>motiv</td>\n",
" <td>motivate</td>\n",
" </tr>\n",
" <tr>\n",
" <th>25</th>\n",
" <td>motivating</td>\n",
" <td>motiv</td>\n",
" <td>motivate</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" words Snowball Stemmer WordNet Lemmatizer\n",
"0 dictionaries dictionari dictionaries\n",
"1 dictionary dictionari dictionary\n",
"2 hushed hush hush\n",
"3 hush hush hush\n",
"4 hushing hush hush\n",
"5 functional function functional\n",
"6 functionally function functionally\n",
"7 lying lie lie\n",
"8 lied lie lie\n",
"9 lies lie lie\n",
"10 flawed flaw flaw\n",
"11 flaws flaw flaw\n",
"12 flawless flawless flawless\n",
"13 friendship friendship friendship\n",
"14 friendships friendship friendships\n",
"15 friendly friend friendly\n",
"16 friendless friendless friendless\n",
"17 definitions definit definitions\n",
"18 definition definit definition\n",
"19 definitely definit definitely\n",
"20 the the the\n",
"21 these these these\n",
"22 those those those\n",
"23 motivational motiv motivational\n",
"24 motivate motiv motivate\n",
"25 motivating motiv motivate"
]
},
"execution_count": 75,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stems_lemmas_df = pd.DataFrame({\n",
" 'words': input_tokens,\n",
" 'Snowball Stemmer': ss_stemmed_tokens,\n",
" 'WordNet Lemmatizer': wnl_lemmatized_tokens\n",
"})\n",
"\n",
"stems_lemmas_df"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Marie Curie was a Polish-born physicist and chemist and one of the most famous scientists of her time.\n",
"Together with her husband Pierre, she was awarded the Nobel Prize in 1903, and she went on to win another in 1911.\n",
"Marie Sklodowska was born in Warsaw on 7 November 1867, the daughter of a teacher.\n",
"In 1891, she went to Paris to study physics and mathematics at the Sorbonne where she met Pierre Curie, professor of the School of Physics.\n",
"They were married in 1895.\n",
"The Curies worked together investigating radioactivity, building on the work of the German physicist Roentgen and the French physicist Becquerel.\n",
"In July 1898, the Curies announced the discovery of a new chemical element, polonium.\n",
"At the end of the year, they announced the discovery of another, radium.\n",
"The Curies, along with Becquerel, were awarded the Nobel Prize for Physics in 1903.\n",
"Pierre's life was cut short in 1906 when he was knocked down and killed by a carriage.\n",
"Marie took over his teaching post, becoming the first woman to teach at the Sorbonne, and devoted herself to continuing the work that they had begun together.\n",
"She received a second Nobel Prize, for Chemistry, in 1911.\n",
"The Curie's research was crucial in the development of x-rays in surgery.\n",
"During World War One Curie helped to equip ambulances with x-ray equipment, which she herself drove to the front lines.\n",
"The International Red Cross made her head of its radiological service and she held training courses for medical orderlies and doctors in the new techniques.\n",
"Despite her success, Marie continued to face great opposition from male scientists in France, and she never received significant financial benefits from her work.\n",
"By the late 1920s her health was beginning to deteriorate.\n",
"She died on 4 July 1934 from leukaemia, caused by exposure to high-energy radiation from her research.\n",
"The Curies' eldest daughter Irene was herself a scientist and winner of the Nobel Prize for Chemistry.\n"
]
}
],
"source": [
"from nltk.tokenize import word_tokenize\n",
" \n",
"with open('./datasets/biography.txt', 'r') as f:\n",
" file_contents = f.read()\n",
" \n",
"print(file_contents)"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [],
"source": [
"word_tokens = word_tokenize(file_contents)"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [],
"source": [
"wnl = WordNetLemmatizer()\n",
"lemmatized_words = []\n",
"\n",
"for word in word_tokens:\n",
" lemmatized_words.append(wnl.lemmatize(word, pos=\"v\"))"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"Marie Curie be a Polish-born physicist and chemist and one of the most famous scientists of her time . Together with her husband Pierre , she be award the Nobel Prize in 1903 , and she go on to win another in 1911 . Marie Sklodowska be bear in Warsaw on 7 November 1867 , the daughter of a teacher . In 1891 , she go to Paris to study physics and mathematics at the Sorbonne where she meet Pierre Curie , professor of the School of Physics . They be marry in 1895 . The Curies work together investigate radioactivity , build on the work of the German physicist Roentgen and the French physicist Becquerel . In July 1898 , the Curies announce the discovery of a new chemical element , polonium . At the end of the year , they announce the discovery of another , radium . The Curies , along with Becquerel , be award the Nobel Prize for Physics in 1903 . Pierre 's life be cut short in 1906 when he be knock down and kill by a carriage . Marie take over his teach post , become the first woman to teach at the Sorbonne , and devote herself to continue the work that they have begin together . She receive a second Nobel Prize , for Chemistry , in 1911 . The Curie 's research be crucial in the development of x-ray in surgery . During World War One Curie help to equip ambulances with x-ray equipment , which she herself drive to the front line . The International Red Cross make her head of its radiological service and she hold train course for medical orderlies and doctor in the new techniques . Despite her success , Marie continue to face great opposition from male scientists in France , and she never receive significant financial benefit from her work . By the late 1920s her health be begin to deteriorate . She die on 4 July 1934 from leukaemia , cause by exposure to high-energy radiation from her research . The Curies ' eldest daughter Irene be herself a scientist and winner of the Nobel Prize for Chemistry .\""
]
},
"execution_count": 79,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\" \".join(lemmatized_words)"
]
},
{
"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
}

View file

@ -1,571 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part-of-Speech Tagging"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import nltk\n",
"from nltk import word_tokenize"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package tagsets to\n",
"[nltk_data] /Users/loonycorn/nltk_data...\n",
"[nltk_data] Unzipping help/tagsets.zip.\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('tagsets')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package averaged_perceptron_tagger to\n",
"[nltk_data] /Users/loonycorn/nltk_data...\n",
"[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('averaged_perceptron_tagger')"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"$: dollar\n",
" $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$\n",
"'': closing quotation mark\n",
" ' ''\n",
"(: opening parenthesis\n",
" ( [ {\n",
"): closing parenthesis\n",
" ) ] }\n",
",: comma\n",
" ,\n",
"--: dash\n",
" --\n",
".: sentence terminator\n",
" . ! ?\n",
":: colon or ellipsis\n",
" : ; ...\n",
"CC: conjunction, coordinating\n",
" & 'n and both but either et for less minus neither nor or plus so\n",
" therefore times v. versus vs. whether yet\n",
"CD: numeral, cardinal\n",
" mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-\n",
" seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025\n",
" fifteen 271,124 dozen quintillion DM2,000 ...\n",
"DT: determiner\n",
" all an another any both del each either every half la many much nary\n",
" neither no some such that the them these this those\n",
"EX: existential there\n",
" there\n",
"FW: foreign word\n",
" gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous\n",
" lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte\n",
" terram fiche oui corporis ...\n",
"IN: preposition or conjunction, subordinating\n",
" astride among uppon whether out inside pro despite on by throughout\n",
" below within for towards near behind atop around if like until below\n",
" next into if beside ...\n",
"JJ: adjective or numeral, ordinal\n",
" third ill-mannered pre-war regrettable oiled calamitous first separable\n",
" ectoplasmic battery-powered participatory fourth still-to-be-named\n",
" multilingual multi-disciplinary ...\n",
"JJR: adjective, comparative\n",
" bleaker braver breezier briefer brighter brisker broader bumper busier\n",
" calmer cheaper choosier cleaner clearer closer colder commoner costlier\n",
" cozier creamier crunchier cuter ...\n",
"JJS: adjective, superlative\n",
" calmest cheapest choicest classiest cleanest clearest closest commonest\n",
" corniest costliest crassest creepiest crudest cutest darkest deadliest\n",
" dearest deepest densest dinkiest ...\n",
"LS: list item marker\n",
" A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005\n",
" SP-44007 Second Third Three Two * a b c d first five four one six three\n",
" two\n",
"MD: modal auxiliary\n",
" can cannot could couldn't dare may might must need ought shall should\n",
" shouldn't will would\n",
"NN: noun, common, singular or mass\n",
" common-carrier cabbage knuckle-duster Casino afghan shed thermostat\n",
" investment slide humour falloff slick wind hyena override subhumanity\n",
" machinist ...\n",
"NNP: noun, proper, singular\n",
" Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos\n",
" Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA\n",
" Shannon A.K.C. Meltex Liverpool ...\n",
"NNPS: noun, proper, plural\n",
" Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists\n",
" Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques\n",
" Apache Apaches Apocrypha ...\n",
"NNS: noun, common, plural\n",
" undergraduates scotches bric-a-brac products bodyguards facets coasts\n",
" divestitures storehouses designs clubs fragrances averages\n",
" subjectivists apprehensions muses factory-jobs ...\n",
"PDT: pre-determiner\n",
" all both half many quite such sure this\n",
"POS: genitive marker\n",
" ' 's\n",
"PRP: pronoun, personal\n",
" hers herself him himself hisself it itself me myself one oneself ours\n",
" ourselves ownself self she thee theirs them themselves they thou thy us\n",
"PRP$: pronoun, possessive\n",
" her his mine my our ours their thy your\n",
"RB: adverb\n",
" occasionally unabatingly maddeningly adventurously professedly\n",
" stirringly prominently technologically magisterially predominately\n",
" swiftly fiscally pitilessly ...\n",
"RBR: adverb, comparative\n",
" further gloomier grander graver greater grimmer harder harsher\n",
" healthier heavier higher however larger later leaner lengthier less-\n",
" perfectly lesser lonelier longer louder lower more ...\n",
"RBS: adverb, superlative\n",
" best biggest bluntest earliest farthest first furthest hardest\n",
" heartiest highest largest least less most nearest second tightest worst\n",
"RP: particle\n",
" aboard about across along apart around aside at away back before behind\n",
" by crop down ever fast for forth from go high i.e. in into just later\n",
" low more off on open out over per pie raising start teeth that through\n",
" under unto up up-pp upon whole with you\n",
"SYM: symbol\n",
" % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***\n",
"TO: \"to\" as preposition or infinitive marker\n",
" to\n",
"UH: interjection\n",
" Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen\n",
" huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly\n",
" man baby diddle hush sonuvabitch ...\n",
"VB: verb, base form\n",
" ask assemble assess assign assume atone attention avoid bake balkanize\n",
" bank begin behold believe bend benefit bevel beware bless boil bomb\n",
" boost brace break bring broil brush build ...\n",
"VBD: verb, past tense\n",
" dipped pleaded swiped regummed soaked tidied convened halted registered\n",
" cushioned exacted snubbed strode aimed adopted belied figgered\n",
" speculated wore appreciated contemplated ...\n",
"VBG: verb, present participle or gerund\n",
" telegraphing stirring focusing angering judging stalling lactating\n",
" hankerin' alleging veering capping approaching traveling besieging\n",
" encrypting interrupting erasing wincing ...\n",
"VBN: verb, past participle\n",
" multihulled dilapidated aerosolized chaired languished panelized used\n",
" experimented flourished imitated reunifed factored condensed sheared\n",
" unsettled primed dubbed desired ...\n",
"VBP: verb, present tense, not 3rd person singular\n",
" predominate wrap resort sue twist spill cure lengthen brush terminate\n",
" appear tend stray glisten obtain comprise detest tease attract\n",
" emphasize mold postpone sever return wag ...\n",
"VBZ: verb, present tense, 3rd person singular\n",
" bases reconstructs marks mixes displeases seals carps weaves snatches\n",
" slumps stretches authorizes smolders pictures emerges stockpiles\n",
" seduces fizzes uses bolsters slaps speaks pleads ...\n",
"WDT: WH-determiner\n",
" that what whatever which whichever\n",
"WP: WH-pronoun\n",
" that what whatever whatsoever which who whom whosoever\n",
"WP$: WH-pronoun, possessive\n",
" whose\n",
"WRB: Wh-adverb\n",
" how however whence whenever where whereby whereever wherein whereof why\n",
"``: opening quotation mark\n",
" ` ``\n"
]
}
],
"source": [
"nltk.help.upenn_tagset()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('I', 'PRP'),\n",
" ('refuse', 'VBP'),\n",
" ('to', 'TO'),\n",
" ('let', 'VB'),\n",
" ('this', 'DT'),\n",
" ('refuse', 'NN'),\n",
" ('get', 'VB'),\n",
" ('me', 'PRP'),\n",
" ('down', 'RP')]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"I refuse to let this refuse get me down\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('Bear', 'NNP'),\n",
" ('with', 'IN'),\n",
" ('me', 'PRP'),\n",
" (',', ','),\n",
" ('this', 'DT'),\n",
" ('effort', 'NN'),\n",
" ('with', 'IN'),\n",
" ('soon', 'RB'),\n",
" ('bear', 'JJ'),\n",
" ('fruit', 'NN'),\n",
" (',', ','),\n",
" ('otherwise', 'RB'),\n",
" ('we', 'PRP'),\n",
" (\"'ll\", 'MD'),\n",
" ('have', 'VB'),\n",
" ('to', 'TO'),\n",
" ('run', 'VB'),\n",
" ('from', 'IN'),\n",
" ('the', 'DT'),\n",
" ('bear', 'NN')]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"\"\"Bear with me, this effort with soon bear fruit, \n",
" otherwise we'll have to run from the bear\"\"\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('A', 'DT'),\n",
" ('bird', 'NN'),\n",
" ('in', 'IN'),\n",
" ('hand', 'NN'),\n",
" ('is', 'VBZ'),\n",
" ('worth', 'JJ'),\n",
" ('two', 'CD'),\n",
" ('in', 'IN'),\n",
" ('the', 'DT'),\n",
" ('bush', 'NN'),\n",
" ('.', '.'),\n",
" ('Good', 'JJ'),\n",
" ('things', 'NNS'),\n",
" ('come', 'VBP'),\n",
" ('to', 'TO'),\n",
" ('those', 'DT'),\n",
" ('who', 'WP'),\n",
" ('wait', 'VBP'),\n",
" ('.', '.'),\n",
" ('There', 'EX'),\n",
" ('are', 'VBP'),\n",
" ('other', 'JJ'),\n",
" ('fish', 'NN'),\n",
" ('in', 'IN'),\n",
" ('the', 'DT'),\n",
" ('sea', 'NN'),\n",
" ('.', '.'),\n",
" ('The', 'DT'),\n",
" ('ball', 'NN'),\n",
" ('is', 'VBZ'),\n",
" ('in', 'IN'),\n",
" ('your', 'PRP$'),\n",
" ('court', 'NN'),\n",
" ('.', '.')]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"A bird in hand is worth two in the bush. \" +\\\n",
" \"Good things come to those who wait. \" +\\\n",
" \"There are other fish in the sea. \" +\\\n",
" \"The ball is in your court.\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('NN', 7),\n",
" ('DT', 5),\n",
" ('IN', 4),\n",
" ('.', 4),\n",
" ('JJ', 3),\n",
" ('VBP', 3),\n",
" ('VBZ', 2),\n",
" ('CD', 1),\n",
" ('NNS', 1),\n",
" ('TO', 1)]"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from nltk.probability import FreqDist\n",
"\n",
"fd = FreqDist(tagged_words)\n",
"fd_tagged = FreqDist(tag for (word, tag) in tagged_words)\n",
"fd_tagged.most_common(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Brown Corpus was the first million-word electronic corpus of English, created in 1961 at Brown University. This corpus contains text from 500 sources, and the sources have been categorized by genre, such as news, editorial, and so on. 1.1 gives an example of each genre (for a complete list, see http://icame.uib.no/brown/bcm-los.html)."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package brown to /Users/loonycorn/nltk_data...\n",
"[nltk_data] Package brown is already up-to-date!\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('brown')"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['The',\n",
" 'Fulton',\n",
" 'County',\n",
" 'Grand',\n",
" 'Jury',\n",
" 'said',\n",
" 'Friday',\n",
" 'an',\n",
" 'investigation',\n",
" 'of']"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.corpus.brown.words()[:10]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"text = nltk.Text(word.lower() for word in nltk.corpus.brown.words())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lexical categories like \"noun\" and part-of-speech tags like NN seem to have their uses, but the details will be obscure to many readers. You might wonder what justification there is for introducing this extra level of information. Many of these categories arise from superficial analysis the distribution of words in text. Consider the following analysis involving woman (a noun), bought (a verb), over (a preposition), and the (a determiner). The text.similar() method takes a word w, finds all contexts w1w w2, then finds all words w' that appear in the same context, i.e. w1w'w2."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Similar words here belong to the same part of speech"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"man time day way girl year house people world city family state room\n",
"country car woman program church government job\n"
]
}
],
"source": [
"text.similar('boy')"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"get be do in see work go have take make put and find time look day say\n",
"use come show\n"
]
}
],
"source": [
"text.similar('run')"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"in on to of and for with from at by that into as up out down through\n",
"is all about\n"
]
}
],
"source": [
"text.similar('over')"
]
},
{
"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
}

View file

@ -1,197 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Hashing trick"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Instead of building a hash table of the features encountered in training, as the vectorizers do, instances of FeatureHasher apply a hash function to the features to determine their column index in sample matrices directly. The result is increased speed and reduced memory usage, at the expense of inspectability; the hasher does not remember what the input features looked like and has no inverse_transform method."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html\n",
"* https://scikit-learn.org/stable/modules/feature_extraction.html#feature-hashing"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(7, 8)"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.feature_extraction import FeatureHasher\n",
"\n",
"text = [\"A bird in hand is worth two in the bush.\",\n",
" \"Good things come to those who wait.\",\n",
" \"These watches cost $1500! \",\n",
" \"These are other fish in the sea.\",\n",
" \"The ball is in your court.\",\n",
" \"Mr. Smith Goes to Washington \",\n",
" \"Doogie Howser M.D.\"]\n",
"\n",
"hasher = FeatureHasher(n_features=8, input_type='string')\n",
"hashed_features = hasher.fit_transform(text)\n",
"\n",
"hashed_features.shape"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 10., 0., 1., 1., -3., -11., 1., -1.],\n",
" [ 6., -2., 0., 3., 0., -6., 0., 0.],\n",
" [ 4., -5., 1., -1., 2., -3., 0., 0.],\n",
" [ 6., 2., 2., 0., -1., -8., 0., 3.],\n",
" [ 7., 1., 1., 1., 1., -6., 1., 0.],\n",
" [ 4., 2., 1., 0., -2., -5., 0., -1.],\n",
" [ 2., 1., 0., 3., 0., -3., 2., 1.]])"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hashed_features.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(7, 16)"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hasher = FeatureHasher(n_features=16, input_type='string')\n",
"hashed_features = hasher.fit_transform(text)\n",
"\n",
"hashed_features.shape"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 1., 0., 1., 1., -3., -4., 0., 1., 9., 0., 0., 0., 0.,\n",
" -7., 1., -2.],\n",
" [ 0., -3., 1., 3., -1., -2., 0., 2., 6., 1., -1., 0., 1.,\n",
" -4., 0., -2.],\n",
" [ 0., -5., 1., -1., 2., 1., 0., 3., 4., 0., 0., 0., 0.,\n",
" -4., 0., -3.],\n",
" [ 0., 2., 2., -1., -1., -2., 0., 6., 6., 0., 0., 1., 0.,\n",
" -6., 0., -3.],\n",
" [ 2., 1., 1., 1., -1., -2., 1., 1., 5., 0., 0., 0., 2.,\n",
" -4., 0., -1.],\n",
" [-1., 1., 1., 0., -2., -2., 0., 1., 5., 1., 0., 0., 0.,\n",
" -3., 0., -2.],\n",
" [ 0., 0., 0., 3., 0., -1., 2., 2., 2., 1., 0., 0., 0.,\n",
" -2., 0., -1.]])"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hashed_features.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'FeatureHasher' object has no attribute 'inverse_transform'",
"output_type": "error",
"traceback": [
"\u001b[0;31m--------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-44-acc2ce62ec0e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mhasher\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minverse_transform\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mhashed_features\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m: 'FeatureHasher' object has no attribute 'inverse_transform'"
]
}
],
"source": [
"hasher.inverse_transform(hashed_features)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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
}

View file

@ -1,486 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## HashingVectorizer\n",
"* <b>HashingVectorizer</b> is the combination of <b>FeatureHasher</b> and <b>CountVectorizer</b> i.e, we get the Term frequency of words as well as the reduced dimension\n",
"* When we used FeatureHasher the dimension of vector reduced but we couldn't get any understandable format in output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### If we have large vocabulary of words we can choose to use the HashingVectorizer rather than the CountVectorizer\n",
"* The use of hashing buckets to represent words allows us to scale large data sets when we use the HashingVectorizer.\n",
"* The input argument to the vectorizer is the number of hash buckets (n_features)\n",
"* Result : numeric representation of all the words in documents.\n",
"* Word ids are from 0 to (n_features - 1) because total of n_features buckets.\n",
"* Because the size of vocabulary is larger than the number of buckets, multiple words can hash to the same bucket.\n",
"* No way to get back to the original value from the hash bucket value.\n",
"* Frequencies of each is represented in normalized from\n",
"\n",
"https://scikit-learn.org/stable/modules/feature_extraction.html#vectorizing-a-large-text-corpus-with-the-hashing-trick"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### words are mapped directly to indices with a hashing function"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(6, 27)"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.feature_extraction.text import CountVectorizer\n",
"\n",
"text_array = [\"Good things come to those who wait.\",\n",
" \"These watches cost $1500! \",\n",
" \"These are other fish in the sea.\",\n",
" \"The ball is in your court.\",\n",
" \"Mr. Smith Goes to Washington \",\n",
" \"Doogie Howser M.D.\"]\n",
"\n",
"count_vectorizer = CountVectorizer()\n",
"feature_vector = count_vectorizer.fit_transform(text_array)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,\n",
" 1, 0, 0, 1, 0],\n",
" [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n",
" 0, 0, 1, 0, 0],\n",
" [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0,\n",
" 0, 0, 0, 0, 0],\n",
" [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 1],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1,\n",
" 0, 1, 0, 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0]], dtype=int64)"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"feature_vector.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'good': 9,\n",
" 'things': 19,\n",
" 'come': 3,\n",
" 'to': 21,\n",
" 'those': 20,\n",
" 'who': 25,\n",
" 'wait': 22,\n",
" 'these': 18,\n",
" 'watches': 24,\n",
" 'cost': 4,\n",
" '1500': 0,\n",
" 'are': 1,\n",
" 'other': 14,\n",
" 'fish': 7,\n",
" 'in': 11,\n",
" 'the': 17,\n",
" 'sea': 15,\n",
" 'ball': 2,\n",
" 'is': 12,\n",
" 'your': 26,\n",
" 'court': 5,\n",
" 'mr': 13,\n",
" 'smith': 16,\n",
" 'goes': 8,\n",
" 'washington': 23,\n",
" 'doogie': 6,\n",
" 'howser': 10}"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer.vocabulary_"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"analyzer = count_vectorizer.build_analyzer()"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['good', 'things', 'come', 'to', 'those', 'who', 'wait']"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"word_tokens = analyzer(text_array[0])\n",
"\n",
"word_tokens"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"frequency_list = []\n",
"\n",
"for i, text in enumerate(text_array):\n",
" tokens = analyzer(text)\n",
" \n",
" word_frequency = {}\n",
"\n",
" for token in tokens:\n",
" word_idx = count_vectorizer.vocabulary_[token]\n",
" \n",
" word_frequency[token] = feature_vector[i, word_idx]\n",
" \n",
" frequency_list.append(word_frequency)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'good': 1, 'things': 1, 'come': 1, 'to': 1, 'those': 1, 'who': 1, 'wait': 1},\n",
" {'these': 1, 'watches': 1, 'cost': 1, '1500': 1},\n",
" {'these': 1, 'are': 1, 'other': 1, 'fish': 1, 'in': 1, 'the': 1, 'sea': 1},\n",
" {'the': 1, 'ball': 1, 'is': 1, 'in': 1, 'your': 1, 'court': 1},\n",
" {'mr': 1, 'smith': 1, 'goes': 1, 'to': 1, 'washington': 1},\n",
" {'doogie': 1, 'howser': 1}]"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequency_list"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(6, 8)"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.feature_extraction import FeatureHasher\n",
"\n",
"hasher = FeatureHasher(n_features=8, input_type='string')\n",
"hashed_features = hasher.fit_transform(frequency_list)\n",
"\n",
"hashed_features.shape"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0., 3., 0., 1., -2., -1., 0., 0.],\n",
" [ 0., 0., -1., 0., -1., 0., 2., 0.],\n",
" [ 0., 1., -1., 0., 0., 0., 0., 1.],\n",
" [ 0., 1., 0., 0., 0., 1., 0., 0.],\n",
" [ 0., -1., 0., 1., 0., -1., 0., 0.],\n",
" [ 0., 1., 0., 0., 1., 0., 0., 0.]])"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hashed_features.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(6, 8)"
]
},
"execution_count": 69,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn.feature_extraction.text import HashingVectorizer\n",
"\n",
"vectorizer = HashingVectorizer(n_features=8, norm=None)\n",
"feature_vector = vectorizer.transform(text_array)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0., 3., 0., 1., -2., -1., 0., 0.],\n",
" [ 0., 0., -1., 0., -1., 0., 2., 0.],\n",
" [ 0., 1., -1., 0., 0., 0., 0., 1.],\n",
" [ 0., 1., 0., 0., 0., 1., 0., 0.],\n",
" [ 0., -1., 0., 1., 0., -1., 0., 0.],\n",
" [ 0., 1., 0., 0., 1., 0., 0., 0.]])"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"feature_vector.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(6, 8)"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vectorizer = HashingVectorizer(n_features=8, norm='l1')\n",
"feature_vector = vectorizer.transform(text_array)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0. , 0.42857143, 0. , 0.14285714, -0.28571429,\n",
" -0.14285714, 0. , 0. ],\n",
" [ 0. , 0. , -0.25 , 0. , -0.25 ,\n",
" 0. , 0.5 , 0. ],\n",
" [ 0. , 0.33333333, -0.33333333, 0. , 0. ,\n",
" 0. , 0. , 0.33333333],\n",
" [ 0. , 0.5 , 0. , 0. , 0. ,\n",
" 0.5 , 0. , 0. ],\n",
" [ 0. , -0.33333333, 0. , 0.33333333, 0. ,\n",
" -0.33333333, 0. , 0. ],\n",
" [ 0. , 0.5 , 0. , 0. , 0.5 ,\n",
" 0. , 0. , 0. ]])"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"feature_vector.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(6, 8)"
]
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vectorizer = HashingVectorizer(n_features=8, norm='l2')\n",
"feature_vector = vectorizer.transform(text_array)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 0. , 0.77459667, 0. , 0.25819889, -0.51639778,\n",
" -0.25819889, 0. , 0. ],\n",
" [ 0. , 0. , -0.40824829, 0. , -0.40824829,\n",
" 0. , 0.81649658, 0. ],\n",
" [ 0. , 0.57735027, -0.57735027, 0. , 0. ,\n",
" 0. , 0. , 0.57735027],\n",
" [ 0. , 0.70710678, 0. , 0. , 0. ,\n",
" 0.70710678, 0. , 0. ],\n",
" [ 0. , -0.57735027, 0. , 0.57735027, 0. ,\n",
" -0.57735027, 0. , 0. ],\n",
" [ 0. , 0.70710678, 0. , 0. , 0.70710678,\n",
" 0. , 0. , 0. ]])"
]
},
"execution_count": 74,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"feature_vector.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0., 3., 0., 1., 2., 1., 0., 0.],\n",
" [0., 0., 1., 0., 1., 0., 2., 0.],\n",
" [2., 1., 1., 0., 0., 0., 2., 1.],\n",
" [0., 1., 0., 0., 2., 1., 2., 0.],\n",
" [0., 1., 0., 3., 0., 1., 0., 0.],\n",
" [0., 1., 0., 0., 1., 0., 0., 0.]])"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vectorizer = HashingVectorizer(n_features=8, norm=None, alternate_sign=False)\n",
"feature_vector = vectorizer.transform(text_array)\n",
"\n",
"feature_vector.toarray()"
]
},
{
"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
}

View file

@ -1,297 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Datasketch\n",
"https://pypi.org/project/datasketch/"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: datasketch in /anaconda3/lib/python3.7/site-packages (1.4.3)\n",
"Requirement already satisfied: numpy>=1.11 in /anaconda3/lib/python3.7/site-packages (from datasketch) (1.16.1)\n",
"Requirement already satisfied: redis>=2.10.0 in /anaconda3/lib/python3.7/site-packages (from datasketch) (3.2.1)\n"
]
}
],
"source": [
"!pip install datasketch"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"from datasketch import MinHash, MinHashLSH\n",
"\n",
"from nltk import ngrams\n",
"from nltk import word_tokenize"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"text_array = [\"A bird in hand is worth two in the bush.\",\n",
" \"Good things come to those who wait.\",\n",
" \"There are other fish in the sea.\",\n",
" \"The ball is in your court.\"]"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[['A', 'bird', 'in', 'hand', 'is', 'worth', 'two', 'in', 'the', 'bush', '.'],\n",
" ['Good', 'things', 'come', 'to', 'those', 'who', 'wait', '.'],\n",
" ['There', 'are', 'other', 'fish', 'in', 'the', 'sea', '.'],\n",
" ['The', 'ball', 'is', 'in', 'your', 'court', '.']]"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"word_token_array = [word_tokenize(text) for text in text_array]\n",
"\n",
"word_token_array"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 ('A', 'bird', 'in')\n",
"0 ('bird', 'in', 'hand')\n",
"0 ('in', 'hand', 'is')\n",
"0 ('hand', 'is', 'worth')\n",
"0 ('is', 'worth', 'two')\n",
"0 ('worth', 'two', 'in')\n",
"0 ('two', 'in', 'the')\n",
"0 ('in', 'the', 'bush')\n",
"0 ('the', 'bush', '.')\n",
"1 ('Good', 'things', 'come')\n",
"1 ('things', 'come', 'to')\n",
"1 ('come', 'to', 'those')\n",
"1 ('to', 'those', 'who')\n",
"1 ('those', 'who', 'wait')\n",
"1 ('who', 'wait', '.')\n",
"2 ('There', 'are', 'other')\n",
"2 ('are', 'other', 'fish')\n",
"2 ('other', 'fish', 'in')\n",
"2 ('fish', 'in', 'the')\n",
"2 ('in', 'the', 'sea')\n",
"2 ('the', 'sea', '.')\n",
"3 ('The', 'ball', 'is')\n",
"3 ('ball', 'is', 'in')\n",
"3 ('is', 'in', 'your')\n",
"3 ('in', 'your', 'court')\n",
"3 ('your', 'court', '.')\n"
]
}
],
"source": [
"for index, word_tokens in enumerate(word_token_array):\n",
" for n_gram in ngrams(word_tokens, 3):\n",
" print(index, n_gram)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"min_hash_lsh = MinHashLSH(threshold=0.5, num_perm=128)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"min_hashes = {}\n",
"\n",
"for index, text in enumerate(text_array):\n",
" min_hash = MinHash(num_perm=128)\n",
"\n",
" for n_gram in ngrams(text, 3):\n",
" min_hash.update(\"\".join(n_gram).encode('utf-8'))\n",
" \n",
" min_hash_lsh.insert(index, min_hash)\n",
" min_hashes[index] = min_hash"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{0: <datasketch.minhash.MinHash at 0x11bc3a9b0>,\n",
" 1: <datasketch.minhash.MinHash at 0x11bc3ab00>,\n",
" 2: <datasketch.minhash.MinHash at 0x11bc392e8>,\n",
" 3: <datasketch.minhash.MinHash at 0x11bc39320>}"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"min_hashes"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Candidate pairs with Jaccard similarity > 0.5 for input 0 : [0]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 1 : [1]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 2 : [2]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 3 : [3]\n"
]
}
],
"source": [
"for i in min_hashes.keys():\n",
" result = min_hash_lsh.query(min_hashes[i])\n",
" print(\"Candidate pairs with Jaccard similarity > 0.5 for input\", i, \":\", result)"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [],
"source": [
"text_array = [\"A bird in hand is worth two in the bush.\",\n",
" \"A bird in hands is worth three in the bushes.\",\n",
" \"Good things come to those who wait.\",\n",
" \"Good tpings cxme to those who wait long.\",\n",
" \"There are other fish in the sea.\",\n",
" \"The ball is in your court.\"\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [],
"source": [
"min_hash_lsh = MinHashLSH(threshold=0.5, num_perm=128)"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [],
"source": [
"min_hashes = {}\n",
"\n",
"for index, text in enumerate(text_array):\n",
" min_hash = MinHash(num_perm=128)\n",
"\n",
" for n_gram in ngrams(text, 3):\n",
" min_hash.update(\"\".join(n_gram).encode('utf-8'))\n",
" \n",
" min_hash_lsh.insert(index, min_hash)\n",
" min_hashes[index] = min_hash"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Candidate pairs with Jaccard similarity > 0.5 for input 0 : [0, 1]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 1 : [0, 1]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 2 : [2, 3]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 3 : [2, 3]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 4 : [4]\n",
"Candidate pairs with Jaccard similarity > 0.5 for input 5 : [5]\n"
]
}
],
"source": [
"for i in min_hashes.keys():\n",
" result = min_hash_lsh.query(min_hashes[i])\n",
" print(\"Candidate pairs with Jaccard similarity > 0.5 for input\", i, \":\", result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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
}

View file

@ -1,711 +0,0 @@
{
"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
}

View file

@ -1,582 +0,0 @@
{
"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
}

View file

@ -1,598 +0,0 @@
{
"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": [
"<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>380616</th>\n",
" <td>10</td>\n",
" <td>Stilifer akahitode</td>\n",
" <td>Stilifer akahitode is a species of sea snail ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>500198</th>\n",
" <td>13</td>\n",
" <td>Ip Man 2</td>\n",
" <td>Ip Man 2 is a 2010 Hong Kong biographical mar...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>88377</th>\n",
" <td>3</td>\n",
" <td>Achuta Manasa</td>\n",
" <td>Achuta Manasa is an Indian kuchipudi dancer.</td>\n",
" </tr>\n",
" <tr>\n",
" <th>377145</th>\n",
" <td>10</td>\n",
" <td>Bombyx incomposita</td>\n",
" <td>Bombyx incomposita is a moth in the Bombycida...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>29060</th>\n",
" <td>1</td>\n",
" <td>W. W. Greener</td>\n",
" <td>W.W. Greener is a sporting shotgun and rifle ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>198749</th>\n",
" <td>5</td>\n",
" <td>Robert E. Holmes</td>\n",
" <td>Robert Edward Holmes (November 14 1922 – July...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>488653</th>\n",
" <td>13</td>\n",
" <td>My Giant</td>\n",
" <td>My Giant is a 1998 comedy drama film starring...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>320765</th>\n",
" <td>9</td>\n",
" <td>Lockland Ohio</td>\n",
" <td>Lockland is a village in Hamilton County Ohio...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7583</th>\n",
" <td>1</td>\n",
" <td>Fresh to Order</td>\n",
" <td>Fresh to Order (f2o) is an Atlanta Fine fast ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>95113</th>\n",
" <td>3</td>\n",
" <td>Donald Deskey</td>\n",
" <td>Donald Deskey (November 23 1894 – April 29 19...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"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
}

View file

@ -1,568 +0,0 @@
{
"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('./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>524463</th>\n",
" <td>14</td>\n",
" <td>Open Sesame (manga)</td>\n",
" <td>Open Sesame is a Japanese manga series writte...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>214954</th>\n",
" <td>6</td>\n",
" <td>USS Porter (DDG-78)</td>\n",
" <td>USS Porter (DDG-78) is an Arleigh Burke-class...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>369188</th>\n",
" <td>10</td>\n",
" <td>Chionodes luctuella</td>\n",
" <td>Chionodes luctuella is a moth of the Gelechii...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>15537</th>\n",
" <td>1</td>\n",
" <td>Rashtriya Chemicals &amp; Fertilizers</td>\n",
" <td>Rashtriya Chemicals &amp; Fertilizers Ltd. (RCF) ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>434426</th>\n",
" <td>11</td>\n",
" <td>Salix gilgiana</td>\n",
" <td>Salix gilgiana is a species of willow native ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>315086</th>\n",
" <td>8</td>\n",
" <td>Devlins Creek</td>\n",
" <td>Devlins Creek an urban watercourse that is pa...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>133194</th>\n",
" <td>4</td>\n",
" <td>Warren Donald</td>\n",
" <td>Warren Donald (born 7 October 1964) is an Eng...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>138090</th>\n",
" <td>4</td>\n",
" <td>Chris Hatcher (outfielder)</td>\n",
" <td>Christopher Kenneth Hatcher (born January 7 1...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>358873</th>\n",
" <td>9</td>\n",
" <td>Królewskie Ostrzeszów County</td>\n",
" <td>Królewskie [kruˈlɛfskʲɛ] is a village in the ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>108048</th>\n",
" <td>3</td>\n",
" <td>Hamuera Tamahau Mahupuku</td>\n",
" <td>Hamuera Tamahau Mahupuku (c.1842 – 14 January...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"524463 14 Open Sesame (manga) \n",
"214954 6 USS Porter (DDG-78) \n",
"369188 10 Chionodes luctuella \n",
"15537 1 Rashtriya Chemicals & Fertilizers \n",
"434426 11 Salix gilgiana \n",
"315086 8 Devlins Creek \n",
"133194 4 Warren Donald \n",
"138090 4 Chris Hatcher (outfielder) \n",
"358873 9 Królewskie Ostrzeszów County \n",
"108048 3 Hamuera Tamahau Mahupuku \n",
"\n",
" Text \n",
"524463 Open Sesame is a Japanese manga series writte... \n",
"214954 USS Porter (DDG-78) is an Arleigh Burke-class... \n",
"369188 Chionodes luctuella is a moth of the Gelechii... \n",
"15537 Rashtriya Chemicals & Fertilizers Ltd. (RCF) ... \n",
"434426 Salix gilgiana is a species of willow native ... \n",
"315086 Devlins Creek an urban watercourse that is pa... \n",
"133194 Warren Donald (born 7 October 1964) is an Eng... \n",
"138090 Christopher Kenneth Hatcher (born January 7 1... \n",
"358873 Królewskie [kruˈlɛfskʲɛ] is a village in the ... \n",
"108048 Hamuera Tamahau Mahupuku (c.1842 – 14 January... "
]
},
"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": [
"77514 Phillips University was a private coeducation...\n",
"341059 Nowiny [nɔˈvinɨ] is a village in the administ...\n",
"517834 Capricious Summer (Czech: Rozmarné léto) is a...\n",
"215388 Maumelle Ordnance Works Locomotive 1 is a gas...\n",
"250923 Grace Reformed Church is a historic church lo...\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": [
"77514 2\n",
"341059 9\n",
"517834 13\n",
"215388 6\n",
"250923 7\n",
"Name: Label, dtype: int64"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Y.head()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"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, 47886)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(stop_words='english')\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, 15329)\t1\n",
" (0, 28116)\t1\n",
" (0, 39106)\t1\n",
" (0, 42005)\t1\n",
" (0, 14627)\t1\n",
" (0, 19453)\t1\n",
" (0, 34423)\t1\n",
" (0, 7888)\t1\n",
" (0, 30095)\t1\n",
" (0, 40200)\t1\n",
" (0, 19281)\t1\n",
" (0, 36984)\t1\n",
" (0, 17534)\t1\n",
" (0, 9770)\t1\n",
" (0, 42720)\t1\n",
" (0, 20178)\t1\n",
" (0, 9116)\t1\n",
" (0, 12475)\t1\n",
" (0, 9188)\t1\n",
" (0, 9127)\t1\n",
" (0, 2428)\t1\n",
" (0, 786)\t1\n",
" (0, 666)\t1\n",
" (0, 39115)\t1\n",
" (0, 42819)\t1\n",
" (0, 29834)\t1\n",
" (0, 14115)\t2\n",
" (0, 24524)\t1\n",
" (0, 13596)\t1\n",
" (0, 19001)\t1\n",
" (0, 20458)\t1\n",
" (0, 9679)\t1\n",
" (0, 32870)\t1\n",
" (0, 42838)\t2\n",
" (0, 31628)\t2\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, 47886)"
]
},
"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, 47886), (2000, 47886))"
]
},
"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": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 8, 13, 4, ..., 6, 4, 13])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1472\n",
"accuracy_score : 0.736\n",
"precision_score : 0.746912711601029\n",
"recall_score : 0.736\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
}

View file

@ -1,539 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"from sklearn.model_selection import train_test_split\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.feature_extraction import text \n",
"\n",
"from sklearn.naive_bayes import GaussianNB\n",
"\n",
"from nltk.tokenize import word_tokenize\n",
"from nltk.probability import FreqDist"
]
},
{
"cell_type": "code",
"execution_count": 4,
"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": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(559999, 3)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df['Label'].unique()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"dbpedia_df = dbpedia_df.sample(10000, replace=False)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"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>293816</th>\n",
" <td>8</td>\n",
" <td>Sheep Mountain (Flathead County Montana)</td>\n",
" <td>Sheep Mountain (8530 feet (2600 m)) is locate...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>379389</th>\n",
" <td>10</td>\n",
" <td>Argyropelecus hemigymnus</td>\n",
" <td>Argyropelecus hemigymnus the half-naked hatch...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>553602</th>\n",
" <td>14</td>\n",
" <td>Double Identity (novel)</td>\n",
" <td>Double Identity is a 2005 young adult novel b...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>104503</th>\n",
" <td>3</td>\n",
" <td>Picaflor de los Andes</td>\n",
" <td>Víctor Alberto Gil Mallma (1930; Huancayo - J...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>338288</th>\n",
" <td>9</td>\n",
" <td>Jerry City Ohio</td>\n",
" <td>Jerry City is a village in Wood County Ohio U...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>244140</th>\n",
" <td>7</td>\n",
" <td>John Hosford House</td>\n",
" <td>The John Hosford House built in 1860 is an hi...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>182565</th>\n",
" <td>5</td>\n",
" <td>Hunt Downer</td>\n",
" <td>Major General Huntington Blair Downer Jr. kno...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>252037</th>\n",
" <td>7</td>\n",
" <td>Brea City Hall and Park</td>\n",
" <td>Brea City Hall and Park in Brea California wa...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>98721</th>\n",
" <td>3</td>\n",
" <td>Christian Jacob (musician)</td>\n",
" <td>Christian Jacob is a lyrical jazz pianist. He...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>188815</th>\n",
" <td>5</td>\n",
" <td>George Forbes (New Zealand politician)</td>\n",
" <td>George William Forbes (12 March 1869 – 17 May...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"293816 8 Sheep Mountain (Flathead County Montana) \n",
"379389 10 Argyropelecus hemigymnus \n",
"553602 14 Double Identity (novel) \n",
"104503 3 Picaflor de los Andes \n",
"338288 9 Jerry City Ohio \n",
"244140 7 John Hosford House \n",
"182565 5 Hunt Downer \n",
"252037 7 Brea City Hall and Park \n",
"98721 3 Christian Jacob (musician) \n",
"188815 5 George Forbes (New Zealand politician) \n",
"\n",
" Text \n",
"293816 Sheep Mountain (8530 feet (2600 m)) is locate... \n",
"379389 Argyropelecus hemigymnus the half-naked hatch... \n",
"553602 Double Identity is a 2005 young adult novel b... \n",
"104503 Víctor Alberto Gil Mallma (1930; Huancayo - J... \n",
"338288 Jerry City is a village in Wood County Ohio U... \n",
"244140 The John Hosford House built in 1860 is an hi... \n",
"182565 Major General Huntington Blair Downer Jr. kno... \n",
"252037 Brea City Hall and Park in Brea California wa... \n",
"98721 Christian Jacob is a lyrical jazz pianist. He... \n",
"188815 George William Forbes (12 March 1869 – 17 May... "
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.sample(10)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 3)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"X = dbpedia_df['Text']\n",
"\n",
"Y = dbpedia_df['Label']"
]
},
{
"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": [
"503033"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokens = word_tokenize(\"\\n\".join(X.values))\n",
"\n",
"len(tokens)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"FreqDist({'the': 23584, '.': 23365, 'in': 16237, 'of': 15558, 'is': 13472, 'a': 13075, 'and': 12741, '(': 7078, ')': 7048, 'was': 6816, ...})"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"freq = FreqDist(tokens)\n",
"freq"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"491"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequent_words = []\n",
"\n",
"for key, value in freq.items():\n",
" if value >= 100:\n",
" frequent_words.append(key.lower())\n",
" \n",
"len(frequent_words)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['columbia',\n",
" '(',\n",
" ')',\n",
" 'was',\n",
" 'an',\n",
" 'american',\n",
" 'company',\n",
" 'that',\n",
" 'from',\n",
" '1994',\n",
" 'to',\n",
" '2002',\n",
" '.',\n",
" 'it',\n",
" 'operated',\n",
" 'as',\n",
" 'the',\n",
" 'third',\n",
" 'name',\n",
" 'of',\n",
" 'early',\n",
" 'studio',\n",
" 'and',\n",
" 'part',\n",
" 'second']"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequent_words[:25]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"stop_words = text.ENGLISH_STOP_WORDS.union(frequent_words)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/anaconda3/lib/python3.7/site-packages/sklearn/feature_extraction/text.py:301: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['st'] not in stop_words.\n",
" 'stop_words.' % sorted(inconsistent))\n"
]
},
{
"data": {
"text/plain": [
"(10000, 47434)"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(stop_words=stop_words)\n",
"\n",
"feature_vector = count_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47434)"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 20,
"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": 21,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([13, 9, 13, ..., 7, 11, 5])"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1397\n",
"accuracy_score : 0.6985\n",
"precision_score : 0.7009864007615241\n",
"recall_score : 0.6985\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
}

View file

@ -1,409 +0,0 @@
{
"cells": [
{
"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",
"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.feature_extraction import text \n",
"\n",
"from sklearn.naive_bayes import GaussianNB\n",
"\n",
"from nltk.tokenize import word_tokenize\n",
"from nltk.probability import FreqDist"
]
},
{
"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": "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>427520</th>\n",
" <td>11</td>\n",
" <td>Guzmania remyi</td>\n",
" <td>Guzmania remyi is a species of plant in the B...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>522145</th>\n",
" <td>14</td>\n",
" <td>Villa Aurore</td>\n",
" <td>Villa Aurore is a novel written in French by ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>462552</th>\n",
" <td>12</td>\n",
" <td>Monk's Casino</td>\n",
" <td>Monk's Casino is a live album by German free ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2460</th>\n",
" <td>1</td>\n",
" <td>Kiss Technology</td>\n",
" <td>Kiss Technology is an entertainment technolog...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>83743</th>\n",
" <td>3</td>\n",
" <td>S.M. Zakir</td>\n",
" <td>S.M. Zakir (born 4 February 1969 in Kota Bhar...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>554887</th>\n",
" <td>14</td>\n",
" <td>New York Law Journal</td>\n",
" <td>The New York Law Journal founded in 1888 is a...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>270857</th>\n",
" <td>7</td>\n",
" <td>Latham United Methodist Church</td>\n",
" <td>Latham United Methodist Church is a historic ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>323989</th>\n",
" <td>9</td>\n",
" <td>Nalavadi</td>\n",
" <td>Nalavadi is a village in Dharwad district in ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>193352</th>\n",
" <td>5</td>\n",
" <td>Richard Ottley (judge)</td>\n",
" <td>Sir Richard Ottley was the 5th Chief Justice ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>78104</th>\n",
" <td>2</td>\n",
" <td>Umatilla High School (Oregon)</td>\n",
" <td>Umatilla High School is a public high school ...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"427520 11 Guzmania remyi \n",
"522145 14 Villa Aurore \n",
"462552 12 Monk's Casino \n",
"2460 1 Kiss Technology \n",
"83743 3 S.M. Zakir \n",
"554887 14 New York Law Journal \n",
"270857 7 Latham United Methodist Church \n",
"323989 9 Nalavadi \n",
"193352 5 Richard Ottley (judge) \n",
"78104 2 Umatilla High School (Oregon) \n",
"\n",
" Text \n",
"427520 Guzmania remyi is a species of plant in the B... \n",
"522145 Villa Aurore is a novel written in French by ... \n",
"462552 Monk's Casino is a live album by German free ... \n",
"2460 Kiss Technology is an entertainment technolog... \n",
"83743 S.M. Zakir (born 4 February 1969 in Kota Bhar... \n",
"554887 The New York Law Journal founded in 1888 is a... \n",
"270857 Latham United Methodist Church is a historic ... \n",
"323989 Nalavadi is a village in Dharwad district in ... \n",
"193352 Sir Richard Ottley was the 5th Chief Justice ... \n",
"78104 Umatilla High School is a public high school ... "
]
},
"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": [],
"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, 217709)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(ngram_range=(2, 2))\n",
"\n",
"feature_vector = count_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"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, 217709)"
]
},
"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": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2, 1, 5, ..., 4, 7, 8])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1812\n",
"accuracy_score : 0.906\n",
"precision_score : 0.9071432275572098\n",
"recall_score : 0.906\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
}

View file

@ -1,405 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"from sklearn.model_selection import train_test_split\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 TfidfVectorizer\n",
"\n",
"from sklearn.naive_bayes import GaussianNB"
]
},
{
"cell_type": "code",
"execution_count": 4,
"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": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(559999, 3)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df['Label'].unique()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"dbpedia_df = dbpedia_df.sample(10000, replace=False)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"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>252405</th>\n",
" <td>7</td>\n",
" <td>Prowers Bridge</td>\n",
" <td>The Prowers Bridge over the Arkansas River ne...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>504457</th>\n",
" <td>13</td>\n",
" <td>Que sera sera (film)</td>\n",
" <td>Que sera sera (Portuguese: Seja o que Deus Qu...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>270494</th>\n",
" <td>7</td>\n",
" <td>The Esplanade (Kenner Louisiana)</td>\n",
" <td>The Esplanade also known as the Esplanade Mal...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>546058</th>\n",
" <td>14</td>\n",
" <td>The 1974 Annual World's Best SF</td>\n",
" <td>The 1974 Annual World's Best SF is an antholo...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>461279</th>\n",
" <td>12</td>\n",
" <td>Just Go (album)</td>\n",
" <td>Just Go is the ninth studio album by American...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>277143</th>\n",
" <td>7</td>\n",
" <td>Steyning Methodist Church</td>\n",
" <td>Steyning Methodist Church is a Methodist plac...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>266867</th>\n",
" <td>7</td>\n",
" <td>Smith Estate (Ridge New York)</td>\n",
" <td>Smith Estate also known as Longwood Estate - ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>283712</th>\n",
" <td>8</td>\n",
" <td>Yr Eifl</td>\n",
" <td>Yr Eifl is a mountain on the north coast of t...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>33861</th>\n",
" <td>1</td>\n",
" <td>IBM India</td>\n",
" <td>IBM India Private Limited is the Indian subsi...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>70953</th>\n",
" <td>2</td>\n",
" <td>Loreto College of Rose-Hill</td>\n",
" <td>Loreto College Rose Hill is a private seconda...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"252405 7 Prowers Bridge \n",
"504457 13 Que sera sera (film) \n",
"270494 7 The Esplanade (Kenner Louisiana) \n",
"546058 14 The 1974 Annual World's Best SF \n",
"461279 12 Just Go (album) \n",
"277143 7 Steyning Methodist Church \n",
"266867 7 Smith Estate (Ridge New York) \n",
"283712 8 Yr Eifl \n",
"33861 1 IBM India \n",
"70953 2 Loreto College of Rose-Hill \n",
"\n",
" Text \n",
"252405 The Prowers Bridge over the Arkansas River ne... \n",
"504457 Que sera sera (Portuguese: Seja o que Deus Qu... \n",
"270494 The Esplanade also known as the Esplanade Mal... \n",
"546058 The 1974 Annual World's Best SF is an antholo... \n",
"461279 Just Go is the ninth studio album by American... \n",
"277143 Steyning Methodist Church is a Methodist plac... \n",
"266867 Smith Estate also known as Longwood Estate - ... \n",
"283712 Yr Eifl is a mountain on the north coast of t... \n",
"33861 IBM India Private Limited is the Indian subsi... \n",
"70953 Loreto College Rose Hill is a private seconda... "
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.sample(10)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 3)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dbpedia_df.shape"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"X = dbpedia_df['Text']\n",
"\n",
"Y = dbpedia_df['Label']"
]
},
{
"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, 48401)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_vectorizer = TfidfVectorizer()\n",
"\n",
"feature_vector = tfidf_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"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, 48401)"
]
},
"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": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([10, 7, 7, ..., 7, 4, 12])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1398\n",
"accuracy_score : 0.699\n",
"precision_score : 0.7100351307095724\n",
"recall_score : 0.699\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
}

View file

@ -1,430 +0,0 @@
{
"cells": [
{
"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",
"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.feature_extraction.text import TfidfTransformer\n",
"\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": "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>445879</th>\n",
" <td>12</td>\n",
" <td>Lucas (album)</td>\n",
" <td>Lucas is the second album by Ghostly Internat...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>120854</th>\n",
" <td>4</td>\n",
" <td>Pat McGehee</td>\n",
" <td>Patrick Henry McGehee (July 2 1888 – December...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>449608</th>\n",
" <td>12</td>\n",
" <td>One Too Many Hearts</td>\n",
" <td>One Too Many Hearts is the third EP by Americ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>171512</th>\n",
" <td>5</td>\n",
" <td>Arken Arystanov</td>\n",
" <td>Arkén Kenesbékovich Arystánov (Kazakh: Аркен ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>26868</th>\n",
" <td>1</td>\n",
" <td>Cineplex Odeon Films</td>\n",
" <td>Cineplex Odeon Films (also known as Cineplex ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>402498</th>\n",
" <td>11</td>\n",
" <td>Steirachne</td>\n",
" <td>Steirachne is a genus of grass in the Poaceae...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>102353</th>\n",
" <td>3</td>\n",
" <td>Harry Thumann</td>\n",
" <td>Harry Thumann (28 February 1952 – 2001) was a...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>337385</th>\n",
" <td>9</td>\n",
" <td>Chah Sheykh</td>\n",
" <td>Chah Sheykh (Persian: چاه شيخ‎ also Romanized...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>485176</th>\n",
" <td>13</td>\n",
" <td>Emmtan-Magan</td>\n",
" <td>Em Magan is a 2006 Tamil drama film directed ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>295129</th>\n",
" <td>8</td>\n",
" <td>Hot Springs Range</td>\n",
" <td>The Hot Springs Range is a mountain range in ...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"445879 12 Lucas (album) \n",
"120854 4 Pat McGehee \n",
"449608 12 One Too Many Hearts \n",
"171512 5 Arken Arystanov \n",
"26868 1 Cineplex Odeon Films \n",
"402498 11 Steirachne \n",
"102353 3 Harry Thumann \n",
"337385 9 Chah Sheykh \n",
"485176 13 Emmtan-Magan \n",
"295129 8 Hot Springs Range \n",
"\n",
" Text \n",
"445879 Lucas is the second album by Ghostly Internat... \n",
"120854 Patrick Henry McGehee (July 2 1888 – December... \n",
"449608 One Too Many Hearts is the third EP by Americ... \n",
"171512 Arkén Kenesbékovich Arystánov (Kazakh: Аркен ... \n",
"26868 Cineplex Odeon Films (also known as Cineplex ... \n",
"402498 Steirachne is a genus of grass in the Poaceae... \n",
"102353 Harry Thumann (28 February 1952 – 2001) was a... \n",
"337385 Chah Sheykh (Persian: چاه شيخ‎ also Romanized... \n",
"485176 Em Magan is a 2006 Tamil drama film directed ... \n",
"295129 The Hot Springs Range is a mountain range in ... "
]
},
"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": 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, 48318)"
]
},
"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": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 48318)"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_transformer = TfidfTransformer()\n",
"\n",
"feature_vector = tfidf_transformer.fit_transform(feature_vector)\n",
"\n",
"feature_vector.shape"
]
},
{
"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, 48318)"
]
},
"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": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 1, 1, 3, ..., 12, 10, 5])"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1438\n",
"accuracy_score : 0.719\n",
"precision_score : 0.7284791775245764\n",
"recall_score : 0.719\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
}

View file

@ -1,430 +0,0 @@
{
"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",
"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.feature_extraction.text import TfidfTransformer\n",
"\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": "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>510378</th>\n",
" <td>13</td>\n",
" <td>Unknown (2006 film)</td>\n",
" <td>Unknown is a 2006 American crime-thriller fil...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>510665</th>\n",
" <td>13</td>\n",
" <td>World Without Sun</td>\n",
" <td>World Without Sun (French: Le Monde sans sole...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>392655</th>\n",
" <td>10</td>\n",
" <td>Argyresthia pseudotsuga</td>\n",
" <td>Argyresthia pseudotsuga is a moth of the Ypon...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>419827</th>\n",
" <td>11</td>\n",
" <td>Erythronium multiscapoideum</td>\n",
" <td>Erythronium multiscapoideum is a species of f...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>217867</th>\n",
" <td>6</td>\n",
" <td>Simca 5</td>\n",
" <td>The Simca 5 is a small Franco-Italian passeng...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>377408</th>\n",
" <td>10</td>\n",
" <td>Bucculatrix zophopasta</td>\n",
" <td>Bucculatrix zophopasta is a moth in the Buccu...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>232485</th>\n",
" <td>6</td>\n",
" <td>HMS Ajax (F114)</td>\n",
" <td>HMS Ajax was a Leander-class frigate of the R...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>327195</th>\n",
" <td>9</td>\n",
" <td>Ruś Ostróda County</td>\n",
" <td>Ruś [ruɕ] (German Reussen) is a village in th...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>478293</th>\n",
" <td>12</td>\n",
" <td>Mortal Kombat: The Album</td>\n",
" <td>Mortal Kombat: The Album is an album by The I...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>533360</th>\n",
" <td>14</td>\n",
" <td>Makers (novel)</td>\n",
" <td>Makers is a novel by Cory Doctorow. It was re...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"510378 13 Unknown (2006 film) \n",
"510665 13 World Without Sun \n",
"392655 10 Argyresthia pseudotsuga \n",
"419827 11 Erythronium multiscapoideum \n",
"217867 6 Simca 5 \n",
"377408 10 Bucculatrix zophopasta \n",
"232485 6 HMS Ajax (F114) \n",
"327195 9 Ruś Ostróda County \n",
"478293 12 Mortal Kombat: The Album \n",
"533360 14 Makers (novel) \n",
"\n",
" Text \n",
"510378 Unknown is a 2006 American crime-thriller fil... \n",
"510665 World Without Sun (French: Le Monde sans sole... \n",
"392655 Argyresthia pseudotsuga is a moth of the Ypon... \n",
"419827 Erythronium multiscapoideum is a species of f... \n",
"217867 The Simca 5 is a small Franco-Italian passeng... \n",
"377408 Bucculatrix zophopasta is a moth in the Buccu... \n",
"232485 HMS Ajax was a Leander-class frigate of the R... \n",
"327195 Ruś [ruɕ] (German Reussen) is a village in th... \n",
"478293 Mortal Kombat: The Album is an album by The I... \n",
"533360 Makers is a novel by Cory Doctorow. It was re... "
]
},
"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": 10,
"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": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47544)"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(min_df=0, max_df=80)\n",
"\n",
"feature_vector = count_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47544)"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_transformer = TfidfTransformer()\n",
"\n",
"feature_vector = tfidf_transformer.fit_transform(feature_vector)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47544)"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 24,
"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": 25,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([10, 4, 1, ..., 13, 6, 2])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1316\n",
"accuracy_score : 0.658\n",
"precision_score : 0.6650727642789968\n",
"recall_score : 0.658\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
}

View file

@ -1,556 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"from sklearn.model_selection import train_test_split\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.feature_extraction.text import TfidfTransformer\n",
"from sklearn.feature_extraction import text \n",
"\n",
"from sklearn.naive_bayes import GaussianNB\n",
"\n",
"from nltk.tokenize import word_tokenize\n",
"from nltk.probability import FreqDist"
]
},
{
"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": "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>179975</th>\n",
" <td>5</td>\n",
" <td>Ramreddy Damodar Reddy</td>\n",
" <td>Ramreddy Damodar Reddy (Telugu: రాంరెడ్డి దామ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>558672</th>\n",
" <td>14</td>\n",
" <td>Sonora Review</td>\n",
" <td>Sonora Review is a biannual graduate student-...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>503492</th>\n",
" <td>13</td>\n",
" <td>Luz en el páramo</td>\n",
" <td>Luz en el páramo is a 1953 Venezuelan film di...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>40980</th>\n",
" <td>2</td>\n",
" <td>Oswaldo Cruz Foundation</td>\n",
" <td>The Oswaldo Cruz Foundation (Portuguese Funda...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>199065</th>\n",
" <td>5</td>\n",
" <td>Tate Reeves</td>\n",
" <td>Jonathon Tate Reeves (born June 5 1974) a Rep...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>20373</th>\n",
" <td>1</td>\n",
" <td>Indie Boyz</td>\n",
" <td>Indie Boyz is a European company based in Lon...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>131192</th>\n",
" <td>4</td>\n",
" <td>Hanna Mazgunova</td>\n",
" <td>Hanna Mazgunova (Belarusian: Ганна Мазгунова;...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>438389</th>\n",
" <td>11</td>\n",
" <td>Platystemon</td>\n",
" <td>Platystemon is a monotypic genus of flowering...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>295233</th>\n",
" <td>8</td>\n",
" <td>Paddys River (South West Slopes New South Wales)</td>\n",
" <td>Paddys River a watercourse of the Murray catc...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>481401</th>\n",
" <td>13</td>\n",
" <td>The Ragged Edge (film)</td>\n",
" <td>The Ragged Edge is a lost 1923 silent film So...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"179975 5 Ramreddy Damodar Reddy \n",
"558672 14 Sonora Review \n",
"503492 13 Luz en el páramo \n",
"40980 2 Oswaldo Cruz Foundation \n",
"199065 5 Tate Reeves \n",
"20373 1 Indie Boyz \n",
"131192 4 Hanna Mazgunova \n",
"438389 11 Platystemon \n",
"295233 8 Paddys River (South West Slopes New South Wales) \n",
"481401 13 The Ragged Edge (film) \n",
"\n",
" Text \n",
"179975 Ramreddy Damodar Reddy (Telugu: రాంరెడ్డి దామ... \n",
"558672 Sonora Review is a biannual graduate student-... \n",
"503492 Luz en el páramo is a 1953 Venezuelan film di... \n",
"40980 The Oswaldo Cruz Foundation (Portuguese Funda... \n",
"199065 Jonathon Tate Reeves (born June 5 1974) a Rep... \n",
"20373 Indie Boyz is a European company based in Lon... \n",
"131192 Hanna Mazgunova (Belarusian: Ганна Мазгунова;... \n",
"438389 Platystemon is a monotypic genus of flowering... \n",
"295233 Paddys River a watercourse of the Murray catc... \n",
"481401 The Ragged Edge is a lost 1923 silent film So... "
]
},
"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": [],
"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": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"504495"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tokens = word_tokenize(\"\\n\".join(X.values))\n",
"\n",
"len(tokens)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"FreqDist({'the': 23494, '.': 23437, 'in': 16379, 'of': 15332, 'is': 13499, 'and': 12934, 'a': 12862, '(': 7204, ')': 7199, 'was': 6950, ...})"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"freq = FreqDist(tokens)\n",
"freq"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"487"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequent_words = []\n",
"\n",
"for key, value in freq.items():\n",
" if value >= 100:\n",
" frequent_words.append(key.lower())\n",
" \n",
"len(frequent_words)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['(',\n",
" ':',\n",
" '[',\n",
" ']',\n",
" '.',\n",
" ')',\n",
" 'is',\n",
" 'a',\n",
" 'lake',\n",
" 'in',\n",
" 'located',\n",
" 'north',\n",
" 'of',\n",
" 'the',\n",
" 'town',\n",
" 'district',\n",
" 'not',\n",
" '1',\n",
" 'the',\n",
" 'area',\n",
" 'by',\n",
" 'including',\n",
" '2001',\n",
" 'was',\n",
" 'international']"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"frequent_words[:25]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"stop_words = text.ENGLISH_STOP_WORDS.union(frequent_words)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47573)"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(stop_words=stop_words)\n",
"\n",
"feature_vector = count_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47573)"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_transformer = TfidfTransformer()\n",
"\n",
"feature_vector = tfidf_transformer.fit_transform(feature_vector)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 47573)"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 23,
"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": 24,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 7, 7, 1, ..., 13, 14, 11])"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1335\n",
"accuracy_score : 0.6675\n",
"precision_score : 0.6803619205404001\n",
"recall_score : 0.6675\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
}

View file

@ -1,430 +0,0 @@
{
"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",
"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.feature_extraction.text import TfidfTransformer\n",
"\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": "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>521705</th>\n",
" <td>14</td>\n",
" <td>Woodstock (novel)</td>\n",
" <td>Woodstock or The Cavalier. A Tale of the Year...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>373693</th>\n",
" <td>10</td>\n",
" <td>Cryptophagidae</td>\n",
" <td>Cryptophagidae is a family of beetles with re...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>333934</th>\n",
" <td>9</td>\n",
" <td>Dehliz-e Yek</td>\n",
" <td>Dehliz-e Yek (Persian: دهليزيك‎ also Romanize...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>125305</th>\n",
" <td>4</td>\n",
" <td>Roland Osabutey</td>\n",
" <td>Roland Osabutey (born 11 March 1980) is a Gha...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>100866</th>\n",
" <td>3</td>\n",
" <td>Ann Voskamp</td>\n",
" <td>Ann Voskamp (born August 10 1973 in Listowel ...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>58320</th>\n",
" <td>2</td>\n",
" <td>Robert Bateman High School</td>\n",
" <td>Robert Bateman High School (also known as Rob...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>419470</th>\n",
" <td>11</td>\n",
" <td>Vriesea languida</td>\n",
" <td>Vriesea languida is a species of the genus Vr...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>164430</th>\n",
" <td>5</td>\n",
" <td>Gilbert Wellington Ostrom</td>\n",
" <td>Gilbert Wellington Ostrom (June 1837 – Decemb...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>426098</th>\n",
" <td>11</td>\n",
" <td>Banara regia</td>\n",
" <td>Banara regia is a species of plant in the Sal...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>281236</th>\n",
" <td>8</td>\n",
" <td>Calder River (Western Australia)</td>\n",
" <td>For other Rivers Calder see River Calder (dis...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Label Name \\\n",
"521705 14 Woodstock (novel) \n",
"373693 10 Cryptophagidae \n",
"333934 9 Dehliz-e Yek \n",
"125305 4 Roland Osabutey \n",
"100866 3 Ann Voskamp \n",
"58320 2 Robert Bateman High School \n",
"419470 11 Vriesea languida \n",
"164430 5 Gilbert Wellington Ostrom \n",
"426098 11 Banara regia \n",
"281236 8 Calder River (Western Australia) \n",
"\n",
" Text \n",
"521705 Woodstock or The Cavalier. A Tale of the Year... \n",
"373693 Cryptophagidae is a family of beetles with re... \n",
"333934 Dehliz-e Yek (Persian: دهليزيك‎ also Romanize... \n",
"125305 Roland Osabutey (born 11 March 1980) is a Gha... \n",
"100866 Ann Voskamp (born August 10 1973 in Listowel ... \n",
"58320 Robert Bateman High School (also known as Rob... \n",
"419470 Vriesea languida is a species of the genus Vr... \n",
"164430 Gilbert Wellington Ostrom (June 1837 – Decemb... \n",
"426098 Banara regia is a species of plant in the Sal... \n",
"281236 For other Rivers Calder see River Calder (dis... "
]
},
"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": [],
"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": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 217434)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"count_vectorizer = CountVectorizer(min_df=0, max_df=80, ngram_range=(2, 2))\n",
"\n",
"feature_vector = count_vectorizer.fit_transform(X)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 217434)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tfidf_transformer = TfidfTransformer()\n",
"\n",
"feature_vector = tfidf_transformer.fit_transform(feature_vector)\n",
"\n",
"feature_vector.shape"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"X_dense = feature_vector.todense()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10000, 217434)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_dense.shape"
]
},
{
"cell_type": "code",
"execution_count": 14,
"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": 15,
"metadata": {},
"outputs": [],
"source": [
"clf = GaussianNB().fit(x_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 7, 12, 6, ..., 1, 12, 3])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y_pred = clf.predict(x_test)\n",
"y_pred"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of testing data: 2000\n",
"accuracy_count : 1778\n",
"accuracy_score : 0.889\n",
"precision_score : 0.8902761517734769\n",
"recall_score : 0.889\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
}

File diff suppressed because one or more lines are too long

View file

@ -1,804 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting ml_metrics\n",
" Downloading ml_metrics-0.1.4.tar.gz (5.0 kB)\n",
"Requirement already satisfied: numpy in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from ml_metrics) (1.24.2)\n",
"Requirement already satisfied: pandas in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from ml_metrics) (2.0.0)\n",
"Requirement already satisfied: tzdata>=2022.1 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2023.3)\n",
"Requirement already satisfied: python-dateutil>=2.8.2 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2.8.2)\n",
"Requirement already satisfied: pytz>=2020.1 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2023.3)\n",
"Requirement already satisfied: six>=1.5 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas->ml_metrics) (1.16.0)\n",
"Building wheels for collected packages: ml-metrics\n",
" Building wheel for ml-metrics (setup.py) ... \u001b[?25ldone\n",
"\u001b[?25h Created wheel for ml-metrics: filename=ml_metrics-0.1.4-py3-none-any.whl size=7844 sha256=64666abeb3d0e3c053380dc33e8580a115a4fe6239401464b56bce42a3e678cd\n",
" Stored in directory: /home/shoney/.cache/pip/wheels/c6/b2/69/0691b3d4de7c8d0c604cd7de94f4b2d4478a04ce3b6e4bab15\n",
"Successfully built ml-metrics\n",
"Installing collected packages: ml-metrics\n",
"Successfully installed ml-metrics-0.1.4\n",
"\u001b[33mWARNING: You are using pip version 21.2.3; however, version 23.0.1 is available.\n",
"You should consider upgrading via the '/home/shoney/devnlp/.venv/bin/python -m pip install --upgrade pip' command.\u001b[0m\n"
]
}
],
"source": [
"!python -m pip install ml_metrics"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn.functional as F\n",
"\n",
"from torch import nn\n",
"from torch.utils.data import Dataset\n",
"from torch.utils.data import DataLoader\n",
"\n",
"import heapq\n",
"import math\n",
"\n",
"import scipy.sparse as sp\n",
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"import ml_metrics as metrics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"https://grouplens.org/datasets/movielens/"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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>userId</th>\n",
" <th>movieId</th>\n",
" <th>rating</th>\n",
" <th>timestamp</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" <td>4.0</td>\n",
" <td>964982703</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>1</td>\n",
" <td>3</td>\n",
" <td>4.0</td>\n",
" <td>964981247</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>1</td>\n",
" <td>6</td>\n",
" <td>4.0</td>\n",
" <td>964982224</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>1</td>\n",
" <td>47</td>\n",
" <td>5.0</td>\n",
" <td>964983815</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>1</td>\n",
" <td>50</td>\n",
" <td>5.0</td>\n",
" <td>964982931</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" userId movieId rating timestamp\n",
"0 1 1 4.0 964982703\n",
"1 1 3 4.0 964981247\n",
"2 1 6 4.0 964982224\n",
"3 1 47 5.0 964983815\n",
"4 1 50 5.0 964982931"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie_data = pd.read_csv('datasets/movies/ml-latest-small/ratings.csv', \n",
" sep=',', header=0)\n",
"\n",
"movie_data.head()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(100836, 4)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie_data.shape"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"610"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"NUM_USERS = movie_data['userId'].max()\n",
"\n",
"NUM_USERS"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"193609"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"NUM_ITEMS = movie_data['movieId'].max()\n",
"\n",
"NUM_ITEMS"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"TEST_USER_IDS = [5, 24, 45, 67, 89, 123, 239, 345, 456, 598]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"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>userId</th>\n",
" <th>movieId</th>\n",
" <th>rating</th>\n",
" <th>timestamp</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>516</th>\n",
" <td>5</td>\n",
" <td>1</td>\n",
" <td>4.0</td>\n",
" <td>847434962</td>\n",
" </tr>\n",
" <tr>\n",
" <th>517</th>\n",
" <td>5</td>\n",
" <td>21</td>\n",
" <td>4.0</td>\n",
" <td>847435238</td>\n",
" </tr>\n",
" <tr>\n",
" <th>518</th>\n",
" <td>5</td>\n",
" <td>34</td>\n",
" <td>4.0</td>\n",
" <td>847434881</td>\n",
" </tr>\n",
" <tr>\n",
" <th>519</th>\n",
" <td>5</td>\n",
" <td>36</td>\n",
" <td>4.0</td>\n",
" <td>847435292</td>\n",
" </tr>\n",
" <tr>\n",
" <th>520</th>\n",
" <td>5</td>\n",
" <td>39</td>\n",
" <td>3.0</td>\n",
" <td>847434961</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" userId movieId rating timestamp\n",
"516 5 1 4.0 847434962\n",
"517 5 21 4.0 847435238\n",
"518 5 34 4.0 847434881\n",
"519 5 36 4.0 847435292\n",
"520 5 39 3.0 847434961"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_movie_users = movie_data[movie_data['userId'].isin(TEST_USER_IDS)]\n",
"\n",
"test_movie_users.head()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"def load_ratings_matrix(movie_data):\n",
"\n",
" ratings_matrix = sp.dok_matrix((NUM_USERS + 1, NUM_ITEMS + 1), dtype=np.float32)\n",
"\n",
" for index, row in movie_data.iterrows():\n",
" user, item, rating = int(row['userId']), int(row['movieId']), float(row['rating'])\n",
" \n",
" ratings_matrix[user, item] = rating\n",
" \n",
" random_user = np.random.randint(1, NUM_USERS)\n",
" \n",
" return ratings_matrix"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(611, 193610)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ratings_matrix = load_ratings_matrix(movie_data)\n",
"\n",
"ratings_matrix.shape"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"class RecommenderNN(nn.Module):\n",
"\n",
" def __init__(self, n_users, n_items, layers=[24, 16], dropout=0.2):\n",
"\n",
" super().__init__()\n",
"\n",
" assert (layers[0] % 2 == 0), \"layers[0] must be an even number\"\n",
"\n",
" self.dropout = dropout\n",
"\n",
" embedding_dim = int(layers[0] / 2)\n",
"\n",
" self.user_embedding = torch.nn.Embedding(n_users, embedding_dim)\n",
" self.item_embedding = torch.nn.Embedding(n_items, embedding_dim)\n",
"\n",
" self.fc_layers = torch.nn.ModuleList()\n",
"\n",
" for _, (in_size, out_size) in enumerate(zip(layers[:-1], layers[1:])):\n",
" self.fc_layers.append(torch.nn.Linear(in_size, out_size))\n",
"\n",
" # Output of the last layer is just 1 for predicting ratings values\n",
" self.output_layer = torch.nn.Linear(layers[-1], 1)\n",
"\n",
" def forward(self, users, items):\n",
" user_embedding = self.user_embedding(users)\n",
" item_embedding = self.item_embedding(items)\n",
"\n",
" # Concatenate user and item embeddings, this is the input to the NN\n",
" x = torch.cat([user_embedding, item_embedding], 1)\n",
" \n",
" for idx, _ in enumerate(range(len(self.fc_layers))):\n",
" x = self.fc_layers[idx](x)\n",
" x = F.relu(x)\n",
" x = F.dropout(x, p=self.dropout, training=self.training)\n",
" \n",
" rating = self.output_layer(x)\n",
"\n",
" return rating\n",
"\n",
" def predict(self, users, items):\n",
" output_scores = self.forward(users, items)\n",
"\n",
" return output_scores.cpu().detach().numpy()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"def generate_training_instances(ratings_matrix):\n",
" \n",
" user_item_ratings = {}\n",
" index = 0\n",
" \n",
" for user, item in ratings_matrix.keys():\n",
" \n",
" user_item_ratings[index] = (user, item, ratings_matrix[user, item])\n",
" index += 1\n",
" \n",
" return user_item_ratings"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"100836"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_user_item_ratings = generate_training_instances(ratings_matrix)\n",
"\n",
"len(train_user_item_ratings)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((1, 1, 4.0), (1, 47, 5.0))"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_user_item_ratings[0], train_user_item_ratings[3]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"def train(model, train_data_loader, criterion, optimizer, epoch):\n",
" \n",
" model.train()\n",
" \n",
" epoch_loss = []\n",
" \n",
" for users_items_rating in train_data_loader:\n",
" \n",
" users, items, ratings = users_items_rating\n",
" \n",
" predictions = model(users, items)\n",
" \n",
" # Convert to float and change dim from [batch_size] to [batch_size, 1]\n",
" ratings = ratings.float().view(predictions.size())\n",
" \n",
" loss = criterion(predictions, ratings)\n",
" \n",
" optimizer.zero_grad()\n",
" loss.backward()\n",
" \n",
" optimizer.step()\n",
" \n",
" epoch_loss.append(loss.item())\n",
" \n",
" epoch_loss = np.mean(epoch_loss)\n",
"\n",
" print(\"Epoch completed\", epoch)\n",
" \n",
" print(\"Train Loss: {%.4f}\" % (epoch_loss))"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"def load_zero_rated(ratings_matrix, user_id, user_item_ratings): \n",
" \n",
" for i in range(100):\n",
" potential_zero_item = np.random.randint(1, NUM_ITEMS)\n",
" \n",
" while (user_id, potential_zero_item) in ratings_matrix:\n",
" potential_zero_item = np.random.randint(1, NUM_ITEMS)\n",
" \n",
" user_item_ratings['users'] = \\\n",
" np.append(user_item_ratings['users'], np.array([user_id]))\n",
" \n",
" user_item_ratings['items'] = \\\n",
" np.append(user_item_ratings['items'], np.array([potential_zero_item]))\n",
" \n",
" user_item_ratings['ratings'] = \\\n",
" np.append(user_item_ratings['ratings'], np.array([0]))"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"def generate_test_instances(ratings_matrix, test_movie_users):\n",
"\n",
" test_list = []\n",
"\n",
" for user_id in TEST_USER_IDS:\n",
" \n",
" user_item_ratings_df = test_movie_users[test_movie_users['userId'] == user_id]\n",
" user_item_ratings_df = user_item_ratings_df[user_item_ratings_df['rating'] >= 4]\n",
" \n",
" user_item_ratings = {}\n",
" \n",
" user_item_ratings['users'] = user_item_ratings_df['userId'].values[5:15]\n",
" user_item_ratings['items'] = user_item_ratings_df['movieId'].values[5:15]\n",
" user_item_ratings['ratings'] = user_item_ratings_df['rating'].values[5:15]\n",
" \n",
" load_zero_rated(ratings_matrix, user_id, user_item_ratings)\n",
" \n",
" test_list.append(user_item_ratings)\n",
" \n",
" return test_list"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_list = generate_test_instances(ratings_matrix, test_movie_users)\n",
"\n",
"len(test_list)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'users': array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]),\n",
" 'items': array([ 58, 110, 232, 247, 261, 290, 296, 367,\n",
" 457, 474, 41345, 182631, 18197, 161233, 1394, 28011,\n",
" 153917, 106034, 66187, 75510, 49438, 113499, 147983, 87947,\n",
" 1317, 74295, 35966, 161110, 32435, 173278, 79787, 10751,\n",
" 193599, 29238, 75645, 76407, 63576, 24895, 101984, 16391,\n",
" 142290, 173458, 9300, 35324, 107225, 140507, 37249, 3218,\n",
" 160625, 165951, 179351, 119584, 88598, 53641, 134842, 34138,\n",
" 95809, 8508, 182036, 93082, 682, 78318, 147539, 74603,\n",
" 103683, 5886, 91604, 4666, 88695, 112021, 117019, 133707,\n",
" 37857, 118359, 137635, 162022, 2682, 30608, 182844, 190418,\n",
" 107332, 20338, 168671, 61775, 42716, 8339, 117789, 139293,\n",
" 124305, 116739, 161583, 182707, 89498, 68145, 45189, 86044,\n",
" 8997, 4850, 95155, 103539, 5542, 180133, 139242, 15780,\n",
" 172943, 100142, 75835, 57258, 158875, 111896]),\n",
" 'ratings': array([5., 4., 4., 5., 4., 5., 5., 4., 4., 4., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
" 0., 0., 0., 0., 0., 0., 0., 0.])}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_list[0]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"def evaluate(model, test_list):\n",
"\n",
" model.eval()\n",
" \n",
" apks = []\n",
"\n",
" for user_item_ratings in test_list:\n",
" \n",
" users = torch.tensor(user_item_ratings['users'])\n",
" items = torch.tensor(user_item_ratings['items'])\n",
" ratings = user_item_ratings['ratings']\n",
"\n",
" predictions = model.predict(users, items)\n",
" \n",
" item_score_map = {}\n",
" \n",
" for i, item in enumerate(user_item_ratings['items']):\n",
" item_score_map[item] = predictions[i]\n",
" \n",
" rank_list = heapq.nlargest(100, item_score_map, key=item_score_map.get)\n",
" \n",
" items_list = items.detach().numpy().tolist()\n",
" rank_list = list(rank_list)\n",
"\n",
" apk = metrics.apk(items_list[:10], rank_list[:10])\n",
" \n",
" apks.append(apk)\n",
" \n",
" \n",
" print(\"Evaluation mean APK : {%.4f}\" % np.mean(apks))"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"model = RecommenderNN(NUM_USERS + 1, NUM_ITEMS + 1, [32, 16, 8], dropout=0.2)\n",
"\n",
"criterion = torch.nn.MSELoss()\n",
"\n",
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.00001)\n",
"\n",
"num_epochs = 15"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"train_data_loader = DataLoader(\n",
" train_user_item_ratings, batch_size=100, shuffle=True, num_workers=0)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch completed 1\n",
"Train Loss: {3.8352}\n",
"Evaluation mean APK : {0.3372}\n",
"Epoch completed 2\n",
"Train Loss: {1.9782}\n",
"Evaluation mean APK : {0.5797}\n",
"Epoch completed 3\n",
"Train Loss: {1.6262}\n",
"Evaluation mean APK : {0.6027}\n",
"Epoch completed 4\n",
"Train Loss: {1.3538}\n",
"Evaluation mean APK : {0.6400}\n",
"Epoch completed 5\n",
"Train Loss: {1.1500}\n",
"Evaluation mean APK : {0.6572}\n",
"Epoch completed 6\n",
"Train Loss: {1.0243}\n",
"Evaluation mean APK : {0.6789}\n",
"Epoch completed 7\n",
"Train Loss: {0.9205}\n",
"Evaluation mean APK : {0.6739}\n",
"Epoch completed 8\n",
"Train Loss: {0.8565}\n",
"Evaluation mean APK : {0.6737}\n",
"Epoch completed 9\n",
"Train Loss: {0.8117}\n",
"Evaluation mean APK : {0.6656}\n",
"Epoch completed 10\n",
"Train Loss: {0.7896}\n",
"Evaluation mean APK : {0.6895}\n",
"Epoch completed 11\n",
"Train Loss: {0.7712}\n",
"Evaluation mean APK : {0.6838}\n",
"Epoch completed 12\n",
"Train Loss: {0.7581}\n",
"Evaluation mean APK : {0.6748}\n",
"Epoch completed 13\n",
"Train Loss: {0.7449}\n",
"Evaluation mean APK : {0.6870}\n",
"Epoch completed 14\n",
"Train Loss: {0.7389}\n",
"Evaluation mean APK : {0.6726}\n",
"Epoch completed 15\n",
"Train Loss: {0.7302}\n",
"Evaluation mean APK : {0.6421}\n"
]
}
],
"source": [
"for epoch in range(1, num_epochs + 1):\n",
" \n",
" train(model, train_data_loader, criterion, optimizer, epoch)\n",
" evaluate(model, test_list)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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
}

View file

@ -1,534 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### GloVe vectors\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Embeddings transform a one-hot encoded vector (a vector that is 0 in elements except one, which is 1) into a much smaller dimension vector of real numbers. The one-hot encoded vector is also known as a sparse vector, whilst the real valued vector is known as a dense vector.\n",
"\n",
"The key concept in these word embeddings is that words that appear in similar contexts appear nearby in the vector space, i.e. the Euclidean distance between these two word vectors is small.\n",
"\n",
"https://github.com/spro/practical-pytorch/blob/master/glove-word-vectors/glove-word-vectors.ipynb"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torchtext.vocab"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Load GloVe vectors\n",
"First, we'll load the GloVe vectors. The name field specifies what the vectors have been trained on, here the 6B means a corpus of 6 billion words."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
".vector_cache/glove.6B.zip: 0.00B [00:10, ?B/s]\n"
]
},
{
"ename": "URLError",
"evalue": "<urlopen error [Errno -3] Temporary failure in name resolution>",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mgaierror\u001b[0m Traceback (most recent call last)",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1346\u001b[0m, in \u001b[0;36mAbstractHTTPHandler.do_open\u001b[0;34m(self, http_class, req, **http_conn_args)\u001b[0m\n\u001b[1;32m 1345\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[0;32m-> 1346\u001b[0m h\u001b[39m.\u001b[39;49mrequest(req\u001b[39m.\u001b[39;49mget_method(), req\u001b[39m.\u001b[39;49mselector, req\u001b[39m.\u001b[39;49mdata, headers,\n\u001b[1;32m 1347\u001b[0m encode_chunked\u001b[39m=\u001b[39;49mreq\u001b[39m.\u001b[39;49mhas_header(\u001b[39m'\u001b[39;49m\u001b[39mTransfer-encoding\u001b[39;49m\u001b[39m'\u001b[39;49m))\n\u001b[1;32m 1348\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mOSError\u001b[39;00m \u001b[39mas\u001b[39;00m err: \u001b[39m# timeout error\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1279\u001b[0m, in \u001b[0;36mHTTPConnection.request\u001b[0;34m(self, method, url, body, headers, encode_chunked)\u001b[0m\n\u001b[1;32m 1278\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"Send a complete request to the server.\"\"\"\u001b[39;00m\n\u001b[0;32m-> 1279\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_send_request(method, url, body, headers, encode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1325\u001b[0m, in \u001b[0;36mHTTPConnection._send_request\u001b[0;34m(self, method, url, body, headers, encode_chunked)\u001b[0m\n\u001b[1;32m 1324\u001b[0m body \u001b[39m=\u001b[39m _encode(body, \u001b[39m'\u001b[39m\u001b[39mbody\u001b[39m\u001b[39m'\u001b[39m)\n\u001b[0;32m-> 1325\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mendheaders(body, encode_chunked\u001b[39m=\u001b[39;49mencode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1274\u001b[0m, in \u001b[0;36mHTTPConnection.endheaders\u001b[0;34m(self, message_body, encode_chunked)\u001b[0m\n\u001b[1;32m 1273\u001b[0m \u001b[39mraise\u001b[39;00m CannotSendHeader()\n\u001b[0;32m-> 1274\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_send_output(message_body, encode_chunked\u001b[39m=\u001b[39;49mencode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1034\u001b[0m, in \u001b[0;36mHTTPConnection._send_output\u001b[0;34m(self, message_body, encode_chunked)\u001b[0m\n\u001b[1;32m 1033\u001b[0m \u001b[39mdel\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_buffer[:]\n\u001b[0;32m-> 1034\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49msend(msg)\n\u001b[1;32m 1036\u001b[0m \u001b[39mif\u001b[39;00m message_body \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 1037\u001b[0m \n\u001b[1;32m 1038\u001b[0m \u001b[39m# create a consistent interface to message_body\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:974\u001b[0m, in \u001b[0;36mHTTPConnection.send\u001b[0;34m(self, data)\u001b[0m\n\u001b[1;32m 973\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mauto_open:\n\u001b[0;32m--> 974\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mconnect()\n\u001b[1;32m 975\u001b[0m \u001b[39melse\u001b[39;00m:\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:945\u001b[0m, in \u001b[0;36mHTTPConnection.connect\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 944\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"Connect to the host and port specified in __init__.\"\"\"\u001b[39;00m\n\u001b[0;32m--> 945\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39msock \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_create_connection(\n\u001b[1;32m 946\u001b[0m (\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mhost,\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mport), \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mtimeout, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49msource_address)\n\u001b[1;32m 947\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39msock\u001b[39m.\u001b[39msetsockopt(socket\u001b[39m.\u001b[39mIPPROTO_TCP, socket\u001b[39m.\u001b[39mTCP_NODELAY, \u001b[39m1\u001b[39m)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/socket.py:823\u001b[0m, in \u001b[0;36mcreate_connection\u001b[0;34m(address, timeout, source_address)\u001b[0m\n\u001b[1;32m 822\u001b[0m err \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[0;32m--> 823\u001b[0m \u001b[39mfor\u001b[39;00m res \u001b[39min\u001b[39;00m getaddrinfo(host, port, \u001b[39m0\u001b[39;49m, SOCK_STREAM):\n\u001b[1;32m 824\u001b[0m af, socktype, proto, canonname, sa \u001b[39m=\u001b[39m res\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/socket.py:954\u001b[0m, in \u001b[0;36mgetaddrinfo\u001b[0;34m(host, port, family, type, proto, flags)\u001b[0m\n\u001b[1;32m 953\u001b[0m addrlist \u001b[39m=\u001b[39m []\n\u001b[0;32m--> 954\u001b[0m \u001b[39mfor\u001b[39;00m res \u001b[39min\u001b[39;00m _socket\u001b[39m.\u001b[39;49mgetaddrinfo(host, port, family, \u001b[39mtype\u001b[39;49m, proto, flags):\n\u001b[1;32m 955\u001b[0m af, socktype, proto, canonname, sa \u001b[39m=\u001b[39m res\n",
"\u001b[0;31mgaierror\u001b[0m: [Errno -3] Temporary failure in name resolution",
"\nDuring handling of the above exception, another exception occurred:\n",
"\u001b[0;31mURLError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[5], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove \u001b[39m=\u001b[39m torchtext\u001b[39m.\u001b[39;49mvocab\u001b[39m.\u001b[39;49mGloVe(name\u001b[39m=\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39m6B\u001b[39;49m\u001b[39m'\u001b[39;49m, dim\u001b[39m=\u001b[39;49m\u001b[39m100\u001b[39;49m)\n\u001b[1;32m 3\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m'\u001b[39m\u001b[39mThere are \u001b[39m\u001b[39m{\u001b[39;00m\u001b[39mlen\u001b[39m(glove\u001b[39m.\u001b[39mitos)\u001b[39m}\u001b[39;00m\u001b[39m words in the vocabulary\u001b[39m\u001b[39m'\u001b[39m)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:220\u001b[0m, in \u001b[0;36mGloVe.__init__\u001b[0;34m(self, name, dim, **kwargs)\u001b[0m\n\u001b[1;32m 218\u001b[0m url \u001b[39m=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39murl[name]\n\u001b[1;32m 219\u001b[0m name \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mglove.\u001b[39m\u001b[39m{}\u001b[39;00m\u001b[39m.\u001b[39m\u001b[39m{}\u001b[39;00m\u001b[39md.txt\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m.\u001b[39mformat(name, \u001b[39mstr\u001b[39m(dim))\n\u001b[0;32m--> 220\u001b[0m \u001b[39msuper\u001b[39;49m(GloVe, \u001b[39mself\u001b[39;49m)\u001b[39m.\u001b[39;49m\u001b[39m__init__\u001b[39;49m(name, url\u001b[39m=\u001b[39;49murl, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:59\u001b[0m, in \u001b[0;36mVectors.__init__\u001b[0;34m(self, name, cache, url, unk_init, max_vectors)\u001b[0m\n\u001b[1;32m 57\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mdim \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[1;32m 58\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39munk_init \u001b[39m=\u001b[39m torch\u001b[39m.\u001b[39mTensor\u001b[39m.\u001b[39mzero_ \u001b[39mif\u001b[39;00m unk_init \u001b[39mis\u001b[39;00m \u001b[39mNone\u001b[39;00m \u001b[39melse\u001b[39;00m unk_init\n\u001b[0;32m---> 59\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mcache(name, cache, url\u001b[39m=\u001b[39;49murl, max_vectors\u001b[39m=\u001b[39;49mmax_vectors)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:95\u001b[0m, in \u001b[0;36mVectors.cache\u001b[0;34m(self, name, cache, url, max_vectors)\u001b[0m\n\u001b[1;32m 93\u001b[0m \u001b[39mwith\u001b[39;00m tqdm(unit\u001b[39m=\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mB\u001b[39m\u001b[39m\"\u001b[39m, unit_scale\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m, miniters\u001b[39m=\u001b[39m\u001b[39m1\u001b[39m, desc\u001b[39m=\u001b[39mdest) \u001b[39mas\u001b[39;00m t:\n\u001b[1;32m 94\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[0;32m---> 95\u001b[0m urlretrieve(url, dest, reporthook\u001b[39m=\u001b[39;49mreporthook(t))\n\u001b[1;32m 96\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mKeyboardInterrupt\u001b[39;00m \u001b[39mas\u001b[39;00m e: \u001b[39m# remove the partial zip file\u001b[39;00m\n\u001b[1;32m 97\u001b[0m os\u001b[39m.\u001b[39mremove(dest)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:239\u001b[0m, in \u001b[0;36murlretrieve\u001b[0;34m(url, filename, reporthook, data)\u001b[0m\n\u001b[1;32m 222\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 223\u001b[0m \u001b[39mRetrieve a URL into a temporary location on disk.\u001b[39;00m\n\u001b[1;32m 224\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 235\u001b[0m \u001b[39mdata file as well as the resulting HTTPMessage object.\u001b[39;00m\n\u001b[1;32m 236\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 237\u001b[0m url_type, path \u001b[39m=\u001b[39m _splittype(url)\n\u001b[0;32m--> 239\u001b[0m \u001b[39mwith\u001b[39;00m contextlib\u001b[39m.\u001b[39mclosing(urlopen(url, data)) \u001b[39mas\u001b[39;00m fp:\n\u001b[1;32m 240\u001b[0m headers \u001b[39m=\u001b[39m fp\u001b[39m.\u001b[39minfo()\n\u001b[1;32m 242\u001b[0m \u001b[39m# Just return the local path and the \"headers\" for file://\u001b[39;00m\n\u001b[1;32m 243\u001b[0m \u001b[39m# URLs. No sense in performing a copy unless requested.\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:214\u001b[0m, in \u001b[0;36murlopen\u001b[0;34m(url, data, timeout, cafile, capath, cadefault, context)\u001b[0m\n\u001b[1;32m 212\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[1;32m 213\u001b[0m opener \u001b[39m=\u001b[39m _opener\n\u001b[0;32m--> 214\u001b[0m \u001b[39mreturn\u001b[39;00m opener\u001b[39m.\u001b[39;49mopen(url, data, timeout)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:517\u001b[0m, in \u001b[0;36mOpenerDirector.open\u001b[0;34m(self, fullurl, data, timeout)\u001b[0m\n\u001b[1;32m 514\u001b[0m req \u001b[39m=\u001b[39m meth(req)\n\u001b[1;32m 516\u001b[0m sys\u001b[39m.\u001b[39maudit(\u001b[39m'\u001b[39m\u001b[39murllib.Request\u001b[39m\u001b[39m'\u001b[39m, req\u001b[39m.\u001b[39mfull_url, req\u001b[39m.\u001b[39mdata, req\u001b[39m.\u001b[39mheaders, req\u001b[39m.\u001b[39mget_method())\n\u001b[0;32m--> 517\u001b[0m response \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_open(req, data)\n\u001b[1;32m 519\u001b[0m \u001b[39m# post-process response\u001b[39;00m\n\u001b[1;32m 520\u001b[0m meth_name \u001b[39m=\u001b[39m protocol\u001b[39m+\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m_response\u001b[39m\u001b[39m\"\u001b[39m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:534\u001b[0m, in \u001b[0;36mOpenerDirector._open\u001b[0;34m(self, req, data)\u001b[0m\n\u001b[1;32m 531\u001b[0m \u001b[39mreturn\u001b[39;00m result\n\u001b[1;32m 533\u001b[0m protocol \u001b[39m=\u001b[39m req\u001b[39m.\u001b[39mtype\n\u001b[0;32m--> 534\u001b[0m result \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_call_chain(\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mhandle_open, protocol, protocol \u001b[39m+\u001b[39;49m\n\u001b[1;32m 535\u001b[0m \u001b[39m'\u001b[39;49m\u001b[39m_open\u001b[39;49m\u001b[39m'\u001b[39;49m, req)\n\u001b[1;32m 536\u001b[0m \u001b[39mif\u001b[39;00m result:\n\u001b[1;32m 537\u001b[0m \u001b[39mreturn\u001b[39;00m result\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:494\u001b[0m, in \u001b[0;36mOpenerDirector._call_chain\u001b[0;34m(self, chain, kind, meth_name, *args)\u001b[0m\n\u001b[1;32m 492\u001b[0m \u001b[39mfor\u001b[39;00m handler \u001b[39min\u001b[39;00m handlers:\n\u001b[1;32m 493\u001b[0m func \u001b[39m=\u001b[39m \u001b[39mgetattr\u001b[39m(handler, meth_name)\n\u001b[0;32m--> 494\u001b[0m result \u001b[39m=\u001b[39m func(\u001b[39m*\u001b[39;49margs)\n\u001b[1;32m 495\u001b[0m \u001b[39mif\u001b[39;00m result \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 496\u001b[0m \u001b[39mreturn\u001b[39;00m result\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1375\u001b[0m, in \u001b[0;36mHTTPHandler.http_open\u001b[0;34m(self, req)\u001b[0m\n\u001b[1;32m 1374\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mhttp_open\u001b[39m(\u001b[39mself\u001b[39m, req):\n\u001b[0;32m-> 1375\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mdo_open(http\u001b[39m.\u001b[39;49mclient\u001b[39m.\u001b[39;49mHTTPConnection, req)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1349\u001b[0m, in \u001b[0;36mAbstractHTTPHandler.do_open\u001b[0;34m(self, http_class, req, **http_conn_args)\u001b[0m\n\u001b[1;32m 1346\u001b[0m h\u001b[39m.\u001b[39mrequest(req\u001b[39m.\u001b[39mget_method(), req\u001b[39m.\u001b[39mselector, req\u001b[39m.\u001b[39mdata, headers,\n\u001b[1;32m 1347\u001b[0m encode_chunked\u001b[39m=\u001b[39mreq\u001b[39m.\u001b[39mhas_header(\u001b[39m'\u001b[39m\u001b[39mTransfer-encoding\u001b[39m\u001b[39m'\u001b[39m))\n\u001b[1;32m 1348\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mOSError\u001b[39;00m \u001b[39mas\u001b[39;00m err: \u001b[39m# timeout error\u001b[39;00m\n\u001b[0;32m-> 1349\u001b[0m \u001b[39mraise\u001b[39;00m URLError(err)\n\u001b[1;32m 1350\u001b[0m r \u001b[39m=\u001b[39m h\u001b[39m.\u001b[39mgetresponse()\n\u001b[1;32m 1351\u001b[0m \u001b[39mexcept\u001b[39;00m:\n",
"\u001b[0;31mURLError\u001b[0m: <urlopen error [Errno -3] Temporary failure in name resolution>"
]
}
],
"source": [
"glove = torchtext.vocab.GloVe(name='6B', dim=100)\n",
"\n",
"print(f'There are {len(glove.itos)} words in the vocabulary')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In these set of GloVe vectors, every single word is lower-case only."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'glove' 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[3], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove\u001b[39m.\u001b[39mvectors\u001b[39m.\u001b[39mshape\n",
"\u001b[0;31mNameError\u001b[0m: name 'glove' is not defined"
]
}
],
"source": [
"glove.vectors.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below implies that row 0 is the vector associated with the word 'the', row 1 for ',' (comma), row 2 for '.' (period), etc."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['the',\n",
" ',',\n",
" '.',\n",
" 'of',\n",
" 'to',\n",
" 'and',\n",
" 'in',\n",
" 'a',\n",
" '\"',\n",
" \"'s\",\n",
" 'for',\n",
" '-',\n",
" 'that',\n",
" 'on',\n",
" 'is']"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.itos[:15]"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'glove' 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[4], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove\u001b[39m.\u001b[39mstoi[\u001b[39m'\u001b[39m\u001b[39mthe\u001b[39m\u001b[39m'\u001b[39m]\n",
"\u001b[0;31mNameError\u001b[0m: name 'glove' is not defined"
]
}
],
"source": [
"glove.stoi['the']"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"36623"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.stoi['dazzle']"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"43165"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.stoi['shenanigans']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### we'll create a function that takes in word embeddings and a word and returns the associated vector. It'll also throw an error if the word doesn't exist in the vocabulary."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"def get_vector(embeddings, word):\n",
" \n",
" assert word in embeddings.stoi, f'*{word}* is not in the vocab!'\n",
" \n",
" return embeddings.vectors[embeddings.stoi[word]]"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([-0.8503, 0.3336, -0.6589, -0.4987, 0.3659, -0.1925, 0.2566, -0.0534,\n",
" 0.3147, 0.2443, 0.2934, -0.4492, 0.1517, 0.3931, -0.3179, 0.0605,\n",
" 0.8177, -0.3885, 0.7676, -1.1041, -0.1544, 0.3165, -0.3724, -0.1148,\n",
" 0.5163, -0.3929, 0.1630, -0.2532, -0.5098, 0.1520, 0.2781, 0.5252,\n",
" -0.3882, -0.3472, -0.6182, 0.1702, 0.1225, -0.2419, -0.3888, -0.5318,\n",
" -0.4699, -0.7050, -0.6213, -0.3869, -0.8564, -0.4100, -0.4749, -0.2108,\n",
" -0.8134, -0.5240, 0.4989, 0.3791, 0.5543, 1.1230, -0.4212, -1.5674,\n",
" -0.5689, 0.4082, 1.7949, 0.1686, -0.0029, 0.2879, -0.9009, -0.0942,\n",
" 0.7999, -0.3910, 0.7629, 0.7131, 0.1319, -0.4076, -0.1869, 0.8956,\n",
" 0.4687, -0.0029, 0.0253, 1.0084, 0.1714, 0.5974, -1.1003, 0.4931,\n",
" 0.4178, 0.1728, -0.4947, 0.0878, -0.9669, -1.0920, 0.3390, -0.5129,\n",
" 0.2464, 0.2714, 0.2421, -0.2171, 0.5504, 0.0082, -0.4557, 0.1353,\n",
" -0.0431, -0.4141, 0.7005, 0.1877])"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_vector(glove, 'paper')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to find the words similar to a certain input word, we first find the vector of this input word, then we scan through our vocabulary finding any vectors similar to this input word vector.\n",
"\n",
"The function below returns the closest 6 words to an input word vector:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"def closest(embeddings, vector, n = 6):\n",
" \n",
" distances = []\n",
" \n",
" for neighbor in embeddings.itos:\n",
" distances.append((neighbor, torch.dist(vector, get_vector(embeddings, neighbor))))\n",
" \n",
" return sorted(distances, key = lambda x: x[1])[:n]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('paper', tensor(0.)),\n",
" ('papers', tensor(3.8442)),\n",
" ('printed', tensor(4.1970)),\n",
" ('print', tensor(4.2666)),\n",
" ('sheet', tensor(4.3835)),\n",
" ('printing', tensor(4.4179))]"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"closest(glove, get_vector(glove, 'paper'))"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('shenanigans', tensor(0.)),\n",
" ('chicanery', tensor(2.3785)),\n",
" ('hijinks', tensor(2.6764)),\n",
" ('escapades', tensor(2.7821)),\n",
" ('machinations', tensor(2.8699)),\n",
" ('gamesmanship', tensor(2.9044))]"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"closest(glove, get_vector(glove, 'shenanigans'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we'll also create another function that will nicely print out the tuples returned by our closest function."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"def print_tuples(tuples):\n",
" \n",
" for t in tuples:\n",
" print('(%.4f) %s' % (t[1], t[0]))"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.0000) stupendous\n",
"(2.5795) marvellous\n",
"(2.7539) frightful\n",
"(2.8506) stupefying\n",
"(2.8561) awe-inspiring\n",
"(2.9179) mind-blowing\n"
]
}
],
"source": [
"print_tuples(closest(glove, get_vector(glove, 'stupendous')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Analogies\n",
"\n",
"with a well-trained word vector space certain semantic relationships can be captured with regular vector arithmetic."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"def analogy(embeddings, w1, w2, w3, n = 6):\n",
" \n",
" print('\\n[%s : %s :: %s : ?]' % (w1, w2, w3))\n",
" \n",
" closest_words = closest(embeddings, \\\n",
" get_vector(embeddings, w2)\n",
" - get_vector(embeddings, w1) \\\n",
" + get_vector(embeddings, w3), \\\n",
" n + 3)\n",
" \n",
" closest_words = [x for x in closest_words if x[0] not in [w1, w2, w3]][:n]\n",
" \n",
" return closest_words"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[moon : night :: sun : ?]\n",
"(5.7069) morning\n",
"(5.7276) afternoon\n",
"(5.8023) evening\n",
"(6.1410) hours\n",
"(6.2797) saturday\n",
"(6.3056) sunday\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'moon', 'night', 'sun'))"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[fly : bird :: swim : ?]\n",
"(5.9754) swimming\n",
"(6.2409) shark\n",
"(6.4822) dolphin\n",
"(6.5421) whale\n",
"(6.6276) cat\n",
"(6.6457) gorilla\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'fly', 'bird', 'swim'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Interesting failure mode"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[earth : moon :: sun : ?]\n",
"(6.2294) lee\n",
"(6.4125) kang\n",
"(6.4644) tan\n",
"(6.4757) yang\n",
"(6.4853) lin\n",
"(6.5220) chong\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'earth', 'moon', 'sun')) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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
}

View file

@ -447,7 +447,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 3, "execution_count": 4,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
@ -457,7 +457,7 @@
"traceback": [ "traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[3], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mtorch\u001b[39;00m\n\u001b[1;32m 2\u001b[0m \u001b[39m# import numpy as np\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[39m# Xtrain_ = torch.from_numpy(X_train.values).float()\u001b[39;00m\n\u001b[1;32m 4\u001b[0m \u001b[39m# Xtest_ = torch.from_numpy(x_test.values).float()\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[39m# Ytest_ = torch.from_numpy(y_test.values).view(1,-1)[0]\u001b[39;00m\n\u001b[1;32m 8\u001b[0m \u001b[39m# Ytrain_.shape\u001b[39;00m\n", "Cell \u001b[0;32mIn[4], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mtorch\u001b[39;00m\n\u001b[1;32m 2\u001b[0m \u001b[39m# import numpy as np\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[39m# Xtrain_ = torch.from_numpy(X_train.values).float()\u001b[39;00m\n\u001b[1;32m 4\u001b[0m \u001b[39m# Xtest_ = torch.from_numpy(x_test.values).float()\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[39m# Ytest_ = torch.from_numpy(y_test.values).view(1,-1)[0]\u001b[39;00m\n\u001b[1;32m 8\u001b[0m \u001b[39m# Ytrain_.shape\u001b[39;00m\n",
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'torch'" "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'torch'"
] ]
} }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
import torch
print(torch.__version__)