Skip to content

Commit

Permalink
Merge pull request #1308 from charliejharrison/develop
Browse files Browse the repository at this point in the history
Corpus streaming tutorial changes
  • Loading branch information
menshikh-iv authored May 31, 2017
2 parents 55997f8 + df4bd06 commit cc74b66
Showing 1 changed file with 87 additions and 51 deletions.
138 changes: 87 additions & 51 deletions docs/notebooks/Corpora_and_Vector_Spaces.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,21 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from gensim import corpora"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"documents = [\"Human machine interface for lab abc computer applications\",\n",
Expand All @@ -87,8 +91,10 @@
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -133,17 +139,17 @@
"\n",
"The ways to process documents are so varied and application- and language-dependent that I decided to not constrain them by any interface. Instead, a document is represented by the features extracted from it, not by its “surface” string form: how you get to the features is up to you. Below I describe one common, general-purpose approach (called bag-of-words), but keep in mind that different application domains call for different features, and, as always, it’s [garbage in, garbage out](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out)...\n",
"\n",
"To convert documents to vectors, we’ll use a document representation called [bag-of-words](https://en.wikipedia.org/wiki/Bag-of-words_model). In this representation, each document is represented by one vector where each vector element represents a question-answer pair, in the style of:\n",
"\n",
"\"How many times does the word *system* appear in the document? Once\"\n",
"To convert documents to vectors, we’ll use a document representation called [bag-of-words](https://en.wikipedia.org/wiki/Bag-of-words_model). In this representation, each document is represented by one vector where a vector element `i` represents the number of times the `i`th word appears in the document.\n",
"\n",
"It is advantageous to represent the questions only by their (integer) ids. The mapping between the questions and ids is called a dictionary:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand All @@ -163,13 +169,15 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we assigned a unique integer id to all words appearing in the corpus with the [gensim.corpora.dictionary.Dictionary](https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary) class. This sweeps across the texts, collecting word counts and relevant statistics. In the end, we see there are twelve distinct words in the processed corpus, which means each document will be represented by twelve numbers (ie., by a 12-D vector). To see the mapping between words and their ids:"
"Here we assigned a unique integer ID to all words appearing in the processed corpus with the [gensim.corpora.dictionary.Dictionary](https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary) class. This sweeps across the texts, collecting word counts and relevant statistics. In the end, we see there are twelve distinct words in the processed corpus, which means each document will be represented by twelve numbers (ie., by a 12-D vector). To see the mapping between words and their ids:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand All @@ -192,8 +200,10 @@
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -222,8 +232,10 @@
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -252,16 +264,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"By now it should be clear that the vector feature with `id=10 stands` for the question “How many times does the word graph appear in the document?” and that the answer is “zero” for the first six documents and “one” for the remaining three. As a matter of fact, we have arrived at exactly the same corpus of vectors as in the [Quick Example](https://radimrehurek.com/gensim/tutorial.html#first-example). If you're running this notebook by your own, the words id may differ, but you should be able to check the consistency between documents comparing their vectors. \n",
"By now it should be clear that the vector feature with `id=10` represents the number of times the word \"graph\" occurs in the document. The answer is “zero” for the first six documents and “one” for the remaining three. As a matter of fact, we have arrived at exactly the same corpus of vectors as in the [Quick Example](https://radimrehurek.com/gensim/tutorial.html#first-example). If you're running this notebook yourself the word IDs may differ, but you should be able to check the consistency between documents comparing their vectors. \n",
"\n",
"## Corpus Streaming – One Document at a Time\n",
"\n",
"Note that *corpus* above resides fully in memory, as a plain Python list. In this simple example, it doesn’t matter much, but just to make things clear, let’s assume there are millions of documents in the corpus. Storing all of them in RAM won’t do. Instead, let’s assume the documents are stored in a file on disk, one document per line. Gensim only requires that a corpus must be able to return one document vector at a time:"
"Note that *corpus* above resides fully in memory, as a plain Python list. In this simple example, it doesn’t matter much, but just to make things clear, let’s assume there are millions of documents in the corpus. Storing all of them in RAM won’t do. Instead, let’s assume the documents are stored in a file on disk, one document per line. Gensim only requires that a corpus be able to return one document vector at a time:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 6,
"metadata": {
"collapsed": true
},
Expand All @@ -278,19 +290,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The assumption that each document occupies one line in a single file is not important; you can mold the `__iter__` function to fit your input format, whatever it is. Walking directories, parsing XML, accessing network... Just parse your input to retrieve a clean list of tokens in each document, then convert the tokens via a dictionary to their ids and yield the resulting sparse vector inside `__iter__`."
"The assumption that each document occupies one line in a single file is not important; you can design the `__iter__` function to fit your input format, whatever that may be - walking directories, parsing XML, accessing network nodes... Just parse your input to retrieve a clean list of tokens in each document, then convert the tokens via a dictionary to their IDs and yield the resulting sparse vector inside `__iter__`."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<__main__.MyCorpus object at 0x000002520A52E0B8>\n"
"<__main__.MyCorpus object at 0x10f48a240>\n"
]
}
],
Expand All @@ -303,13 +317,15 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Corpus is now an object. We didn’t define any way to print it, so `print` just outputs address of the object in memory. Not very useful. To see the constituent vectors, let’s iterate over the corpus and print each document vector (one at a time):"
"`corpus_memory_friendly` is now an object. We didn’t define any way to print it, so `print` just outputs address of the object in memory. Not very useful. To see the constituent vectors, let’s iterate over the corpus and print each document vector (one at a time):"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -343,8 +359,10 @@
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -377,19 +395,21 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"And that is all there is to it! At least as far as bag-of-words representation is concerned. Of course, what we do with such corpus is another question; it is not at all clear how counting the frequency of distinct words could be useful. As it turns out, it isn’t, and we will need to apply a transformation on this simple representation first, before we can use it to compute any meaningful document vs. document similarities. Transformations are covered in the [next tutorial](https://radimrehurek.com/gensim/tut2.html), but before that, let’s briefly turn our attention to *corpus persistency*.\n",
"And that is all there is to it! At least as far as bag-of-words representation is concerned. Of course, what we do with such a corpus is another question; it is not at all clear how counting the frequency of distinct words could be useful. As it turns out, it isn’t, and we will need to apply a transformation on this simple representation first, before we can use it to compute any meaningful document vs. document similarities. Transformations are covered in the [next tutorial](https://radimrehurek.com/gensim/tut2.html), but before that, let’s briefly turn our attention to *corpus persistency*.\n",
"\n",
"## Corpus Formats\n",
"\n",
"There exist several file formats for serializing a Vector Space corpus (~sequence of vectors) to disk. *Gensim* implements them via the *streaming corpus interface* mentioned earlier: documents are read from (resp. stored to) disk in a lazy fashion, one document at a time, without the whole corpus being read into main memory at once.\n",
"There exist several file formats for serializing a Vector Space corpus (~sequence of vectors) to disk. *Gensim* implements them via the *streaming corpus interface* mentioned earlier: documents are read from (or stored to) disk in a lazy fashion, one document at a time, without the whole corpus being read into main memory at once.\n",
"\n",
"One of the more notable file formats is the [Matrix Market format](http://math.nist.gov/MatrixMarket/formats.html). To save a corpus in the Matrix Market format:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create a toy corpus of 2 documents, as a plain Python list\n",
Expand All @@ -407,8 +427,10 @@
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"corpora.SvmLightCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.svmlight'), corpus)\n",
Expand All @@ -425,8 +447,10 @@
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"corpus = corpora.MmCorpus(os.path.join(TEMP_FOLDER, 'corpus.mm'))"
Expand All @@ -441,8 +465,10 @@
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand All @@ -465,8 +491,10 @@
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand All @@ -490,8 +518,10 @@
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
Expand Down Expand Up @@ -519,8 +549,10 @@
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"corpora.BleiCorpus.serialize(os.path.join(TEMP_FOLDER, 'corpus.lda-c'), corpus)"
Expand All @@ -539,8 +571,10 @@
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import gensim\n",
Expand All @@ -559,8 +593,10 @@
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import scipy.sparse\n",
Expand All @@ -573,7 +609,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"For a complete reference (Want to prune the dictionary to a smaller size? Optimize converting between corpora and NumPy/SciPy arrays?), see the [API documentation](https://radimrehurek.com/gensim/apiref.html). Or continue to the next tutorial on Topics and Transformations ([notebook](https://github.com/piskvorky/gensim/tree/develop/docs/notebooks/Topics_and_Transformations.ipynb) \n",
"For a complete reference (want to prune the dictionary to a smaller size? Optimize converting between corpora and NumPy/SciPy arrays?), see the [API documentation](https://radimrehurek.com/gensim/apiref.html). Or continue to the next tutorial on Topics and Transformations ([notebook](https://github.com/piskvorky/gensim/tree/develop/docs/notebooks/Topics_and_Transformations.ipynb) \n",
"or [website](https://radimrehurek.com/gensim/tut2.html))."
]
}
Expand Down

0 comments on commit cc74b66

Please sign in to comment.