For just one time synchronization, it is easy:

$ sudo aptitude install ntpdate $ sudo ntpdate us.pool.ntp.org

The server to use can be specified from the list given here.

Taro Sato's Memorandum

For just one time synchronization, it is easy:

$ sudo aptitude install ntpdate $ sudo ntpdate us.pool.ntp.org

The server to use can be specified from the list given here.

On Debian, it is of course easy to install:

$ sudo aptitude install mongodb

My main use of local database servers is for testing, however, and I don’t want MongoDB to take up more than a few GB under */var/lib* for journal files. I can instruct it to use smaller files by adding the following line to */etc/mongodb.conf*:

smallfiles=true

Then stop the MongoDB service, remove the existing journal files, and restart:

$ sudo /etc/init.d/mongodb stop $ sudo rm /var/lib/mongodb/journal/* $ sudo /etc/init.d/mongodb start

Posted in Uncategorized
Leave a comment

Installing NumPy, SciPy, and Matplotlib has gotten so much easier with PIP, but there are some dependencies that are not taken care of automatically.

NumPy:

$ sudo pip install numpy

SciPy:

$ sudo aptitude install libblas-dev liblapack-dev gfortran $ sudo pip install scipy

Matplotlib:

$ sudo aptitude install libfreetype6-dev $ su # pip install matplotlib

I had some issue with `sudo`

when the installer could not find X. Running the command as root worked.

Posted in Uncategorized
Leave a comment

$ sudo aptitude install postgresql postgresql-contrib $ sudo su - postgres postgres$ createuser -s yourusername

where *yourusername* is the username of your account. Note that with the `-s`

switch the user will be created as a superuser. For assigning a more restricted role, see the official documentation.

Go back to your normal shell, and do

$ createdb $ psql

Now you should be on the PostgreSQL shell.

Posted in Uncategorized
Leave a comment

Suppose we ran an A/B test with two different versions of a web page, and , for which we count the number of visitors and whether they convert or not. We can summarize this in a contingency table showing the frequency distribution of the events:

not converted () | converted () | |
---|---|---|

4514 | 486 | |

4473 | 527 |

It is trivial to compute the conversion rate of each version, for a and for a. With such a relatively small difference, however, can we convincingly say that the version b converts better? To test the *statistical significance* of a result like this, a hypothesis testing can be used.

An appropriate hypothesis test here is Pearson’s chi-squared test. There are two types of the chi-squared test, goodness of fit and test of independence, but it is the latter which is useful for the case in question. The reason as to why a test of “independence” is applicable becomes clear by converting the contingency table into a probability matrix by dividing each element by the grand total of frequencies:

not converted () | converted () | |
---|---|---|

A table like this is sometimes called correspondence matrix. Here, the table consists of joint probabilities where is the version of the web page ( or ) and is the conversion result ( or ).

Now, our interest is whether the conversion depends on the page version , and if it does, to learn which version converts better. In probability theory, the events and are said to be independent if the joint probability can be computed by , where and are marginal probabilities of and , respectively. It is straightforward to compute the marginal probabilities from row and column marginals:

where is the grand total of all the elements. The null hypothesis (i.e., a neutral hypothesis in which the effect we seek is absent) is that and are independent, in which case the elements of the matrix are equivalent to

not converted () | converted () | |
---|---|---|

The conversion is said to be dependent on the version of the web site if this null hypothesis is rejected. Hence rejecting the null hypothesis means that one version is better at converting than the other. This is the reason why the test is on independence.

The chi-squared test compares an observed distribution to an expected distribution

(1)

where and are the row and column indices of the matrix (*). The values of are computed from and . The statistic thus obtained is now compared to the distribution assumed in the null hypothesis, and to do this we need to find the degree of freedom (dof) which is the shape parameter of chi-squared distribution. For the test of independence using a contingency matrix, the dof is computed from the total number of matrix entries () minus the reduction in dof, which is given by . The reductions come from the row and column sum constraints, but decreased by one because the last entry in the matrix is determined by either the row or column sum on that row/column and therefore degenerate. Hence the dof for the test of independence comes out to be .

Fortunately it is very straightforward to carry out this hypothesis testing using `scipy.stats.chi2_contingency`

. All we need is to supply the function with a contingency matrix and it will return the statistic and the corresponding p-value:

The result for the original table (of ) is and . Since the p-value is greater than the standard threshold , we cannot reject the null hypothesis that the page version and the conversion is independent. Therefore the difference in the conversion rates cited in the beginning of this article is not statistically significant.

What if we keep running the same A/B test a bit longer, until we accumulate visitors? Using example data (`n40000.csv`

), we have the conversion rates of for version a and for version b. Running the same test on the new data yields and . Since , the difference we see in the conversion rates is statistically significant this time. This is a demonstration of how a bigger sample helps to see a tiny difference. (The example data used in this article are generated assuming the true conversion rates of for a and for b.)

(*) For a 2 x 2 contingency table, Yate’s chi-squared test is commonly used. This applies a correction of the form

to account for an error between the observed discrete distribution and the continuous chi-squared distribution.

I was reading an article about visualization techniques using multidimensional scaling (MDS), the correspondence analysis in particular. The example used R, but as usual I want to find ways to do it on Python, so here goes.

The correspondence analysis is useful when you have a two-way contingency table for which relative values of ratio-scaled data are of interest. For example, I here use a table where the rows are fashion brands (Chanel, Louis Vuitton, etc.) and the columns are the number of people who answered that the particular brand has the particular attribute expressed by the adjective (luxurious, youthful, energetic, etc.). (I borrowed the data from this article.)

The correspondence analysis (or MDS in general) is a method of reducing dimensions to make the data more sensible for interpretation. In this case, I get a scatter plot of brands and adjectives in two-dimensional space, in which brands/adjectives more closely associated with each other are placed near each other.

As you see, brands like GAP, H&M, and Uniqlo are associated with youth, friendliness, and energy, while old-school brands like Chanel and Tiffany are associated with luxury and brilliance. This way of visualization is useful because the high-dimensional information (11 brands and 9 attributes) are reduced into two-dimensional plane, and the distance on that plane is meaningful.

Here’s the code and data:

I have been using SyntaxHighlighter Evolved for displaying code snippets on this site. While the WordPress plugin has been working very well, I seem to lose my custom CSS styles every time the updated plugin gets installed. I want to keep a custom CSS that suits the style of my site and keep using it whenever the plugin gets updated.

This is a procedure to create a custom theme and use it with SyntaxHighlighter Evolved (version 3.1.x).

First, download the source from the Github repository. I will also create a branch and work on that branch.

$ git clone https://github.com/Viper007Bond/syntaxhighlighter.git $ cd syntaxhighligher $ git branch MyTheme $ git checkout MyTheme

Next, create a custom CSS file by copying the default style sheet.

$ cp syntaxhighlighter3/styles/shCoreDefault.css syntaxhighlighter3/styles/shCoreMyTheme.css $ cp syntaxhighlighter3/styles/shThemeDefault.css syntaxhighlighter3/styles/shThemeMyTheme.css

I can make whatever edits to the newly created CSS style sheets. If all I want to change is color, editing *shThemeMyTheme.css* would be enough. To change the style more in detail, I may need to edit *shCoreMyTheme.css*. For example, if the font size needs adjustment, look for lines specifying “font-size” property.

Then I register the new theme so that the plugin recognizes it. In *syntaxhighlighter.php*, look for the parts of code that look as follows, and append a line relevant for the new theme:

// Create list of themes and their human readable names // Plugins can add to this list: http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/adding-a-new-theme/ $this->themes = (array) apply_filters( 'syntaxhighlighter_themes', array( 'default' => __( 'Default', 'syntaxhighlighter' ), 'django' => __( 'Django', 'syntaxhighlighter' ), 'eclipse' => __( 'Eclipse', 'syntaxhighlighter' ), 'emacs' => __( 'Emacs', 'syntaxhighlighter' ), 'fadetogrey' => __( 'Fade to Grey', 'syntaxhighlighter' ), 'midnight' => __( 'Midnight', 'syntaxhighlighter' ), 'rdark' => __( 'RDark', 'syntaxhighlighter' ), 'none' => __( '[None]', 'syntaxhighlighter' ), 'mytheme' => __( 'MyTheme', 'syntaxhighlighter' ), ) );

// Register theme stylesheets wp_register_style( 'syntaxhighlighter-core', plugins_url( $this->shfolder . '/styles/shCore.css', __FILE__ ), array(), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-default', plugins_url( $this->shfolder . '/styles/shThemeDefault.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-django', plugins_url( $this->shfolder . '/styles/shThemeDjango.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-eclipse', plugins_url( $this->shfolder . '/styles/shThemeEclipse.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-emacs', plugins_url( $this->shfolder . '/styles/shThemeEmacs.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-fadetogrey', plugins_url( $this->shfolder . '/styles/shThemeFadeToGrey.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-midnight', plugins_url( $this->shfolder . '/styles/shThemeMidnight.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-rdark', plugins_url( $this->shfolder . '/styles/shThemeRDark.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver ); wp_register_style( 'syntaxhighlighter-theme-mytheme', plugins_url( $this->shfolder . '/styles/shThemeMyTheme.css', __FILE__ ), array('syntaxhighlighter-core'), $this->agshver );

Note in each code snippet I added a line for MyTheme at the end.

Now I upload these files to the WordPress plugin directory of my web server host. Before I do that, however, I need to overwrite *shCore.css* with *shCoreMyTheme.css*; it looks like the core style sheet is not automatically used unless I manually copy like this:

$ cp syntaxhighlighter3/styles/shCoreMyTheme.css syntaxhighlighter3/styles/shCore.css

Finally, I upload all the files:

$ scp syntaxhighlighter3/styles/shCore.css $MYWEB/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles $ scp syntaxhighlighter3/styles/shCoreMyTheme.css $MYWEB/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles $ scp syntaxhighlighter3/styles/shThemeMyTheme.css $MYWEB/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles $ scp syntaxhighlighter.php $MYWEB/wp-content/plugins/syntaxhighlighter/

where `$MYWEB`

points to the public directory on my web server.

Once this is properly done, the new theme will appear under the “Color Theme” in the SyntaxHighter plugin setting page in my WordPress admin area.

There are several ways to run principal component analysis (PCA) using various packages (scikit-learn, statsmodels, etc.) or even just rolling out your own through singular-value decomposition and such. Visualizing the PCA result can be done through biplot. I was looking at an example of using `prcomp`

and `biplot`

in R, but it does not seem like there is a comparable plug-and-play way of generating a biplot on Python.

As it turns out, generating a biplot from the result of PCA by `pcasvd`

of StatsModels is fairly straightforward from the rotation matrix supplied by the function. Here is a code snippet:

In addition to PCA, k-means clustering (three clusters) was run on the data to color the observations by how they cluster. The resulting biplot for states.x77 (which I exported and borrowed from R) looks like this:

There are numerous pieces of duplicate information served by multiple sources on the web. Many news stories that we receive from the media tend to originate from the same source, such as the Associated Press. When such contents are scraped off the web for archiving, a need may arise to categorize documents by their similarity (not in the sense of meaning of the text but the character-level or lexical matching).

Here, we build a prototype for near-duplicate document detection system. This article presents the background material on an algorithm called MinHash and a method for probabilistic dimension reduction through the locality-sensitive hashing. A future article presents their implementation on Python and CouchDB.

(Note that all the numbers generated for the tables in this article are totally made up for illustration purposes; they may not be mathematically consistent with any hashing algorithm.)

A similarity is represented by the Jaccard index:

where and are sets representing the two documents in our context.

A useful way to construct a set representing a document is by *shingling*. To construct a set of -singles from a text, a sliding window of characters is applied over the text. For example, if the text is “abcdabd,” the resulting set of 2-shingles is {ab, bc, cd, da, bd} (note that “ab” appears only once and not repeated in the set).

The value of is arbitrary, but it should be large enough that the probability of any given shingle appearing in any random document is low. That is, if the available number of characters is and the character length of typical documents is , we should at least ensure . Since each character has a different frequency of appearance in a typical text, an suitable value of depends on the nature of the documents and should be tuned accordingly. A good rule of thumb for an order of magnitude estimate is to assume for English texts.

Instead of using individual characters, shingles can also be constructed from words. For example, in a math text book we may often see a sentence beginning with a terse expression “it is trivial to show,” whose 3-shingle set is {“it is trivial”, “is trivial to”, “trivial to show”}. This has advantage in that shingles built this way are more sensitive to the styles of writing. The style sensitivity may aid in identifying similarities between domain-specific texts buried in other types of documents.

Typically, shingles are *hashed* so that those who contain similar information are grouped into a single bucket while being represented as an integer. The latter is a huge advantage in that the data can be compressed more efficiently in terms of bytes. For example, a 4-shingle (of characters) typically uses 4 bytes, each byte used for character representation, and this is good for representing 160,000 4-shingles (i.e., ). With a 4-byte, however, about 4 million () integers and therefore shingles could be represented, which is good enough size for (i.e., ). If a small probability for collision into the same bucket can be tolerated, can be chosen even larger. From here on, we assume a random hash function does not produce any collision between any pair of randomly chosen shingles, i.e., the mapping yields a unique integer.

Suppose we have a random hash function and all possible singles from for a total of documents. We can summarize this in a *characteristic matrix*:

1 | 0 | 1 | ||

1 | 1 | 0 | ||

1 | 1 | 0 |

where the entry of indicates that the document contains a shingle for which a hash value exists. (The entry of means the shingle itself does not appear in that document.) It is trivial to compute Jaccard indices using any pair of documents from this matrix. In practice, however, the requirement for comparing all the hash values for a large number of documents makes the process prohibitive.

Let us focus on a pair of documents, and , for which the shingles , , , have been hashed by a function . The relevant entries from the characteristic matrix look as follows:

0 | 0 | |

1 | 0 | |

1 | 1 | |

0 | 1 | |

1 | 0 | |

0 | 0 | |

1 | 1 |

There are three types of rows: (a) both columns have 1, (b) one of the columns have 1, and (c) both columns have 0. We let , , and denote the numbers of rows categorized this way, respectively. For and , is the cardinality of their joint set and is that for their union. Hence the Jaccard index is .

Now, consider an experiment in which the rows in the matrix are randomly permutated. Remove the rows of type (c), since they do not contribute at all to the union of two sets. We look at the first row of the matrix thus constructed and note its type defined above, either (a) or (b). Repeat the process times. What is the chance that the first row found this way to be of type (a) above? The probability is given by , which is similar to the way Jaccard index is computed. This is the property that we use as a Jaccard index estimator.

In practice, randomly permuting a huge number of rows is very inefficient. Instead, we prepare a set of random hash functions (for for a set of measurements) that effectively permute the row order given the same set of shingles and sort rows in ascending order by hash values. (In order for this to be true, the hash functions need to be well-chosen and produce few collisions.) The row of the minimum hash value corresponds to picking the first row in the example above.

What we have shown is that, for estimating Jaccard indices, we only need to keep the minimum hash values generated from different hash functions. Therefore the very sparse characteristic matrix can be condensed into a *signature matrix* of minimum hash values with entries given by

where

is the set of shingles from the document .

98273 | 23 | 23 | 63483 | |||

2763 | 524 | 524 | 2345 | |||

325 | 567849 | 567849 | 987 | |||

876 | 7849 | 32 | 897347 |

For supposedly near-duplicate documents such as and in the table, most MinHash values are similar, and the fraction of values that are similar is an estimate of the Jaccard index. This is the gist of the *MinHash algorithm*. In other words, the probability that a pair of MinHash values from two documents and match is equivalent to their Jaccard index:

(1)

While the information necessary to compute document similarity have been compressed quite nicely into a signature matrix, examining all documents would take pairs, each involving comparisons from signature entries. The vast majority of documents may not be near-duplicate, however, and in such a case we do not need every pair to be compared. *Locality-sensitive hashing* (LSH) offers a method of reducing the number of dimensions in high-dimensional MinHash signatures.

The idea is to partition a MinHash signature matrix into bands, each with rows (such that is the total number of rows), and hashing MinHash integer sequences grouped by band. For example, if we have MinHash values, we could partition them into bands of rows:

Band | |||||||
---|---|---|---|---|---|---|---|

1 | 98273 | 23 | 23 | 63483 | |||

1 | 2763 | 524 | 524 | 2345 | |||

1 | 49368 | 7207 | 7207 | 59542 | |||

1 | 9559 | 34784 | 34784 | 6095 | |||

2 | 37153 | 14927 | 14927 | 581 | |||

2 | 8671 | 17492 | 17492 | 6664 | |||

2 | 2763 | 43306 | 43306 | 10916 | |||

2 | 2600 | 38712 | 38712 | 45472 | |||

3 | 14352 | 25862 | 25862 | 14812 | |||

3 | 263 | 52 | 52 | 11973 | |||

3 | 325 | 567849 | 567849 | 987 | |||

3 | 876 | 7849 | 32 | 897347 |

Then we use some good hash function which takes MinHash values and summarizes into another hash, for band 1, for band 2, and so on. This reduces the signature matrix into matrix:

390 | 57232 | 57232 | 33719 | |||

62509 | 453 | 453 | 51954 | |||

453 | 13009 | 23905 | 12174 |

Near-duplicate documents will be hashed into the same bucket within each band. In this example, and are in the same bucket for bands 1 and 2. (Note that in band 3 has the same hash value as and in band 2, but they are not considered to be in the same bucket since the bands are different.) The documents that share a bucket within a band is considered *candidates* for further examination. The advantage is that, since in general, the number of required comparisons is much smaller. The LSH thus provides a way to select out candidates for near-duplicate detection, before full signature comparisons are carried out.

The assumption is that a pair of documents, if near-duplicate, has a total of chances to be hashed into a common bucket in at least one of the available bands. Recall from Eq.~(1) that the probability that a pair of MinHash values from two documents match is equivalent to their Jaccard index. The probability that a pair of documents share a bucket in a band of rows is given by . Its complement, , is the probability that a document pair does not get hashed into the same bucket for a band. Then the probability that two documents become candidates in at least one band is given by . Plotting for varying and , the function forms a series of S-curves:

The figure provides an intuition as to how the value of and should be chosen for a target Jaccard similarity threshold (above which two documents are considered near-duplicate). Let . The value of for the steepest slope is obtained from the second derivative, , which is

for . As a rule of thumb, we want want , but the exact value of can be adjusted based on rejection criteria. Choosing reduces false positives, whereas reduces false negatives at the candidate selection step.

- Anand Rajaraman and Jeffrey David Ullman (2011).
*Mining of Massive Datasets*. Cambridge University Press. ISBN 978-1-107-01535-7

Say if I need to compute the sum of a series like this one:

(1)

where . This series looks like a geometric series in which case the sum can be computed from

The coefficients vary, so the relation cannot be directly used.

There is a trick transform a series like this into a geometric series. Multiplying Eq. (1) by , I have

(2)

Subtracting Eq. (2) from Eq. (1), we write

which is a geometric series with . Hence