<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Tianlong's Blog</title><link href="https://stlong0521.github.io/" rel="alternate"></link><link href="https://stlong0521.github.io/feeds/all.atom.xml" rel="self"></link><id>https://stlong0521.github.io/</id><updated>2017-10-15T00:00:00-07:00</updated><entry><title>Language Detection from Speech: Chinese or English?</title><link href="https://stlong0521.github.io/20171015%20-%20Language%20Detection.html" rel="alternate"></link><updated>2017-10-15T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2017-10-15:20171015 - Language Detection.html</id><summary type="html">&lt;p&gt;In language processing, it is an essential step to detect which language it is before speech recognition and machine translation. This blog post presents an approach to distinguish Chinese and English from speech (an audio sample) using a neural network model. &lt;a href="https://spark.apache.org/"&gt;Spark&lt;/a&gt; is used to perform data preprocessing, and &lt;a href="https://www.tensorflow.org/"&gt;TensorFlow&lt;/a&gt; is used for neural network model training and evaluation.&lt;/p&gt;
&lt;h3&gt;Raw Data Collection&lt;/h3&gt;
&lt;p&gt;YouTube videos (with audio extracted) are downloaded and converted to wav format. The data are collected from two representative interview shows in each language (Chinese and English), and they are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;635 minutes of Chinese interviews from &lt;a href="https://www.youtube.com/watch?v=6GOTZa3xU2U&amp;amp;list=PL0qv-SqUbwqVVIabi_90Me4UeuKWs1Sbn"&gt;Luyu Official&lt;/a&gt; (i.e., 《鲁豫有约》)&lt;/li&gt;
&lt;li&gt;534 minutes of English interviews from &lt;a href="https://www.youtube.com/watch?v=s0MbQWhyoD0&amp;amp;list=PLuW4g7xujBWeiOJ-C-pZCTdUMWucxeMNQ"&gt;Ellen Show&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Data Preprocessing&lt;/h3&gt;
&lt;p&gt;The data preprocessing converts a wav audio file into a spectrogram image by the following steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Split audio into pieces of one second for each;&lt;/li&gt;
&lt;li&gt;Re-sample (down-sample) to make sure each audio piece has the same sampling rate (16k);&lt;/li&gt;
&lt;li&gt;Apply &lt;a href="http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/"&gt;Mel Frequency Cepstral Coefficient (MFCC) filter&lt;/a&gt; to obtain the spectrogram of the audio;&lt;/li&gt;
&lt;li&gt;Convert the spectrogram into a gray-scale image;&lt;/li&gt;
&lt;li&gt;Improve the contrast of images by applying &lt;a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_histograms/py_histogram_equalization/py_histogram_equalization.html"&gt;histogram equalization&lt;/a&gt; and &lt;a href="https://helpx.adobe.com/photoshop/using/levels-adjustment.html"&gt;levels filter&lt;/a&gt;;&lt;/li&gt;
&lt;li&gt;Cut or pad to make sure each image has the same size.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To enable parallelization, Spark is used to execute the steps described above. Most steps are easy to understand, while Step 3 needs a little bit more explanation here. The MFCC filter essentially mimics the functionality of human cochleae, by framing, calculating power spectrum and summing over different mel-spaced filter banks for each audio sample. See &lt;a href="http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/"&gt;here&lt;/a&gt; for more details, especially how mel-spaced filter banks are generated.&lt;/p&gt;
&lt;p&gt;At last, all spectrogram images are labelled, mixed, shuffled and then split into train/test tests by 80%/20%. After that, we have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Train set: 30497 spectrogram images for Chinese, and 25663 spectrogram images for English&lt;/li&gt;
&lt;li&gt;Test set: 7625 spectrogram images for Chinese, and 6416 spectrogram images for English&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Model Training and Evaluation&lt;/h3&gt;
&lt;p&gt;A Berlinnet neural network model is adopted from &lt;a href="https://github.com/twerkmeister/iLID/blob/master/tensorflow/network/instances/berlinnet.py"&gt;here&lt;/a&gt; to perform the classification. The model contains 12 layers (in the order they appear in the network):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;One input layer&lt;/li&gt;
&lt;li&gt;One convolutional layer&lt;/li&gt;
&lt;li&gt;One &lt;a href="https://www.tensorflow.org/api_docs/python/tf/nn/local_response_normalization"&gt;local response normalization layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;One pooling layer&lt;/li&gt;
&lt;li&gt;One convolutional layer&lt;/li&gt;
&lt;li&gt;One local response normalization layer&lt;/li&gt;
&lt;li&gt;One pooling layer&lt;/li&gt;
&lt;li&gt;One convolutional layer&lt;/li&gt;
&lt;li&gt;One local response normalization layer&lt;/li&gt;
&lt;li&gt;One pooling layer&lt;/li&gt;
&lt;li&gt;One fully connected layer&lt;/li&gt;
&lt;li&gt;One fully connected layer&lt;/li&gt;
&lt;li&gt;One output layer&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The model is trained and evaluated using the TensorFlow framework. The configuration of the training as well as the model itself can be found &lt;a href="https://github.com/stlong0521/language-detector/blob/master/language_detector/modeling/config.yaml"&gt;here&lt;/a&gt;, and the results are discussed in the next section.&lt;/p&gt;
&lt;h3&gt;Results &amp;amp; Discussion&lt;/h3&gt;
&lt;p&gt;Due to limited resources on a regular PC (that is what I have), there was only 19300 iterations performed during the training step, which took around 24 hours. However, the evaluation on the test set delivered an accuracy of as high as 92.7%. It should be noted that the classification is merely based on a very short audio sample (lasting for one second only).&lt;/p&gt;
&lt;p&gt;There are at least three potential ways to make the accuracy even higher:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Collect more data to train the model;&lt;/li&gt;
&lt;li&gt;Apply more iterations during training, if more resources are available;&lt;/li&gt;
&lt;li&gt;Most likely, an utterance lasts for more than one second, which gives us a chance to apply majority voting across the classification results drawn independently from multiple one-second audio pieces. A weighted voting is even better and meanwhile definitely doable, as each classification returns not only a label but also the confidence.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The last approach turns out to be a very effective way to boost the classification accuracy, which barely consumes any additional resource but can reduce the classification error dramatically.&lt;/p&gt;
&lt;h3&gt;Code Repository&lt;/h3&gt;
&lt;p&gt;Check out the &lt;a href="https://github.com/stlong0521/language-detector"&gt;codes&lt;/a&gt;, if you are interested in the implementation.&lt;/p&gt;
&lt;h3&gt;Acknowledgment&lt;/h3&gt;
&lt;p&gt;This project is inspired by and a large portion of codes comes from the great work &lt;a href="https://github.com/twerkmeister/iLID"&gt;here&lt;/a&gt;.&lt;/p&gt;</summary><category term="Machine Learning"></category><category term="Natural Language Processing"></category></entry><entry><title>An Approach Of Scaling Airflow To A Corporate Level</title><link href="https://stlong0521.github.io/20170715%20-%20Airflow%20in%20Corporate.html" rel="alternate"></link><updated>2017-07-15T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2017-07-15:20170715 - Airflow in Corporate.html</id><summary type="html">&lt;p&gt;&lt;a href="https://stlong0521.github.io/20161023%20-%20Airflow.html"&gt;The last post on Airflow&lt;/a&gt; provides step-by-step instructions on how to build an Airflow cluster from scratch. It could serve the development purpose well, but lacks critical features to work in prod, e.g., CI/CD compliance, resource monitoring, service recovery, and so on.&lt;/p&gt;
&lt;p&gt;I have been leading the efforts to build the Airflow backbone at Zillow's Data Science and Engineering (DSE) team, and I would like to introduce &lt;a href="https://www.zillow.com/data-science/airflow-at-zillow/"&gt;a post&lt;/a&gt; from Zillow's tech blog site. It describes how Airflow is adopted and working at Zillow, and can possibly give you an idea on how Airflow can be configured to run in a corporate level.&lt;/p&gt;</summary><category term="Big Data"></category></entry><entry><title>A Guide On How To Build An Airflow Server/Cluster</title><link href="https://stlong0521.github.io/20161023%20-%20Airflow.html" rel="alternate"></link><updated>2016-10-23T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-10-23:20161023 - Airflow.html</id><summary type="html">&lt;p&gt;&lt;a href="https://github.com/apache/incubator-airflow"&gt;Airflow&lt;/a&gt; is an open-source platform to author, schedule and monitor workflows and data pipelines. When you have periodical jobs, which most likely involve various data transfer and/or show dependencies on each other, you should consider Airflow. This blog post briefly introduces Airflow, and provides the instructions to build an Airflow server/cluster from scratch.&lt;/p&gt;
&lt;h3&gt;A Glimpse at Airflow under the Hood&lt;/h3&gt;
&lt;p&gt;Generally, Airflow works in a distributed environment, as you can see in the diagram below. The airflow scheduler schedules jobs according to the dependencies defined in directed acyclic graphs (DAGs), and the airflow workers pick up and run jobs with their loads properly balanced. All job information is stored in the meta DB, which is updated in a timely manner. The users can monitor their jobs via a shiny Airflow web UI and/or the logs.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20161023/Airflow.png" alt="Airflow"&gt;
&lt;figcaption align="center"&gt;Fig. 1: Airflow Diagram.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Although you do not necessarily need to run a fully distributed version of Airflow, this page will go through all three modes: standalone, pseudo-distributed and distributed modes.&lt;/p&gt;
&lt;h3&gt;Phase 1: Start with Standalone Mode Using Sequential Executor&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Under the standalone mode with a sequential executor, the executor picks up and runs jobs sequentially, which means there is no parallelism for this choice. Although not often used in production, it enables you to get familiar with Airflow quickly.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Install and configure airflow&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Set the airflow home
export AIRFLOW_HOME=~/airflow

# Install from pypi using pip
pip install airflow

# Install necessary sub-packages
pip install airflow[crypto] # For connection credentials protection
pip install airflow[postgres] # For PostgreSQL DBs
pip install airflow[celery] # For distributed mode: celery executor
pip install airflow[rabbitmq] # For message queuing and passing between airflow server and workers
... # Anything more you need

# Configure airflow: modify AIRFLOW_HOME/airflow.cfg if necessary
# For the standalone mode, we will leave the configuration to default
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Initialize the meta database (home for almost all airflow information)&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# For the standalone mode, it could be a sqlite database, which applies to sequential executor only
airflow initdb
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Start the airflow webserver and explore the web UI&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;airflow webserver -p 8080 # Test it out by opening a web browser and go to localhost:8080
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create your dags and place them into your DAGS_FOLDER (AIRFLOW_HOME/dags by default); refer to this &lt;a href="https://pythonhosted.org/airflow/tutorial.html"&gt;tutorial&lt;/a&gt; for how to create a dag, and keep the key commands below in mind&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Check syntax errors for your dag
python ~/airflow/dags/tutorial.py

# Print the list of active DAGs
airflow list_dags

# Print the list of tasks the &amp;quot;tutorial&amp;quot; dag_id
airflow list_tasks tutorial

# Print the hierarchy of tasks in the tutorial DAG
airflow list_tasks tutorial --tree

# Test your tasks in your dag
airflow test [DAG_ID] [TASK_ID] [EXECUTION_DATE]
airflow test tutorial sleep 2015-06-01

# Backfill: execute jobs that are not done in the past
airflow backfill tutorial -s 2015-06-01 -e 2015-06-07
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Start the airflow scheduler and monitor the tasks via the web UI&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;airflow scheduler # Monitor the your tasks via the web UI (success/failure/scheduling, etc.)

# Remember to turn on the dags you want to run via the web UI, if they are not on yet
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;[Optional] Put your dags in remote storage, and sync them with your local dag folder&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Create a daemon using crons to sync up dags; below is an example for remote dags in S3 (you can also put them in remote repo)
# Note: you need to have the aws command line tool installed and your AWS credentials properly configured
crontab -e
* * * * * /usr/local/bin/aws s3 sync s3://your_bucket/your_prefix YOUR_AIRFLOW_HOME/dags # Sync up every minute
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;[Optional] Add access control to the web UI; add users with password protection, see &lt;a href="https://pythonhosted.org/airflow/security.html"&gt;here&lt;/a&gt;. You may need to install the dependency below&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;pip install flask-bcrypt
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Phase 2: Adopt Pseudo-distributed Mode Using Local Executor&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Under the pseudo-distributed mode with a local executor, the local workers pick up and run jobs locally via multiprocessing. If you have only a moderate amount of scheduled jobs, this could be the right choice.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Adopt another DB server to support executors other than the sequential executor; MySQL and PostgreSQL are recommended; here PostgreSQL is used as an example&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Install postgres
brew install postgresql # For Mac, the command varies for different OS

# Connect to the database
psql -d postgres # This will open a prompt

# Operate on the database server
\l # List all databases
\du # List all users/roles
\dt # Show all tables in database
\h # List help information
\q # Quit the prompt

# Create a meta db for airflow
CREATE DATABASE database_name;
\l # Check for success
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Modify the configuration in AIRFLOW_HOME/airflow.cfg&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Change the executor to Local Executor
executor = LocalExecutor

# Change the meta db configuration
# Note: the postgres username and password do not matter for now, since the database server and clients are still on the same host
sql_alchemy_conn = postgresql+psycopg2://your_postgres_user_name:your_postgres_password@host_name/database_name
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Restart airflow to test your dags&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;airflow initdb
airflow webserver
airflow scheduler
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Establish your own connections via the web UI; you can test your DB connections via the Ad Hoc Query (see &lt;a href="https://pythonhosted.org/airflow/profiling.html"&gt;here&lt;/a&gt;)&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span class="c"&gt;# Go to the web UI: Admin -&amp;gt; Connection -&amp;gt; Create&lt;/span&gt;
&lt;span class="n"&gt;Connection&lt;/span&gt; &lt;span class="n"&gt;ID&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;
&lt;span class="n"&gt;Connection&lt;/span&gt; &lt;span class="n"&gt;Type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;database&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;AWS&lt;/span&gt;
&lt;span class="n"&gt;Host&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;your&lt;/span&gt; &lt;span class="n"&gt;database&lt;/span&gt; &lt;span class="n"&gt;server&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;address&lt;/span&gt;
&lt;span class="n"&gt;Scheme&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;your&lt;/span&gt; &lt;span class="n"&gt;database&lt;/span&gt;
&lt;span class="n"&gt;Username&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;your&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;
&lt;span class="n"&gt;Password&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;will&lt;/span&gt; &lt;span class="n"&gt;be&lt;/span&gt; &lt;span class="n"&gt;encrypted&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;airflow&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;crypto&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="n"&gt;installed&lt;/span&gt;
&lt;span class="n"&gt;Extra&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;additional&lt;/span&gt; &lt;span class="n"&gt;configuration&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;AWS&lt;/span&gt; &lt;span class="n"&gt;credentials&lt;/span&gt;

&lt;span class="c"&gt;# Encrypt your credentials&lt;/span&gt;
&lt;span class="c"&gt;# Generate a valid Fernet key and place it into airflow.cfg&lt;/span&gt;
&lt;span class="n"&gt;FERNET_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="err"&gt;$&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;python&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="s"&gt;&amp;quot;from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print FERNET_KEY&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Phase 3: Extend to Distributed Mode Using Celery Executor&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Under the distributed mode with a celery executor, remote workers pick up and run jobs as scheduled and load-balanced. As being highly scalable, it is the choice when you expect heavy and expanding loads.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Install and configure the message queuing/passing engine on the airflow server: RabbitMQ/Reddis/etc; RabbitMQ (resources: &lt;a href="http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html"&gt;link1&lt;/a&gt; and &lt;a href="http://blog.genesino.com/2016/05/airflow/"&gt;link2&lt;/a&gt;)&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; Install RabbitMQ&lt;/span&gt;
&lt;span class="x"&gt;brew install rabbitmq &lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; For Mac, the command varies for different OS&lt;/span&gt;

&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; Add the following path to your .bash_profile or .profile&lt;/span&gt;
&lt;span class="x"&gt;PATH=&lt;/span&gt;&lt;span class="p"&gt;$&lt;/span&gt;&lt;span class="nv"&gt;PATH&lt;/span&gt;&lt;span class="x"&gt;:/usr/local/sbin&lt;/span&gt;

&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; Start the RabbitMQ server&lt;/span&gt;
&lt;span class="x"&gt;sudo rabbitmq-server &lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; run in foreground; or&lt;/span&gt;
&lt;span class="x"&gt;sudo rabbitmq-server -detached &lt;/span&gt;&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; run in background&lt;/span&gt;

&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; Configure RabbitMQ: create user and grant privileges&lt;/span&gt;
&lt;span class="x"&gt;rabbitmqctl add_user rabbitmq_user_name rabbitmq_password&lt;/span&gt;
&lt;span class="x"&gt;rabbitmqctl add_vhost rabbitmq_virtual_host_name&lt;/span&gt;
&lt;span class="x"&gt;rabbitmqctl set_user_tags rabbitmq_user_name rabbitmq_tag_name&lt;/span&gt;
&lt;span class="x"&gt;rabbitmqctl set_permissions -p rabbitmq_virtual_host_name rabbitmq_user_name &amp;quot;.*&amp;quot; &amp;quot;.*&amp;quot; &amp;quot;.*&amp;quot;&lt;/span&gt;

&lt;span class="err"&gt;#&lt;/span&gt;&lt;span class="x"&gt; Make the RabbitMQ server open to remote connections&lt;/span&gt;
&lt;span class="x"&gt;Go to /usr/local/etc/rabbitmq/rabbitmq-env.conf, and change NODE_IP_ADDRESS from 127.0.0.1 to 0.0.0.0 (development only, restrict access for prod)&lt;/span&gt;
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Modify the configuration in AIRFLOW_HOME/airflow.cfg&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Change the executor to Celery Executor
executor = CeleryExecutor

# Set up the RabbitMQ broker url and celery result backend
broker_url = amqp://rabbitmq_user_name:rabbitmq_password@host_name/rabbitmq_virtual_host_name # host_name=localhost on server
celery_result_backend = meta db url (as configured in step 2 of Phase 2), or RabbitMQ broker url (same as above), or any other eligible result backend
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Open the meta DB (PostgreSQL) to remote connections&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Modify /usr/local/var/postgres/pg_hba.conf to add Client Authentication Record
host    all         all         0.0.0.0/0          md5 # 0.0.0.0/0 stands for all ips; use CIDR address to restrict access; md5 for pwd authentication

# Change the Listen Address in /usr/local/var/postgres/postgresql.conf
listen_addresses = &amp;#39;*&amp;#39;

# Create a user and grant privileges (run the commands below under superuser of postgres)
CREATE USER your_postgres_user_name WITH ENCRYPTED PASSWORD &amp;#39;your_postgres_pwd&amp;#39;;
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_postgres_user_name;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO your_postgres_user_name;

# Restart the PostgreSQL server and test it out
brew services restart postgresql
psql -U [postgres_user_name] -h [postgres_host_name] -d [postgres_database_name]

# IMPORTANT: update your sql_alchemy_conn string in airflow.cfg
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Configure your airflow workers; follow most steps for the airflow server, except that they do not have PostgreSQL and RabbitMQ servers&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Test it out&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;# Start your airflow workers, on each worker, run:
airflow worker # The prompt will show the worker is ready to pick up tasks if everything goes well

# Start you airflow server
airflow webserver
airflow scheduler
airflow worker # [Optional] Let your airflow server be a worker as well
&lt;/pre&gt;&lt;/div&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Your airflow workers should be now picking up and running jobs from the airflow server!&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;</summary><category term="Big Data"></category></entry><entry><title>Monte Carlo Tree Search and Its Application in AlphaGo</title><link href="https://stlong0521.github.io/20160409%20-%20MCTS.html" rel="alternate"></link><updated>2016-04-09T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-04-09:20160409 - MCTS.html</id><summary type="html">&lt;p&gt;As one of the most important methods in artificial intelligence (AI), especially for playing games, Monte Carlo tree search (MCTS) has received considerable interest due to its spectacular success in the difficult problem of computer Go. In fact, most successful computer Go algorithms are powered by MCTS, including the recent success of Google's AlphaGo&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;. This post introduces MCTS and explains how it is used in AlphaGo.&lt;/p&gt;
&lt;h3&gt;Warm Up: Bandit-Based Methods&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Bandit problems&lt;/em&gt; are a well-known class of sequential decision problems, in which one needs to choose among &lt;span class="math"&gt;\(K\)&lt;/span&gt; actions (e.g. the &lt;span class="math"&gt;\(K\)&lt;/span&gt; arms of a multi-armed bandit slot machine) in order to maximize the cumulative reward by consistently taking the optimal action. The choice of action is difficult as the underlying reward distributions are unknown, and potential rewards must be estimated based on past observations. This leads to the &lt;em&gt;exploitation-exploration dilemma&lt;/em&gt;: one needs to balance the exploitation of the action currently believed to be optimal with the exploration of other actions that currently appear suboptimal but may turn out to be superior in the long run.&lt;/p&gt;
&lt;p&gt;The primary goal is to find a policy that can minimize the player's regret after &lt;span class="math"&gt;\(n\)&lt;/span&gt; plays, which is the difference between: (i) the best possible total reward if the player could at the beginning have the knowledge of the reward distributions that is actually learned afterwards; and (ii) the actual total reward from the &lt;span class="math"&gt;\(n\)&lt;/span&gt; finished plays. In other words, the regret is the expected loss due to not playing the best bandit. An upper confidence bound (UCB) policy has been proposed, which has an expected logarithmic growth of regret uniformly over the total number of plays &lt;span class="math"&gt;\(n\)&lt;/span&gt; without any prior knowledge regarding the reward distributions. According to the UCB policy, to minimize his regret, for the current play, the player should choose arm &lt;span class="math"&gt;\(j\)&lt;/span&gt; that maximizes:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\overline{X}_j+\sqrt{\frac{2\ln{n}}{n_j}},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\overline{X}_j\)&lt;/span&gt; is the average reward from arm &lt;span class="math"&gt;\(j\)&lt;/span&gt;, &lt;span class="math"&gt;\(n_j\)&lt;/span&gt; is the number of times arm &lt;span class="math"&gt;\(j\)&lt;/span&gt; was played and &lt;span class="math"&gt;\(n\)&lt;/span&gt; is the total number of plays so far. The physical meaning is that: the term &lt;span class="math"&gt;\(\overline{X}_j\)&lt;/span&gt; encourages the exploitation of higher-rewarded choices, while the term &lt;span class="math"&gt;\(\sqrt{\frac{2\ln{n}}{n_j}}\)&lt;/span&gt; encourages the exploration of less-visited choices.&lt;/p&gt;
&lt;h3&gt;Monte Carlo Tree Search (MCTS)&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;Let us use the board game as an example. Given a board state, the primary goal would be finding out the best action that should be taken currently, which should naturally be chosen according to some precomputed value of each action. The purpose of MCTS is to approximate the (true) values of actions that may be taken from the current board state. This is achieved by iteratively building a partial search tree.&lt;/p&gt;
&lt;h4&gt;Four Fundamental Steps in Each Iteration&lt;/h4&gt;
&lt;p&gt;The basic algorithm involves iteratively building a search tree until some predefined computational budget (e.g., time, memory or iteration constraint) is reached, at which point the search is halted and the best-performing root action returned. Each node in the search tree represents a state, and directed links to child nodes represent actions leading to subsequent states.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160409/MCTS.png" alt="MCTS"&gt;
&lt;figcaption align="center"&gt;Fig. 1: Four steps in one iteration of MCTS.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;As illustrate in Fig. 1, four steps are applied for each iteration&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Selection: Starting from the root node (i.e., current state), a tree policy for child selection is recursively applied to descend through the tree until an expandable node is reached. A node is expandable if it represents a non-terminal state and has unvisited (i.e., expandable) children.&lt;/li&gt;
&lt;li&gt;Expansion: For the expandable node we reached in the selection step, one child node is added to expand the tree, according to the available actions.&lt;/li&gt;
&lt;li&gt;Simulation: A simulation is run from the newly expanded node according to the default policy to produce an outcome (e.g., win or lose when reaching a terminal state).&lt;/li&gt;
&lt;li&gt;Backpropagation: The simulated result is backpropagated through the selected nodes in the selection step to update their statistics.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There are two essential ideas that should be highlighted here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The tree policy for child selection should be able to give the high-value nodes priorities in value approximation, and meanwhile explore the less-visited nodes. This is quite similar to the bandit problem, so we can apply the UCB policy to choose the child node.&lt;/li&gt;
&lt;li&gt;The value of each node is approximated in an incremental way. That is, its initial value is obtained from a random simulation by the default policy (e.g., a win/lose result along a random path), and then refined by the backpropagation steps during the following iterations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;The Full Algorithm Description&lt;/h4&gt;
&lt;p&gt;Before describing the algorithm, let us define some notations first.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span class="math"&gt;\(s(v)\)&lt;/span&gt;: the associated state to node &lt;span class="math"&gt;\(v\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(a(v)\)&lt;/span&gt;: the incoming action that leads to node &lt;span class="math"&gt;\(v\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(N(v)\)&lt;/span&gt;: the visit count of node &lt;span class="math"&gt;\(v\)&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(Q(v)\)&lt;/span&gt;: the vector of total simulation rewards of node &lt;span class="math"&gt;\(v\)&lt;/span&gt; for all players&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The main procedure of the MCTS algorithm is described below, which essentially executes the four fundamental steps for each iteration until the computational budget is reached. It returns the best action that should be taken for the current state.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/Main.png" alt="Main"&gt;&lt;/p&gt;
&lt;p&gt;The selection step is described below, which returns the expandable node according to the tree policy.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/TreePolicy.png" alt="TreePolicy"&gt;&lt;/p&gt;
&lt;p&gt;The child selection is described below, which returns the best child of a given node. It essentially applies the UCB method, which uses a constant &lt;span class="math"&gt;\(c\)&lt;/span&gt; to balance the exploitation with the exploration. It should be noted that there might be multiple players, but the best child is selected as per the interest of the player who is supposed to play in this state.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/BestChild.png" alt="BestChild"&gt;&lt;/p&gt;
&lt;p&gt;The selected node after the selection step is expanded by choosing one of its unvisited children, and then adding the associated data to the new node. The procedure is described below.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/Expand.png" alt="Expand"&gt;&lt;/p&gt;
&lt;p&gt;Given the state associating to the newly expanded node, a random simulation is run as indicated below, which finds a random path to a terminal state and returns the simulated reward.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/DefaultPolicy.png" alt="DefaultPolicy"&gt;&lt;/p&gt;
&lt;p&gt;Once the simulated reward of the newly expanded node is obtained, it is backpropagated through the selected nodes in the selection step. The visit counts are updated at the same time.&lt;/p&gt;
&lt;p&gt;&lt;img src="/figures/20160409/Backup.png" alt="Backup"&gt;&lt;/p&gt;
&lt;p&gt;Recall the board game example, assume that the rewards of winning and losing a game are 1 and 0, respectively. After applying the MCTS algorithm, for each node &lt;span class="math"&gt;\(v\)&lt;/span&gt; in the tree, &lt;span class="math"&gt;\(Q(v)\)&lt;/span&gt; would be the number of wins that is accumulated from &lt;span class="math"&gt;\(N(v)\)&lt;/span&gt; visits of this node, and thus &lt;span class="math"&gt;\(\frac{Q(v)}{N(v)}\)&lt;/span&gt; would be the winning rate. This is exactly the information we could rely on to choose the best action to take in the current state.&lt;/p&gt;
&lt;h3&gt;How is MCTS used by Google's AlphaGo?&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;We now understand how MCTS works. Can MCTS be directly applied to computer Go? Yes, but there could be a better way to do that. The reason is that Go is a very high-branching game. Consider the number of all possible sequences of moves, &lt;span class="math"&gt;\(b^d\)&lt;/span&gt;, where &lt;span class="math"&gt;\(b\)&lt;/span&gt; is the game's breadth (number of legal moves per state, &lt;span class="math"&gt;\(b \approx 250\)&lt;/span&gt; for Go), and &lt;span class="math"&gt;\(d\)&lt;/span&gt; is game's depth (game length, &lt;span class="math"&gt;\(d \approx 150\)&lt;/span&gt; for Go). As a result, exhaustive search is computationally impossible. Applying MCTS to Go in a straightforward way helps, but the benefits of MCTS are not really fully exploited, since the limited number of simulations could only scratch the surface of the giant search space.&lt;/p&gt;
&lt;p&gt;Aided by the useful information learned by two deep convolutional neural networks (a.k.a., &lt;a href="https://stlong0521.github.io/20160403%20-%20NN%20and%20DL.html"&gt;deep learning&lt;/a&gt;), policy network and value network, Google's AlphaGo applies MCTS in an innovative way. &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;First, for the tree policy to select child, instead of using the UCB method, AlphaGo takes into account the prior probability of actions learned by the policy network. More specifically, for node &lt;span class="math"&gt;\(v_0\)&lt;/span&gt;, the child &lt;span class="math"&gt;\(v\)&lt;/span&gt; is selected by maximizing
&lt;div class="math"&gt;\begin{equation}
\frac{Q(v)}{N(v)}+\frac{P(v|v_0)}{1+N(v)},
\end{equation}&lt;/div&gt;
where &lt;span class="math"&gt;\(P(v|v_0)\)&lt;/span&gt; is the prior probability that is provided by the policy network. This greatly improves the child selection policy, and thus grants more professional moves (e.g., by human experts) priorities in MCTS simulation.&lt;/li&gt;
&lt;li&gt;Second, for the default policy to evaluate expanded nodes, AlphaGo combines the outcomes from simulation steps and node values learned by the value network, and their weights are balanced by a constant &lt;span class="math"&gt;\(\lambda\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that both the policy network and value network are trained offline, which greatly reduces the time cost in a real-time contest.&lt;/p&gt;
&lt;h3&gt;Acknowledgement&lt;/h3&gt;
&lt;p&gt;A large majority of this post, including Fig. 1 and the pseudo codes, comes from the survey paper&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;. More details about MCTS and its variants can be found there.&lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;D. Silver, et al., &lt;em&gt;&lt;a href="http://www.nature.com/nature/journal/v529/n7587/full/nature16961.html"&gt;Mastering the game of Go with deep neural networks and tree search&lt;/a&gt;&lt;/em&gt;, Nature, 2016.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id="fn:2"&gt;
&lt;p&gt;C. Browne, et al., &lt;em&gt;&lt;a href="http://www.cameronius.com/cv/mcts-survey-master.pdf"&gt;A Survey of Monte Carlo Tree Search Methods&lt;/a&gt;&lt;/em&gt;, IEEE Transactions on Computational Intelligence and AI in Gamges, 2012.&amp;#160;&lt;a class="footnote-backref" href="#fnref:2" rev="footnote" title="Jump back to footnote 2 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Machine Learning"></category></entry><entry><title>Neural Networks and Deep Learning</title><link href="https://stlong0521.github.io/20160403%20-%20NN%20and%20DL.html" rel="alternate"></link><updated>2016-04-03T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-04-03:20160403 - NN and DL.html</id><summary type="html">&lt;p&gt;It has been a long time since the idea of neural networks was proposed, but it is really during the last few years that neural networks have become widely used. One of the major enablers is the infrastructure with high computational capability (e.g., cloud computing), which makes the training of large and deep (multilayer) neural networks possible. This post is in no way an exhaustive review of neural networks or deep learning, but rather an entry-level introduction excerpted from a very popular book&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;h3&gt;Neural Network (NN) Basics&lt;/h3&gt;
&lt;p&gt;Let us start with sigmoid neurons, and then find out how they are used in NNs.&lt;/p&gt;
&lt;h4&gt;Sigmoid Neurons&lt;/h4&gt;
&lt;p&gt;As the smallest unit in NNs, a sigmoid neuron mimics the behaviour of a real neuron in human neural systems. It takes multiple inputs and generates one single output, as in a process of local or partial decision making. More specifically, given a series of inputs &lt;span class="math"&gt;\([x_1,x_2,...]\)&lt;/span&gt;, a neuron applies the sigmoid function to the weighted sum of the inputs plus a bias, i.e., the output of the neuron is computed as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\sigma(z)=\sigma(\sum_j{w_jx_j}+b)=\frac{1}{1+\exp(-\sum_j{w_jx_j}-b)},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(z=\sum_j{w_jx_j}+b\)&lt;/span&gt; is the weighted input to the neuron, and the sigmoid function, &lt;span class="math"&gt;\(\sigma(z)=\frac{1}{1+\exp(-z)}\)&lt;/span&gt;, is to approximate the step function as usually used in binary decision making. A natural question is: why do not we just use the step function? The answer is that the step function is not smooth (not differentiable at origin), which disables the gradient method in model learning. With the smoothed version of the step function, we are safe to relate the change at the output to the weight/bias changes by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\Delta{output}=\sum_j{\frac{\partial{output}}{\partial{w_j}}\Delta{w_j}}+\frac{\partial{output}}{\partial{b}}\Delta{b}.
\end{equation}&lt;/div&gt;
&lt;h4&gt;The Architecture of NNs&lt;/h4&gt;
&lt;p&gt;The architecture of a typical NN is depicted in Fig. 1. As shown, the leftmost layer in this network is called the input layer, and the neurons within this layer are called input neurons. The rightmost or output layer contains the output neuron(s). The middle layer is called a hidden layer, since the neurons in this layer are neither inputs nor outputs.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160403/NN.png" alt="Neural Network Architecture"&gt;
&lt;figcaption align="center"&gt;Fig. 1: The neural network architecture.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;It was proved that NNs with a single hidden layer can be used to approximate any continuous function to any desired precision. Click &lt;a href="http://neuralnetworksanddeeplearning.com/chap4.html"&gt;here&lt;/a&gt; to see how. It can be expected that a NN with more neurons/layers could be more accurate in the approximation.&lt;/p&gt;
&lt;h4&gt;Learning with Gradient Descent&lt;/h4&gt;
&lt;p&gt;Before training a model, we first need to find a way to quantify how well we are achieving. That is, we need to introduce a cost function. Although there are many cost functions available, we will start with the quadratic cost function, which is defined as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
C(w,b)=\frac{1}{2n}\sum_x{||y(x)-a||^2},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(w\)&lt;/span&gt; denotes the collection of all weights in the network, &lt;span class="math"&gt;\(b\)&lt;/span&gt; all the biases, &lt;span class="math"&gt;\(n\)&lt;/span&gt; is the total number of training inputs, &lt;span class="math"&gt;\(a\)&lt;/span&gt; is the vector of outputs from the network when &lt;span class="math"&gt;\(x\)&lt;/span&gt; is input, and the sum is over all training inputs, &lt;span class="math"&gt;\(x\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Applying the gradient descent method, we can learn the weights and biases by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
w_k'=w_k-\eta\frac{\partial{C}}{\partial{w_k}},
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation}
b_l'=b_l-\eta\frac{\partial{C}}{\partial{b_l}}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
To compute each gradient, we need to take into account all the training input &lt;span class="math"&gt;\(x\)&lt;/span&gt; in each iteration. However, this slows the learning down if the training data size is large. An idea called &lt;em&gt;stochastic gradient descent (a.k.a., mini-batch learning)&lt;/em&gt; can be used to speed up learning. The idea is to estimate the gradient by computing it for a small sample of randomly chosen training inputs.&lt;/p&gt;
&lt;h3&gt;The Backpropagation Algorithm: How to Compute Gradients of the Cost Function?&lt;/h3&gt;
&lt;p&gt;So far we have known that the model parameters can be learned by the gradient descent method, but the computation of the gradients can be challenging by itself. Note that the network size and the data size can both be very large. In this section, we will see how the backpropagation algorithm helps compute the gradients efficiently.&lt;/p&gt;
&lt;h4&gt;Matrix Notation for NNs&lt;/h4&gt;
&lt;p&gt;For ease of presentation, let us define some notations first.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;span class="math"&gt;\(w_{jk}^l\)&lt;/span&gt;: weight from the &lt;span class="math"&gt;\(k\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l-1\)&lt;/span&gt; to the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(w^l=\{w_{jk}^l\}\)&lt;/span&gt;: matrix including all weights from each neuron in layer &lt;span class="math"&gt;\(l-1\)&lt;/span&gt; to each neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(b_j^l\)&lt;/span&gt;: bias for the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(b^l=\{b_j^l\}\)&lt;/span&gt;: column vector including all biases for each neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(a_j^l=\sigma(\sum_k{w_{jk}^la_k^{l-1}+b_j^l})\)&lt;/span&gt;: activation of the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(a^l=\{a_j^l\}=\sigma(w^la^{l-1}+b^l)\)&lt;/span&gt;: column vector including all activations of each neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(z_j^l=\sum_k{w_{jk}^la_k^{l-1}+b_j^l}\)&lt;/span&gt;: weighted input to the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(z^l=\{z_j^l\}=w^la^{l-1}+b^l\)&lt;/span&gt;: column vector including all weighted inputs to each neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(\delta_j^l=\frac{\partial{C}}{\partial{z_j^l}}\)&lt;/span&gt;: gradient of the cost function w.r.t. the weighted input to the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;, &lt;span class="math"&gt;\(z_j^l\)&lt;/span&gt;;&lt;/p&gt;
&lt;p&gt;&lt;span class="math"&gt;\(\delta^l=\{\delta_j^l\}\)&lt;/span&gt;: column vector including all gradients of the cost function w.r.t. the weighted input to each neuron in layer &lt;span class="math"&gt;\(l\)&lt;/span&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Four Fundamental Equations behind Backpropagation&lt;/h4&gt;
&lt;p&gt;There are four fundamental equations behind backpropagation, which will be explained one by one as below.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;First&lt;/em&gt;, the gradient of the cost function w.r.t. the weighted input to each neuron in output layer &lt;span class="math"&gt;\(L\)&lt;/span&gt; can be computed as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\delta^L=\nabla_{a^L}C \odot \sigma'(z^L),
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\nabla_{a^L}C=\{\frac{\partial{C}}{\partial{a_j^L}}\}\)&lt;/span&gt; is defined to be a column vector whose components are the partial derivatives &lt;span class="math"&gt;\(\frac{\partial{C}}{\partial{a_j^L}}\)&lt;/span&gt;, &lt;span class="math"&gt;\(\sigma'(z)\)&lt;/span&gt; is the first-order derivative of the sigmoid function &lt;span class="math"&gt;\(\sigma(z)\)&lt;/span&gt;, and &lt;span class="math"&gt;\(\odot\)&lt;/span&gt; represents an element-wise product.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Second&lt;/em&gt;, the gradient of the cost function w.r.t. the weighted input to each neuron in layer &lt;span class="math"&gt;\(l(l&amp;lt;L)\)&lt;/span&gt; can be computed from the results of layer &lt;span class="math"&gt;\(l+1\)&lt;/span&gt; (backpropagation), i.e.,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\delta^l=((w^{l+1})^T\delta^{l+1}) \odot \sigma'(z^l).
\end{equation}&lt;/div&gt;
&lt;p&gt;&lt;em&gt;Third&lt;/em&gt;, the gradient of the cost function w.r.t. each bias can be computed as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\frac{\partial{C}}{\partial{b_j^l}}=\delta_j^l.
\end{equation}&lt;/div&gt;
&lt;p&gt;&lt;em&gt;Fourth&lt;/em&gt;, the gradient of the cost function w.r.t. each weight can be computed as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\frac{\partial{C}}{\partial{w_{jk}^l}}=\delta_j^la_k^{l-1}.
\end{equation}&lt;/div&gt;
&lt;p&gt;The four equations above are not straightforward at first sight, but they are all consequences of the chain rule from multivariable calculus. The proof can be found &lt;a href="http://neuralnetworksanddeeplearning.com/chap2.html#proof_of_the_four_fundamental_equations_(optional)"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;The Backpropagation Algorithm&lt;/h4&gt;
&lt;p&gt;The backpropagation algorithm essentially includes a feedforward process and a backpropagation process. More specifically, in each iteration:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Input a mini-batch of &lt;span class="math"&gt;\(m\)&lt;/span&gt; training examples;&lt;/li&gt;
&lt;li&gt;For each training example &lt;span class="math"&gt;\(x\)&lt;/span&gt;:&lt;ul&gt;
&lt;li&gt;Initialization: set the activations of the input layer by &lt;span class="math"&gt;\(a^{x,1}=x\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Feedforward: for each &lt;span class="math"&gt;\(l=2,3,...,L\)&lt;/span&gt;, compute &lt;span class="math"&gt;\(z^{x,l}=w^la^{x,l-1}+b^l\)&lt;/span&gt; and &lt;span class="math"&gt;\(a^{x,l}=\sigma(z^{x,l})\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Output error: compute the error vector &lt;span class="math"&gt;\(\delta^{x,L}=\nabla_{a^L}C_x \odot \sigma'(z^{x,L})\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Backpropagate the error: for &lt;span class="math"&gt;\(l=L-1,L-2,...,2\)&lt;/span&gt;, compute &lt;span class="math"&gt;\(\delta^{x,l}=((w^{l+1})^T\delta^{x,l+1}) \odot \sigma'(z^{x,l})\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Compute gradients and apply the gradient descent method by
&lt;div class="math"&gt;\begin{equation}
\frac{\partial{C_x}}{\partial{w_{jk}^l}}=\delta_j^{x,l}a_k^{x,l-1},~~\frac{\partial{C_x}}{\partial{b_j^l}}=\delta_j^{x,l},~~w^l=w^l-\frac{\eta}{m}\sum_x{\delta^{x,l}(a^{x,l-1})^T},~~b^l=b^l-\frac{\eta}{m}\sum_x{\delta^{x,l}}.
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Deep Learning&lt;/h3&gt;
&lt;p&gt;Everything seems going well so far! What if our NNs are deep, i.e., with a lot of hidden layers? Typically we expect a deep NN could deliver better performance than shallow ones. Unfortunately it was observed that: for deep NNs, the learning speeds of the first few layers of neurons can be much higher/lower than those of the last few layers, in which case the NNs cannot be well trained. Click &lt;a href="http://neuralnetworksanddeeplearning.com/chap5.html#the_vanishing_gradient_problem"&gt;here&lt;/a&gt; to see why. This is known as &lt;em&gt;vanishing/exploding gradient problem&lt;/em&gt;. To resolve this problem, it is suggested that we should resort to convolutional networks.&lt;/p&gt;
&lt;h4&gt;Convolutional Networks&lt;/h4&gt;
&lt;p&gt;Convolutional neural networks use three basic ideas: local receptive fields, shared weights, and pooling. A typical convolutional network is depicted in Fig. 2, where the network includes one input layer, one convolutional layer, one pooling layer and one output layer (fully connected). We will try to understand the three ideas using this network as an example.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160403/ConvN.png" alt="Convolutional Networks"&gt;
&lt;figcaption align="center"&gt;Fig. 2: The convolutional networks.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;&lt;em&gt;Local receptive fields&lt;/em&gt;: Given a 28x28 image as the input layer, instead of directly connecting to all 28x28 pixels, the convolutional layer only connects to small, localized regions (local receptive fields) of the input image in the hope of detecting some localized features. In this example, the small region size is 5x5, so exploring all those regions with a stride length of one results into 24x24 neurons. Here we have three feature maps, so the convolutional layer eventually has 3x24x24 neurons.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Shared weights and biases&lt;/em&gt;: We use the same weights and bias for each neuron in a 24x24 feature map. It makes sense to use the same parameters in detecting the same feature but only in different local regions, and it can greatly reduce the number of parameters involved in a convolutional network compared to a fully connected layer.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The pooling layer&lt;/em&gt;: A pooling layer is usually used immediately after a convolutional layer. What the pooling layer do is simplify the information in the output from the convolutional layer. In this example, each unit in the pooling layer summarizes a region of 2x2 in the previous convolutional layer, which results into 3x12x12 neurons. The pooling can be a max-pooling (finding the maximum activation of the region to be summarized) or L2 pooling (obtaining the square root of the sum of the squares of the activations in the region to be summarized).&lt;/p&gt;
&lt;p&gt;To summarize, a convolutional network tries to detect localized features and at the same time greatly reduces the number of parameters. In principle, we could include any number of convolutional/pooling layers and also fully connected layers in our networks. What is exciting is that the backpropagation algorithm can apply to convolutional networks with only necessary minor modifications.&lt;/p&gt;
&lt;p&gt;Does convolutional networks avoid the vanishing/exploding gradient problem? Not really, but it helps us to proceed anyway, e.g., by reducing the number of parameters. The problem can be considerably alleviated by convolutional/pooling layers as well as other techniques, such as powerful regularization, advanced artificial neurons and more training epochs by GPU.&lt;/p&gt;
&lt;h4&gt;Deep Learning in Practice&lt;/h4&gt;
&lt;p&gt;It may be not that hard to construct a very basic (deep) NN and achieve a nice performance. However, there are still many techniques that could help to improve the NN's performance. A couple of insightful ideas are listed below, which should be kept in mind if we are working towards a better NN.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use more convolutional/pooling layers: reduce the number of parameters and make learning faster;&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://neuralnetworksanddeeplearning.com/chap3.html#the_cross-entropy_cost_function"&gt;right cost functions&lt;/a&gt;: resolve the problem of learning slow down by the cross-entropy cost function;&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://neuralnetworksanddeeplearning.com/chap3.html#overfitting_and_regularization"&gt;regularization&lt;/a&gt;: combat overfitting by L2/L1/drop-out regularization;&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://neuralnetworksanddeeplearning.com/chap3.html#other_models_of_artificial_neuron"&gt;advanced neurons&lt;/a&gt;: for example, tanh neurons and rectified linear units;&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://neuralnetworksanddeeplearning.com/chap3.html#weight_initialization"&gt;good weight initialization&lt;/a&gt;: avoid neuron saturation and learn faster;&lt;/li&gt;
&lt;li&gt;Use an expanded training data set: for example, rotate/shift images as new training data in image classification;&lt;/li&gt;
&lt;li&gt;Use an ensemble of NNs: heavy computation, but multiple models beat one;&lt;/li&gt;
&lt;li&gt;Use GPU: gain more training epochs;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Acknowledgement&lt;/h3&gt;
&lt;p&gt;A large majority of this post comes from Michael Nielsen's book&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt; entitled "Neural Networks and Deep Learning", which I strongly recommend to anyone interested in discovering how essentially neural networks work.&lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;M. Nielsen, &lt;em&gt;&lt;a href="http://neuralnetworksanddeeplearning.com/"&gt;Neural Networks and Deep Learning&lt;/a&gt;&lt;/em&gt;, Determination Press, 2015.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Machine Learning"></category><category term="Data Mining"></category></entry><entry><title>Latent Dirichlet Allocation and Topic Modeling</title><link href="https://stlong0521.github.io/20160326%20-%20LDA.html" rel="alternate"></link><updated>2016-03-26T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-03-26:20160326 - LDA.html</id><summary type="html">&lt;p&gt;When reading an article, we humans are able to easily identify the topics the article talks about. An interesting question is: can we automate this process, i.e., train a machine to find out the underlying topics in articles? In this post, a very popular topic modeling method, Latent Dirichlet allocation (LDA), will be discussed.&lt;/p&gt;
&lt;h3&gt;Latent Dirichlet Allocation (LDA) Topic Model&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;Given a library of &lt;span class="math"&gt;\(M\)&lt;/span&gt; documents, &lt;span class="math"&gt;\(\mathcal{L}=\{d_1,d_2,...,d_M\}\)&lt;/span&gt;, where each document &lt;span class="math"&gt;\(d_m\)&lt;/span&gt; contains a sequence of words, &lt;span class="math"&gt;\(d_m=\{w_{m,1},w_{m,2},...,w_{m,N_m}\}\)&lt;/span&gt;, we need to think of a model which describes how essentially these documents are generated. Considering &lt;span class="math"&gt;\(K\)&lt;/span&gt; topics and a vocabulary &lt;span class="math"&gt;\(V\)&lt;/span&gt;, the LDA topic model assumes that the documents are generated by the following two steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For each document &lt;span class="math"&gt;\(d_m\)&lt;/span&gt;, use a doc-to-topic model parameterized by &lt;span class="math"&gt;\(\boldsymbol\vartheta_m\)&lt;/span&gt; to generate the topic for the &lt;span class="math"&gt;\(n\)&lt;/span&gt;th word and denote it as &lt;span class="math"&gt;\(z_{m,n}\)&lt;/span&gt;, for all &lt;span class="math"&gt;\(1 \leq n \leq N_m\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;For each generated topic &lt;span class="math"&gt;\(k=z_{m,n}\)&lt;/span&gt; corresponding to each word in each document, use a topic-to-word model parameterized by &lt;span class="math"&gt;\(\boldsymbol\varphi_k\)&lt;/span&gt; to generate the word &lt;span class="math"&gt;\(w_{m,n}\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160326/LDA.png" alt="LDA Model"&gt;
&lt;figcaption align="center"&gt;Fig. 1: LDA topic model.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;The two steps are graphically illustrated in Fig. 1. Considering that the doc-to-topic model and the topic-to-word model essentially follow multinomial distributions (counts of each topic in a document or each word in a topic), a good prior for their parameters, &lt;span class="math"&gt;\(\boldsymbol\vartheta_m\)&lt;/span&gt; and &lt;span class="math"&gt;\(\boldsymbol\varphi_k\)&lt;/span&gt;, would be the conjugate prior of multinomial distribution, &lt;a href="https://en.wikipedia.org/wiki/Dirichlet_distribution"&gt;Dirichlet distribution&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A conjugate prior, &lt;span class="math"&gt;\(p(\boldsymbol\varphi)\)&lt;/span&gt;, of a likelihood, &lt;span class="math"&gt;\(p(\textbf{x}|\boldsymbol\varphi)\)&lt;/span&gt;, is a distribution that results in a posterior distribution, &lt;span class="math"&gt;\(p(\boldsymbol\varphi|\textbf{x})\)&lt;/span&gt; with the same functional form as the prior (but different parameters). For example, the conjugate prior of a multinomial distribution is Dirichlet distribution. That is, for a multinomial distribution parameterized by &lt;span class="math"&gt;\(\boldsymbol\varphi\)&lt;/span&gt;, if the prior for &lt;span class="math"&gt;\(\boldsymbol\varphi\)&lt;/span&gt; is a Dirichlet distribution characterized by &lt;span class="math"&gt;\(Dir(\boldsymbol\varphi|\boldsymbol\alpha)\)&lt;/span&gt;, after observing &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt;, the posterior for &lt;span class="math"&gt;\(\boldsymbol\varphi\)&lt;/span&gt; still follows a Dirichlet distribution &lt;span class="math"&gt;\(Dir(\boldsymbol\varphi|\textbf{n}_x+\boldsymbol\alpha)\)&lt;/span&gt;, but incorporating the counting result &lt;span class="math"&gt;\(\textbf{n}_x\)&lt;/span&gt; of observation &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Keep this in mind, let us take a closer look at the two steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;In the first step, for the &lt;span class="math"&gt;\(m\)&lt;/span&gt;th document, assume the prior for the doc-to-topic model's parameter &lt;span class="math"&gt;\(\boldsymbol\vartheta_m\)&lt;/span&gt; follows &lt;span class="math"&gt;\(Dir(\boldsymbol\vartheta_m|\boldsymbol\alpha)\)&lt;/span&gt;, after observing topics in the document and obtaining the counting result &lt;span class="math"&gt;\(\textbf{n}_m\)&lt;/span&gt;, we have the posterior for &lt;span class="math"&gt;\(\boldsymbol\vartheta_m\)&lt;/span&gt; as &lt;span class="math"&gt;\(Dir(\boldsymbol\vartheta_m|\textbf{n}_m+\boldsymbol\alpha)\)&lt;/span&gt;. After some calculation, we can obtain the topic distribution for the &lt;span class="math"&gt;\(m\)&lt;/span&gt;th document as
&lt;div class="math"&gt;\begin{equation}
p(\textbf{z}_m|\boldsymbol\alpha)=\frac{\Delta(\textbf{n}_m+\boldsymbol\alpha)}{\Delta(\boldsymbol\alpha)},
\end{equation}&lt;/div&gt;
where &lt;span class="math"&gt;\(\Delta(\boldsymbol\alpha)\)&lt;/span&gt; is the normalization factor for &lt;span class="math"&gt;\(Dir(\textbf{p}|\boldsymbol\alpha)\)&lt;/span&gt;, i.e., &lt;span class="math"&gt;\(\Delta(\boldsymbol\alpha)=\int{\prod_{k=1}^K{p_k^{\alpha_k-1}}}d\textbf{p}\)&lt;/span&gt;. Taking all documents into account,
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Doc2Topic}
p(\textbf{z}|\boldsymbol\alpha)=\prod_{m=1}^M{p(\textbf{z}_m|\boldsymbol\alpha)}=\prod_{m=1}^M{\frac{\Delta(\textbf{n}_m+\boldsymbol\alpha)}{\Delta(\boldsymbol\alpha)}}.
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;In the second step, similarly, for the &lt;span class="math"&gt;\(k\)&lt;/span&gt;th topic, assume the prior for the topic-to-word model's parameter &lt;span class="math"&gt;\(\boldsymbol\varphi_k\)&lt;/span&gt; follows &lt;span class="math"&gt;\(Dir(\boldsymbol\varphi_k|\boldsymbol\beta)\)&lt;/span&gt;, after observing words in the topic and obtaining the counting result &lt;span class="math"&gt;\(\textbf{n}_k\)&lt;/span&gt;, we have the posterior for &lt;span class="math"&gt;\(\boldsymbol\varphi_k\)&lt;/span&gt; as &lt;span class="math"&gt;\(Dir(\boldsymbol\varphi_k|\textbf{n}_k+\boldsymbol\beta)\)&lt;/span&gt;. After some calculation, we can obtain the word distribution for the &lt;span class="math"&gt;\(k\)&lt;/span&gt;th topic as
&lt;div class="math"&gt;\begin{equation}
p(\textbf{w}_k|\textbf{z}_k,\boldsymbol\beta)=\frac{\Delta(\textbf{n}_k+\boldsymbol\beta)}{\Delta(\boldsymbol\beta)}.
\end{equation}&lt;/div&gt;
Taking all topics into account,
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Topic2Word}
p(\textbf{w}|\textbf{z},\boldsymbol\beta)=\prod_{k=1}^K{p(\textbf{w}_k|\textbf{z}_k,\boldsymbol\beta)}=\prod_{k=1}^K{\frac{\Delta(\textbf{n}_k+\boldsymbol\beta)}{\Delta(\boldsymbol\beta)}}.
\end{equation}&lt;/div&gt;
Combining (\ref{Eqn:Doc2Topic}) and (\ref{Eqn:Topic2Word}), we have
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Joint_Distribution}
p(\textbf{w},\textbf{z}|\boldsymbol\alpha,\boldsymbol\beta)=p(\textbf{w}|\textbf{z},\boldsymbol\beta)p(\textbf{z}|\boldsymbol\alpha)=\prod_{k=1}^K{\frac{\Delta(\textbf{n}_k+\boldsymbol\beta)}{\Delta(\boldsymbol\beta)}}\prod_{m=1}^M{\frac{\Delta(\textbf{n}_m+\boldsymbol\alpha)}{\Delta(\boldsymbol\alpha)}}.
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Joint Distribution Emulation by Gibbs Sampling&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;So far we know that the documents can be characterized by a joint distribution of topics and words as shown in (\ref{Eqn:Joint_Distribution}). The words are given, but the associating topics are not. Now we are thinking how to properly associate a topic to each word in each document, such that the result will best fit the joint distribution in (\ref{Eqn:Joint_Distribution}). This is a typical problem that can be solved by &lt;a href="https://en.wikipedia.org/wiki/Gibbs_sampling"&gt;Gibbs sampling&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Gibbs sampling, a special case of Monte Carlo Markov Chain (MCMC) sampling, is a method to emulate high-dimensional probability distributions &lt;span class="math"&gt;\(p(\textbf{x})\)&lt;/span&gt; by the stationary behaviour of a Markov chain. A typical Gibbs sampling works by: (i) Initialize &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt;; (ii) Repeat until convergence: for all &lt;span class="math"&gt;\(i\)&lt;/span&gt;, sample &lt;span class="math"&gt;\(x_i\)&lt;/span&gt; from &lt;span class="math"&gt;\(p(x_i|\textbf{x}_{\neg i})\)&lt;/span&gt;, where &lt;span class="math"&gt;\(\neg i\)&lt;/span&gt; indicates excluding the &lt;span class="math"&gt;\(i\)&lt;/span&gt;th dimension. According to the stationary behaviour of a Markov chain, a sufficiently large collection of samples after convergence would well approximate the desired distribution &lt;span class="math"&gt;\(p(\textbf{x})\)&lt;/span&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In light of the observations above, to apply Gibbs sampling, it is essential to calculate &lt;span class="math"&gt;\(p(x_i|\textbf{x}_{\neg i})\)&lt;/span&gt;. In our case, it is &lt;span class="math"&gt;\(p(z_i=k|\textbf{z}_{\neg i},\textbf{w})\)&lt;/span&gt;, where &lt;span class="math"&gt;\(i=(m,n)\)&lt;/span&gt; is a two dimensional coordinate indicating the &lt;span class="math"&gt;\(n\)&lt;/span&gt;th word of the &lt;span class="math"&gt;\(m\)&lt;/span&gt;th document. Since &lt;span class="math"&gt;\(z_i=k,w_i=t\)&lt;/span&gt; involves the &lt;span class="math"&gt;\(m\)&lt;/span&gt;th document and the &lt;span class="math"&gt;\(k\)&lt;/span&gt;th topic only, &lt;span class="math"&gt;\(p(z_i=k|\textbf{z}_{\neg i},\textbf{w})\)&lt;/span&gt; eventually depends only on two probabilities: (i) the probability of document &lt;span class="math"&gt;\(m\)&lt;/span&gt; emitting topic &lt;span class="math"&gt;\(k\)&lt;/span&gt;, &lt;span class="math"&gt;\(\hat{\vartheta}_{mk}\)&lt;/span&gt;; (ii) the probability of topic &lt;span class="math"&gt;\(k\)&lt;/span&gt; emitting word &lt;span class="math"&gt;\(t\)&lt;/span&gt;, &lt;span class="math"&gt;\(\hat{\varphi}_{kt}\)&lt;/span&gt;. Formally,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Gibbs_Sampling}
p(z_i=k|\textbf{z}_{\neg i},\textbf{w}) \propto \hat{\vartheta}_{mk}\hat{\varphi}_{kt}=\frac{n_{m,\neg i}^{(k)}+\alpha_k}{\sum_{k=1}^K{(n_{m,\neg i}^{(k)}+\alpha_k)}}\frac{n_{k,\neg i}^{(t)}+\beta_t}{\sum_{t=1}^V{(n_{k,\neg i}^{(t)}+\beta_t)}},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(n_m^{(k)}\)&lt;/span&gt; is the count of topic &lt;span class="math"&gt;\(k\)&lt;/span&gt; in document &lt;span class="math"&gt;\(m\)&lt;/span&gt;, &lt;span class="math"&gt;\(n_k^{(t)}\)&lt;/span&gt; is the count of word &lt;span class="math"&gt;\(t\)&lt;/span&gt; for topic &lt;span class="math"&gt;\(k\)&lt;/span&gt;, and &lt;span class="math"&gt;\(\neg i\)&lt;/span&gt; indicates that &lt;span class="math"&gt;\(w_i\)&lt;/span&gt; should not be counted. Besides, &lt;span class="math"&gt;\(\alpha_k\)&lt;/span&gt; and &lt;span class="math"&gt;\(\beta_t\)&lt;/span&gt; are the prior knowledge (pseudo counts) for topic &lt;span class="math"&gt;\(k\)&lt;/span&gt; and word &lt;span class="math"&gt;\(t\)&lt;/span&gt;, respectively. The underlying physical meaning is that (\ref{Eqn:Gibbs_Sampling}) actually characterizes a word-generating path &lt;span class="math"&gt;\(p(topic~k|doc~m)p(word~t|topic~k)\)&lt;/span&gt;.&lt;/p&gt;
&lt;h3&gt;LDA: Training and Inference&lt;sup id="fnref:2"&gt;&lt;a class="footnote-ref" href="#fn:2" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;With the LDA model built, we want to: (i) estimate the model parameters, &lt;span class="math"&gt;\(\boldsymbol\vartheta_m\)&lt;/span&gt; and &lt;span class="math"&gt;\(\boldsymbol\varphi_k\)&lt;/span&gt;, from training documents; (ii) find out the topic distribution, &lt;span class="math"&gt;\(\boldsymbol\vartheta_{new}\)&lt;/span&gt;, for each new document.&lt;/p&gt;
&lt;p&gt;The training procedure is:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialization: assign a topic to each word in each document randomly;&lt;/li&gt;
&lt;li&gt;For each word in each document, update its topic by the Gibbs sampling equation (\ref{Eqn:Gibbs_Sampling});&lt;/li&gt;
&lt;li&gt;Repeat 2 until the Gibbs sampling converges;&lt;/li&gt;
&lt;li&gt;Calculate the topic-to-word model parameter by &lt;span class="math"&gt;\(\hat{\varphi}_{kt}=\frac{n_k^{(t)}+\beta_t}{\sum_{v=1}^V{(n_k^{(t)}+\beta_t)}}\)&lt;/span&gt;, and save them as the model parameters.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Once the LDA model is trained, we are ready to analyze the topic distribution of any new document. The inference works in the following procedure:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialization: assign a topic to each word in the new document randomly;&lt;/li&gt;
&lt;li&gt;For each word in the new document, update its topic by the Gibbs sampling equation (\ref{Eqn:Gibbs_Sampling}) (Note that the &lt;span class="math"&gt;\(\hat{\varphi}_{kt}\)&lt;/span&gt; part is directly available from the trained model, and only &lt;span class="math"&gt;\(\hat{\vartheta}_{mk}\)&lt;/span&gt; needs to be calculated regarding the new document);&lt;/li&gt;
&lt;li&gt;Repeat 2 until the Gibbs sampling converges;&lt;/li&gt;
&lt;li&gt;Calculate the topic distribution by &lt;span class="math"&gt;\(\hat{\vartheta}_{new,k}=\frac{n_{new}^{(k)}+\alpha_k}{\sum_{k=1}^K{(n_{new}^{(k)}+\alpha_k)}}\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There are multiple open-source LDA implementations available online. To learn how LDA could be implemented, a Python implementation can be found &lt;a href="https://github.com/nrolland/pyLDA/blob/master/src/pyLDA.py"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;LDA v.s. Probabilistic Latent Semantic Analysis (PLSA)&lt;/h3&gt;
&lt;p&gt;PLSA is a maximum likelihood (ML) model, while LDA is a maximum a posterior (MAP) model (Bayesian estimation). With that said, LDA would reduce to PLSA if a uniform Dirichlet prior is used. LDA is actually more complex than PLSA, so what could be the key advantages of LDA? The answer is the PRIOR! LDA would defeat PLSA, if there is a good prior for the data and the data by itself is not sufficient to train a model well. &lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;G. Heinrich, &lt;em&gt;&lt;a href="http://www.arbylon.net/publications/text-est.pdf"&gt;Parameter estimation for text analysis&lt;/a&gt;&lt;/em&gt;, 2005.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id="fn:2"&gt;
&lt;p&gt;Z. Jin, &lt;a href="http://cos.name/2013/03/lda-math-lda-text-modeling/"&gt;&lt;em&gt;LDA Topic Modeling (in Chinese)&lt;/em&gt;&lt;/a&gt;,  accessed on Mar 26, 2016.&amp;#160;&lt;a class="footnote-backref" href="#fnref:2" rev="footnote" title="Jump back to footnote 2 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Natural Language Processing"></category><category term="Machine Learning"></category><category term="Data Mining"></category></entry><entry><title>Hidden Markov Model and Part of Speech Tagging</title><link href="https://stlong0521.github.io/20160319%20-%20HMM%20and%20POS.html" rel="alternate"></link><updated>2016-03-19T00:00:00-07:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-03-19:20160319 - HMM and POS.html</id><summary type="html">&lt;p&gt;In a Markov model, we generally assume that the states are directly observable or one state corresponds to one observation/event only. However, this is not always true. A good example would be: in speech recognition, we are supposed to identify a sequence of words given a sequence of utterances, in which case the states (words) are not directly observable and one single state (word) could have different observations (utterances). This is a perfect example that could be treated as a hidden Markov model (HMM), by which the hidden states can be inferred from the observations.&lt;/p&gt;
&lt;h3&gt;Elements of a Hidden Markov Model (HMM)&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;A hidden Markov model, &lt;span class="math"&gt;\(\Phi\)&lt;/span&gt;, typically includes the following elements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Time: &lt;span class="math"&gt;\(t=\{1,2,...,T\}\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(N\)&lt;/span&gt; States: &lt;span class="math"&gt;\(Q=\{1,2,...,N\}\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(M\)&lt;/span&gt; Observations: &lt;span class="math"&gt;\(O=\{1,2,...,M\}\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Initial Probabilities: &lt;span class="math"&gt;\(\pi_i=p(q_1=i),~1 \leq i \leq N\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Transition Probabilities: &lt;span class="math"&gt;\(a_{ij}=p(q_{t+1}=j|q_t=i),~1 \leq i,j \leq N\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Observation Probabilities: &lt;span class="math"&gt;\(b_j(k)=p(o_t=k|q_t=j)~1 \leq j \leq N, 1 \leq k \leq M\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The entire model can be characterized by &lt;span class="math"&gt;\(\Phi=(A,B,\pi)\)&lt;/span&gt;, where &lt;span class="math"&gt;\(A=\{a_{ij}\}\)&lt;/span&gt;, &lt;span class="math"&gt;\(B=\{b_j(k)\}\)&lt;/span&gt; and &lt;span class="math"&gt;\(\pi=\{\pi_i\}\)&lt;/span&gt;. The states are "hidden", since they are not directly observable, but reflected in observations with uncertainty.&lt;/p&gt;
&lt;h3&gt;Three Basic Problems for HMMs&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;There are three basic problems that are very important to real-world applications of HMMs:&lt;/p&gt;
&lt;h4&gt;Problem 1: Evaluation Problem&lt;/h4&gt;
&lt;blockquote&gt;
&lt;p&gt;Given the observation sequence &lt;span class="math"&gt;\(O=o_1o_2...o_T\)&lt;/span&gt; and a model &lt;span class="math"&gt;\(\Phi=(A,B,\pi)\)&lt;/span&gt;, how to efficiently compute the probability of the observation sequence given the model, i.e., &lt;span class="math"&gt;\(p(O|\Phi)\)&lt;/span&gt;?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\alpha_t(i)=p(o_1o_2...o_t,q_t=i|\Phi)
\end{equation}&lt;/div&gt;
&lt;p&gt;
denote the probability that the state is &lt;span class="math"&gt;\(i\)&lt;/span&gt; at time &lt;span class="math"&gt;\(t\)&lt;/span&gt; and we have a sequence of observations &lt;span class="math"&gt;\(o_1o_2...o_t\)&lt;/span&gt;. The evaluation problem can be solved by the forward algorithm as illustrated below:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Base case: 
&lt;div class="math"&gt;\begin{equation}
\alpha_1(i)=p(o_1,q_1=i|\Phi)=p(o_1|q_1=i,\Phi)p(q_1=i|\Phi)=\pi_ib_i(o_1),~1 \leq i \leq N;
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Induction:
&lt;div class="math"&gt;\begin{equation}
\alpha_{t+1}(j)=\left[\sum_{i=1}^N{\alpha_{t}(i)a_{ij}}\right]b_j(o_{t+1}),~1 \leq j \leq N;
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Termination:
&lt;div class="math"&gt;\begin{equation}
p(O|\Phi)=\sum_{i=1}^N{\alpha_T(i)},
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation}
p(q_T=i|O,\Phi)=\frac{\alpha_T(i)}{\sum_{j=1}^N{\alpha_T(j)}}.
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The algorithm above essentially applies dynamic programming, and its complexity is &lt;span class="math"&gt;\(O(N^2T)\)&lt;/span&gt;.&lt;/p&gt;
&lt;h4&gt;Problem 2: Decoding Problem&lt;/h4&gt;
&lt;blockquote&gt;
&lt;p&gt;Given the observation sequence &lt;span class="math"&gt;\(O=o_1o_2...o_T\)&lt;/span&gt; and a model &lt;span class="math"&gt;\(\Phi=(A,B,\pi)\)&lt;/span&gt;, how to choose the "best" state sequence &lt;span class="math"&gt;\(Q=q_1q_2...q_T\)&lt;/span&gt; (the most probable path) in terms of how good it explains the observations?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Define
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
v_t(i)=\max_{q_1q_2...q_{t-1}}{p(q_1q_2...q_{t-1},q_t=i,o_1o_2...o_t|\Phi)}
\end{equation}&lt;/div&gt;
&lt;p&gt;
as the best state sequence through which the state arrives at &lt;span class="math"&gt;\(i\)&lt;/span&gt; at time &lt;span class="math"&gt;\(t\)&lt;/span&gt; with a sequence of observations &lt;span class="math"&gt;\(o_1o_2...o_t\)&lt;/span&gt;. The decoding problem can be solved by the Viterbi algorithm as illustrated below:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Base case: 
&lt;div class="math"&gt;\begin{equation}
v_1(i)=p(q_1=i,o_1|\Phi)=p(o_1|q_1=i,\Phi)p(q_1=i|\Phi)=\pi_ib_i(o_1),~1 \leq i \leq N;
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Induction:
&lt;div class="math"&gt;\begin{equation}
v_{t+1}(j)=\left[\max_i{v_{t}(i)a_{ij}}\right]b_j(o_{t+1}),~1 \leq j \leq N,
\end{equation}&lt;/div&gt;
in which the optimal &lt;span class="math"&gt;\(i\)&lt;/span&gt; from the maximization should be stored properly for backtracking;&lt;/li&gt;
&lt;li&gt;Termination: The best state sequence can be determined by first finding the optimal final state
&lt;div class="math"&gt;\begin{equation}
q_T=\max_i{v_T(i)},
\end{equation}&lt;/div&gt;
and then backtracking all the way to the initial state.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The algorithm above also applies dynamic programming, and its complexity is &lt;span class="math"&gt;\(O(N^2T)\)&lt;/span&gt; as well.&lt;/p&gt;
&lt;h4&gt;Problem 3: Model Learning&lt;/h4&gt;
&lt;blockquote&gt;
&lt;p&gt;Given the observation sequence &lt;span class="math"&gt;\(O=o_1o_2...o_T\)&lt;/span&gt;, how to find the model &lt;span class="math"&gt;\(\Phi=(A,B,\pi)\)&lt;/span&gt; that maximizes &lt;span class="math"&gt;\(p(O|\Phi)\)&lt;/span&gt;?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A general maximum likelihood (ML) learning approach could determine the optimal &lt;span class="math"&gt;\(\Phi\)&lt;/span&gt; as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\hat{\Phi}=\max_{\Phi}{p(O|\Phi)}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
It is much easier to perform supervised learning, where the true state are tagged to each observation. Given &lt;span class="math"&gt;\(V\)&lt;/span&gt; training sequences in total, the model parameters can be estimated as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Supervised_Learning}
\hat{a}_{ij}=\frac{Count(q:i \rightarrow j)}{Count(q:i)},~~\hat{b}_j(k)=\frac{Count(q:j,o:k)}{Count(q:j)},~~\hat{\pi}_i=\frac{Count(q_1=i)}{V}.
\end{equation}&lt;/div&gt;
&lt;p&gt;It becomes a little bit tricky for unsupervised learning, where the true state are not tagged. To facilitate our model learning, we need to first introduce the following definition/calculation:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Episilon}
\varepsilon_t(i,j)=p(q_t=i,q_{t+1}=j|O,\Phi)=\frac{p(q_t=i,q_{t+1}=j,O|\Phi)}{p(O|\Phi)}=\frac{\alpha_t(i)a_{ij}b_j(o_{t+1})\beta_{t+1}(j)}{\sum_{i=1}^N{\alpha_T(i)}},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(p(O|\Phi)\)&lt;/span&gt; is exactly Problem 1 we have yet talked about. &lt;span class="math"&gt;\(\beta_{t+1}(j)\)&lt;/span&gt; can be calculated using the backward algorithm, which is very similar to the forward algorithm in Problem 1 to calculate &lt;span class="math"&gt;\(\alpha_t(i)\)&lt;/span&gt; except the difference in the direction of calculation. Following (\ref{Eqn:Episilon}), we further introduce
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Gamma}
\gamma_t(i)=p(q_t=i|O,\Phi)=\sum_{j=1}^N{\varepsilon_t(i,j)}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
Then the model parameters can be recomputed as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\begin{split}
\hat{a}_{ij}&amp;amp;=\frac{Expected~number~of~transitions~from~state~i~to~j}{Expected~number~of~transitions~from~state~i}\\
&amp;amp;=\frac{\sum_{t=1}^{T-1}{\varepsilon_t(i,j)}}{\sum_{t=1}^{T-1}{\gamma_t(i)}},
\end{split}
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation}
\begin{split}
\hat{b}_j(k)&amp;amp;=\frac{Expected~number~of~times~in~state~j~and~observing~k}{Expected~number~of~times~in~state~j}\\
&amp;amp;=\frac{\sum_{t=1,~s.t.~o_t=k}^{T}{\gamma_t(j)}}{\sum_{t=1}^{T}{\gamma_t(j)}},
\end{split}
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation}
\begin{split}
\hat{\pi}_i&amp;amp;=Expected~number~of~times~in~state~i~at~time~t=1\\
&amp;amp;=\gamma_1(i).
\end{split}
\end{equation}&lt;/div&gt;
&lt;p&gt;Now we are ready to apply the &lt;a href="20160312 - EM and GMM.html"&gt;expectation maximization (EM) algorithm&lt;/a&gt; for HMM learning. More specifically:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialize the HMM, &lt;span class="math"&gt;\(\Phi\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Repeat the two steps below until convergence:&lt;ul&gt;
&lt;li&gt;E Step: Given observations &lt;span class="math"&gt;\(o_1o_2...o_T\)&lt;/span&gt; and the model &lt;span class="math"&gt;\(\Phi\)&lt;/span&gt;, compute &lt;span class="math"&gt;\(\varepsilon_t(i,j)\)&lt;/span&gt; by (\ref{Eqn:Episilon}) and &lt;span class="math"&gt;\(\gamma_t(i)\)&lt;/span&gt; by (\ref{Eqn:Gamma});&lt;/li&gt;
&lt;li&gt;M Step: Update the model &lt;span class="math"&gt;\(\Phi\)&lt;/span&gt; by recomputing parameters using the three equations right above.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Part of Speech (POS) Tagging&lt;/h3&gt;
&lt;p&gt;In natural language processing, part of speech (POS) tagging is to associate with each word in a sentence a lexical tag. As an example, Janet (NNP) will (MD) back (VB) the (DT) bill (NN), in which each POS tag describes what its corresponding word is about. In this particular example, "VB" tells that "back" is a verb, and "NN" tells that "bill" is a noun, etc.&lt;/p&gt;
&lt;p&gt;POS tagging is very useful, because it is usually the first step of many practical tasks, e.g., speech synthesis, grammatical parsing and information extraction. For instance, if we want to pronounce the word "record" correctly, we need to first learn from context if it is a noun or verb and then determine where the stress is in its pronunciation. A similar argument applies to grammatical parsing and information extraction as well.&lt;/p&gt;
&lt;p&gt;We need to do some preprocessing before performing POS tagging using HMM. First, because the vocabulary size could be very large while most of the words are not frequently used, we replace each low-frequency word with a special word "UNKA". This is very helpful to reduce the vocabulary size, and thus reduce the memory cost on storing the probability matrix. Second, for each sentence, we add two tags to represent sentence boundaries, e.g., "START" and "END".&lt;/p&gt;
&lt;p&gt;Now we are ready to apply HMM to perform POS tagging. The model can be characterized by:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Time: length of each sentence;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(N\)&lt;/span&gt; States: POS tags, e.g., 45 POS tags from Penn Treebank;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(M\)&lt;/span&gt; Observations: vocabulary (compressed by replacing low-frequency words with "UNKA");&lt;/li&gt;
&lt;li&gt;Initial Probabilities: probability of each tag associated to the first word;&lt;/li&gt;
&lt;li&gt;Transition Probabilities: &lt;span class="math"&gt;\(p(t_{i+1}|t_i)\)&lt;/span&gt;, where &lt;span class="math"&gt;\(t_i\)&lt;/span&gt; represents the tag for the &lt;span class="math"&gt;\(i\)&lt;/span&gt;th word;&lt;/li&gt;
&lt;li&gt;Observation Probabilities: &lt;span class="math"&gt;\(p(w|t)\)&lt;/span&gt;, where &lt;span class="math"&gt;\(t\)&lt;/span&gt; stands for a tag and &lt;span class="math"&gt;\(w\)&lt;/span&gt; stands for a word.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Once we finish training the model, e.g., under supervised learning by (\ref{Eqn:Supervised_Learning}), we will then be able to tag new sentences applying the Viterbi algorithm as previously illustrated in Problem 2 for HMM. To see details about implementing POS tagging using HMM, &lt;a href="https://github.com/stlong0521/hmm-pos"&gt;click here&lt;/a&gt; for demo codes.&lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;L. R. Rabiner, &lt;em&gt;A tutorial on hidden Markov models and selected applications in speech recognition&lt;/em&gt;, in Proceedings of the IEEE, vol. 77, no. 2, pp. 257-286, Feb 1989.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Natural Language Processing"></category><category term="Machine Learning"></category><category term="Data Mining"></category></entry><entry><title>Expectation Maximization Algorithm and Gaussian Mixture Model</title><link href="https://stlong0521.github.io/20160312%20-%20EM%20and%20GMM.html" rel="alternate"></link><updated>2016-03-12T00:00:00-08:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-03-12:20160312 - EM and GMM.html</id><summary type="html">&lt;p&gt;In statistical modeling, it is possible that some observations are just missing. For example, when flipping two biased coins with unknown biases, we only have a sequence of observations on heads and tails, but forgot to record which coin each observation comes from. In this case, the conventional maximum likelihood (ML) or maximum a posteriori (MAP) algorithm would no longer be able to work, and it is time for the expectation maximization (EM) algorithm to come into play.&lt;/p&gt;
&lt;h3&gt;A Motivating Example&lt;/h3&gt;
&lt;p&gt;Although the two-biased-coin example above works as a valid example, another example will be discussed here, as it is more relevant to practical needs. Let us assume that we have a collection of float numbers, which come from two different Gaussian distributions. Unfortunately, we do not know which distribution each number comes from. Now we are supposed to learn the two Gaussian distributions (i,e, their means and variances) from the given data. This is the well-known Gaussian mixture model (GMM). What makes things difficult is that we have missing observations, i.e., membership of each number towards the two distributions. Though conventional ML or MAP would not work here, this is a perfect problem that EM can handle.&lt;/p&gt;
&lt;h3&gt;Expectation Maximization (EM) Algorithm&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;Let us consider a statistical model with a vector of unknown parameters &lt;span class="math"&gt;\(\boldsymbol\theta\)&lt;/span&gt;, which generates a set of observed data &lt;span class="math"&gt;\(\textbf{X}\)&lt;/span&gt; and a set of missing observations &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt;. The likelihood function, &lt;span class="math"&gt;\(p(\textbf{X},\textbf{Z}|\boldsymbol\theta)\)&lt;/span&gt;, characterizes the probability that &lt;span class="math"&gt;\(\textbf{X}\)&lt;/span&gt; and &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt; appear given the model with parameters &lt;span class="math"&gt;\(\boldsymbol\theta\)&lt;/span&gt;. An intuitive idea to estimate &lt;span class="math"&gt;\(\boldsymbol\theta\)&lt;/span&gt; would be trying to perform the maximum likelihood estimation (MLE) considering all possible &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt;, i.e.,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\max_{\boldsymbol\theta}{\ln{p(\textbf{X}|\boldsymbol\theta)}}=\max_{\boldsymbol\theta}{\ln{\sum_{\textbf{Z}}{p(\textbf{X},\textbf{Z}|\boldsymbol\theta)}}}=\max_{\boldsymbol\theta}{\ln{\sum_{\textbf{Z}}{p(\textbf{X}|\textbf{Z},\boldsymbol\theta)p(\textbf{Z}|\boldsymbol\theta)}}}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
Unfortunately, the problem above is not directly tractable, since we do not have any prior knowledge on the missing observations &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;The EM algorithm aims to solve the problem above by starting with a guess on &lt;span class="math"&gt;\(\boldsymbol\theta=\boldsymbol\theta_{0}\)&lt;/span&gt; and then iteratively applying the two steps as indicated below:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Expectation Step (E Step):&lt;/em&gt; Calculate the log likelihood with respect to &lt;span class="math"&gt;\(\boldsymbol\theta\)&lt;/span&gt; given &lt;span class="math"&gt;\(\boldsymbol\theta_{t}\)&lt;/span&gt; by
&lt;div class="math"&gt;\begin{equation}
\mathcal{L}(\boldsymbol\theta|\boldsymbol\theta_{t})=\ln{\sum_{\textbf{Z}}{p(\textbf{X}|\textbf{Z},\boldsymbol\theta_{t})p(\textbf{Z}|\boldsymbol\theta_{t})}};
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Maximization Step (M Step):&lt;/em&gt; Find the parameter vector that maximizes the log likelihood above and then update it as
&lt;div class="math"&gt;\begin{equation}
\theta_{t+1}={\arg \, \max}_{\theta}{\mathcal{L}(\boldsymbol\theta|\boldsymbol\theta_{t})}.
\end{equation}&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There are two things that should be noted here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;There are two categories of EM: &lt;em&gt;hard&lt;/em&gt; EM and &lt;em&gt;soft&lt;/em&gt; EM. The algorithm illustrated above is soft EM, because the log likelihood in the E step is weighted upon all possible &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt; with their probabilities. While in hard EM, instead of using weighted average, we simply select the most probable &lt;span class="math"&gt;\(\textbf{Z}\)&lt;/span&gt; and then move forward. The &lt;a href="https://en.wikipedia.org/wiki/K-means_clustering"&gt;k-means algorithm&lt;/a&gt; is a good example of hard EM algorithm.&lt;/li&gt;
&lt;li&gt;The EM algorithm typically converges to a local optimum, and &lt;em&gt;cannot&lt;/em&gt; guarantee global optimum. With this being said, the solution might differ with different initialization, and it is possibly helpful to try more than one initialization when applying EM practically.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Gaussian Mixture Model (GMM)&lt;/h3&gt;
&lt;p&gt;In the motivating example, a GMM with two Gaussian distributions was introduced. Here we are going to extend it to a general case with &lt;span class="math"&gt;\(K\)&lt;/span&gt; Gaussian distributions, and the data points will be generalized to be multidimensional. At the same time, we will discuss how it can be used for clustering.&lt;/p&gt;
&lt;p&gt;Given a data set containing &lt;span class="math"&gt;\(N\)&lt;/span&gt; data points, &lt;span class="math"&gt;\(\mathcal{D}=\{\textbf{x}_1,\textbf{x}_2,...,\textbf{x}_N\}\)&lt;/span&gt;, in which each data point is a &lt;span class="math"&gt;\(M\)&lt;/span&gt;-dimensional column vector and comes from one of &lt;span class="math"&gt;\(K\)&lt;/span&gt; Gaussian distributions. Here we will introduce &lt;span class="math"&gt;\(\mathcal{Z}=\{z_1,z_2,...,z_N\}\)&lt;/span&gt; with &lt;span class="math"&gt;\(z_i\in\{1,2,...,K\}\)&lt;/span&gt; as latent (hidden) variables to represent the cluster membership of the data points in &lt;span class="math"&gt;\(\mathcal{D}\)&lt;/span&gt;. The &lt;span class="math"&gt;\(K\)&lt;/span&gt; Gaussian distributions are characterized by &lt;span class="math"&gt;\(\mathcal{N}(\boldsymbol\mu_j,\boldsymbol\Sigma_j)\)&lt;/span&gt; for &lt;span class="math"&gt;\(j=1,2,...,K\)&lt;/span&gt;, and the &lt;span class="math"&gt;\(j\)&lt;/span&gt;th distribution has a weight of &lt;span class="math"&gt;\(\pi_j\)&lt;/span&gt; accounted in the overall distribution. Let us first try to map this GMM model to the EM algorithm component by component:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span class="math"&gt;\(\mathcal{D}\)&lt;/span&gt; is the observed data;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(\mathcal{Z}\)&lt;/span&gt; is the missing observations;&lt;/li&gt;
&lt;li&gt;&lt;span class="math"&gt;\(\boldsymbol\mu_j\)&lt;/span&gt;, &lt;span class="math"&gt;\(\boldsymbol\Sigma_j\)&lt;/span&gt; and &lt;span class="math"&gt;\(\pi_j\)&lt;/span&gt; are the unknown model parameters.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Following the EM algorithm, we will start with a guess on the unknown parameters, and then iteratively applying E step and M step until convergence. In the E step, we calculate the log likelihood based on given model parameters by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
LL&amp;amp;=\ln{p(\textbf{x}_1,\textbf{x}_2,...,\textbf{x}_N)}\\
&amp;amp;=\ln{\prod_{i=1}^{N}{p(\textbf{x}_i)}}\\
&amp;amp;=\ln{\prod_{i=1}^{N}{\sum_{j=1}^{K}{p(z_i=j)p(\textbf{x}_i|z_i=j)}}}\\
&amp;amp;=\sum_{i=1}^{N}{\ln\left(\sum_{j=1}^{K}{\pi_j\mathcal{N}(\textbf{x}_i|\boldsymbol\mu_j,\boldsymbol\Sigma_j)}\right)}.
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;In the M step, we maximize the log likelihood by solving the optimization problem below:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
\max_{\boldsymbol\mu_j,\boldsymbol\Sigma_j,\pi_j}~~&amp;amp;{LL}\\
&amp;amp;s.t.~\sum_{j=1}^{K}{\pi_j}=1.
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;
We can apply Lagrange multiplier to solve the problem above. Let
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
L=\sum_{i=1}^{N}{\ln\left(\sum_{j=1}^{K}{\pi_j\mathcal{N}(\textbf{x}_i|\boldsymbol\mu_j,\boldsymbol\Sigma_j)}\right)}-\lambda\left(\sum_{j=1}^{K}{\pi_j}-1\right),
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\lambda\)&lt;/span&gt; is the Lagrange multiplier. Taking partial derivatives and setting them to zero, we can obtain the optimal parameters as below:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Maximization_1}
\boldsymbol\mu_j=\frac{\sum_{i=1}^{N}{\gamma_{ij}}\textbf{x}_i}{\sum_{i=1}^{N}{\gamma_{ij}}},
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Maximization_2}
\boldsymbol\Sigma_j=\frac{\sum_{i=1}^{N}{\gamma_{ij}}(\textbf{x}_i-\boldsymbol\mu_j)(\textbf{x}_i-\boldsymbol\mu_j)^T}{\sum_{i=1}^{N}{\gamma_{ij}}},
\end{equation}&lt;/div&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Maximization_3}
\pi_j=\frac{1}{N}{\sum_{i=1}^{N}{\gamma_{ij}}},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\gamma_{ij}=p(z_i=j|\textbf{x}_i)\)&lt;/span&gt; is the cluster membership, which can be calculated using Bayes theorem,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\begin{split}
\gamma_{ij}&amp;amp;=p(z_i=j|\textbf{x}_i)\\
&amp;amp;=\frac{p(z_i=j)p(\textbf{x}_i|z_i=j)}{\sum_{j=1}^{K}{p(z_i=j)p(\textbf{x}_i|z_i=j)}}\\
&amp;amp;=\frac{\pi_j\mathcal{N}(\textbf{x}_i|\boldsymbol\mu_j,\boldsymbol\Sigma_j)}{\sum_{j=1}^{K}{\pi_j\mathcal{N}(\textbf{x}_i|\boldsymbol\mu_j,\boldsymbol\Sigma_j)}}.
\end{split}
\end{equation}&lt;/div&gt;
&lt;p&gt;To summarize, the GMM model can be learned using EM algorithm as in the following steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialize &lt;span class="math"&gt;\(\boldsymbol\mu_j\)&lt;/span&gt;, &lt;span class="math"&gt;\(\boldsymbol\Sigma_j\)&lt;/span&gt; and &lt;span class="math"&gt;\(\pi_j\)&lt;/span&gt; for &lt;span class="math"&gt;\(j=1,2,...,K\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;Repeat the following two steps until the log likelihood converges:&lt;ul&gt;
&lt;li&gt;E Step: Estimate cluster membership &lt;span class="math"&gt;\(\gamma_{ij}\)&lt;/span&gt; by the equation right above for all data point &lt;span class="math"&gt;\(x_i\)&lt;/span&gt; and cluster &lt;span class="math"&gt;\(z_i=j\)&lt;/span&gt;;&lt;/li&gt;
&lt;li&gt;M Step: Maximize the log likelihood and update the model parameters by (\ref{Eqn:Maximization_1})-(\ref{Eqn:Maximization_3}) based on cluster membership &lt;span class="math"&gt;\(\gamma_{ij}\)&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;Wikipedia, &lt;a href="https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm"&gt;&lt;em&gt;Expectation–maximization algorithm&lt;/em&gt;&lt;/a&gt;, accessed on Mar 12, 2016.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Machine Learning"></category><category term="Data Mining"></category></entry><entry><title>Locating and Filling Missing Words in Sentences</title><link href="https://stlong0521.github.io/20160305%20-%20Missing%20Word.html" rel="alternate"></link><updated>2016-03-05T00:00:00-08:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-03-05:20160305 - Missing Word.html</id><summary type="html">&lt;p&gt;There has been many occasions that we have incomplete sentences that are needed to completed. One example is that in speech recognition noisy environment can lead to unrecognizable words, but we still hope to recover and understand the complete sentence (e.g., by inference); another example is sentence completion questions that appear in language tests (e.g., SAT, GRE, etc.).&lt;/p&gt;
&lt;h3&gt;What are Exactly the Problem?&lt;/h3&gt;
&lt;p&gt;Generally, the problem we are aiming to solve is locating and filling any missing words in incomplete sentences. However, this problem seems too ambitious so far, and we direct ourselves to a simplified version of this problem. To simplify the problem, we assume that there is only one missing word in a sentence, and the missing word is neither the first word nor the last word of the sentence. This problem originally comes from &lt;a href="https://www.kaggle.com/c/billion-word-imputation"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Locating the Missing Word&lt;/h3&gt;
&lt;p&gt;Two approaches are presented here so as to locate the missing word.&lt;/p&gt;
&lt;h4&gt;N-gram Model&lt;/h4&gt;
&lt;p&gt;For a given training data set, define &lt;span class="math"&gt;\(C(w_1,w_2)\)&lt;/span&gt; as the number of occurrences of the bigram pattern &lt;span class="math"&gt;\((w_1,w_2)\)&lt;/span&gt;, and &lt;span class="math"&gt;\(C(w_1,w,w_2)\)&lt;/span&gt; the number of occurrences of the trigram pattern &lt;span class="math"&gt;\((w_1,w,w_2)\)&lt;/span&gt;. Then, the number of occurrences of the pattern, where there is one and only one word between &lt;span class="math"&gt;\(w_1\)&lt;/span&gt; and &lt;span class="math"&gt;\(w_2\)&lt;/span&gt;, can be calculated by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
D(w_1,w_2)=\sum_{w\in{V}}C(w_1,w,w_2),
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(V\)&lt;/span&gt; is the vocabulary.&lt;/p&gt;
&lt;p&gt;Consider a particular location, &lt;span class="math"&gt;\(l\)&lt;/span&gt;, of an incomplete sentence of length &lt;span class="math"&gt;\(L\)&lt;/span&gt;, and let &lt;span class="math"&gt;\(w_l\)&lt;/span&gt; be the &lt;span class="math"&gt;\(l\)&lt;/span&gt;th word in the sentence. &lt;span class="math"&gt;\(D(w_{l-1},w_{l})\)&lt;/span&gt; would be the number of positive votes from the training data set for missing word at this location, while &lt;span class="math"&gt;\(C(w_{l-1},w_{l})\)&lt;/span&gt; would be correspondingly the number of negative votes. We define the score indicating there is a missing word at location &lt;span class="math"&gt;\(l\)&lt;/span&gt; as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Score}
S_l=\frac{D(w_{l-1},w_{l})^{1+\gamma}}{C(w_{l-1},w_{l})+D(w_{l-1},w_{l})}-\frac{C(w_{l-1},w_{l})^{1+\gamma}}{C(w_{l-1},w_{l})+D(w_{l-1},w_{l})},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt; is a small positive constant. Hence, the missing word location can be identified by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\hat{l}={\arg \, \max}_{1 \leq l \leq L-1} S_l.
\end{equation}&lt;/div&gt;
&lt;p&gt;Note that in (\ref{Eqn:Score}), if we set &lt;span class="math"&gt;\(\gamma=0\)&lt;/span&gt;, the left part would be exactly the percentage of positive votes for missing word at that location, and the right part is the percentage of negative votes. It seems a fairly reasonable score, then &lt;em&gt;why do we still need a positive &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt;&lt;/em&gt;? The underlying reason is that intuitively the more number of votes for a particular decision, the more confident we are on that decision. This trend is reflected in a positive &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt;, which can be viewed as &lt;em&gt;sparse vote penalty&lt;/em&gt; and is useful in breaking ties in the missing word location voting. That is, if we have exactly the same ratio of positive votes relative to negative votes for two candidate locations, e.g., 80 positive votes v.s. 20 negative votes for location A, and 8 positive votes v.s. 2 negative votes for location B, we would believe that location A is more likely to be the missing word location compared with location B.&lt;/p&gt;
&lt;h4&gt;Word Distance Statistics (WDS)&lt;/h4&gt;
&lt;p&gt;In view of the fact that the statistics of the two words immediately adjacent to a given location contribute a lot in deciding whether the location has a word missing, we tentatively guess that all the words within a window centered at that location would more or less contribute some information as well. As a result, we introduce the concept of word distance statistics (WDS).&lt;/p&gt;
&lt;p&gt;More specifically, we use &lt;span class="math"&gt;\(\widetilde{C}(w_1,w_2,m)\)&lt;/span&gt; to denote the number of occurrences of the pattern, where there is exactly &lt;span class="math"&gt;\(m\)&lt;/span&gt; words between &lt;span class="math"&gt;\(w_1\)&lt;/span&gt; and &lt;span class="math"&gt;\(w_2\)&lt;/span&gt;, i.e., the word distance of &lt;span class="math"&gt;\(w_1\)&lt;/span&gt; and &lt;span class="math"&gt;\(w_2\)&lt;/span&gt; is &lt;span class="math"&gt;\(m\)&lt;/span&gt;. For a given location &lt;span class="math"&gt;\(l\)&lt;/span&gt; in an incomplete sentence and a word window size &lt;span class="math"&gt;\(W\)&lt;/span&gt;, we are interested in the word distance statistics of each word pair, in which one word &lt;span class="math"&gt;\(w_i\)&lt;/span&gt; is on the left of the location &lt;span class="math"&gt;\(l\)&lt;/span&gt;, and the other word &lt;span class="math"&gt;\(w_j\)&lt;/span&gt; is on the right, as illustrated in Fig. 1.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160305/WDS.png" alt="WDS"&gt;
&lt;figcaption align="center"&gt;Fig. 1: Word distance illustration.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Formally, for any &lt;span class="math"&gt;\(l-W/2 \leq i \leq l-1\)&lt;/span&gt; and &lt;span class="math"&gt;\(l \leq j \leq l+W/2-1\)&lt;/span&gt;, &lt;span class="math"&gt;\(\widetilde{C}(w_i,w_j,j-i)\)&lt;/span&gt; would be the number of positive votes for missing word at this location, while &lt;span class="math"&gt;\(\widetilde{C}(w_i,w_j,j-i-1)\)&lt;/span&gt; is the number of negative votes. Applying the idea in (\ref{Eqn:Score}), for each word pair &lt;span class="math"&gt;\((w_i,w_j)\)&lt;/span&gt;, we extract its feature as the score indicating there is a missing word at location &lt;span class="math"&gt;\(l\)&lt;/span&gt;, i.e.,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:ScoreGeneralized}
S_l(i,j)=\frac{\widetilde{C}(w_i,w_j,j-i)^{1+\gamma}}{\widetilde{C}(w_i,w_j,j-i)+\widetilde{C}(w_i,w_j,j-i-1)}-\frac{\widetilde{C}(w_i,w_j,j-i-1)^{1+\gamma}}{\widetilde{C}(w_i,w_j,j-i)+\widetilde{C}(w_i,w_j,j-i-1)}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
As a special example, let &lt;span class="math"&gt;\(i=l-1\)&lt;/span&gt; and &lt;span class="math"&gt;\(j=l\)&lt;/span&gt;, (\ref{Eqn:ScoreGeneralized}) would be reduced to (\ref{Eqn:Score}).&lt;/p&gt;
&lt;p&gt;To find the missing word location, we need to assign different weights to the extracted features, &lt;span class="math"&gt;\(S_l(i,j)\)&lt;/span&gt;. Then, the missing word location can be determined by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:LocationDetermination}
\hat{l}={\arg \, \max}_{1 \leq l \leq L-1} \sum_{l-\frac{W}{2} \leq i \leq l-1}\sum_{l \leq j \leq l+\frac{W}{2}-1}v(i,j)S_l(i,j),
\end{equation}&lt;/div&gt;
&lt;p&gt;
where the weight, &lt;span class="math"&gt;\(v(i,j)\)&lt;/span&gt;, should be monotonically decreasing with respect to &lt;span class="math"&gt;\(|j-i|\)&lt;/span&gt;.&lt;/p&gt;
&lt;h3&gt;Filling the Missing Word&lt;/h3&gt;
&lt;p&gt;To find the most probable word in the given missing word location, we take into account five conditional probabilities, as shown in Table 1, to explore the statistical connection between the candidate words and the surrounding words at the missing word location. Ultimately, the most probable missing word can be determined by
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\hat{w}={\arg \, \max}_{w\in{B}} \sum_{1 \leq i \leq 5} v_iP_i,
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(B\)&lt;/span&gt; is the candidate word space (detailed &lt;a href="https://github.com/stlong0521/missing-word/blob/master/Project%20Report.pdf"&gt;here&lt;/a&gt;), and the weight &lt;span class="math"&gt;\(v_i\)&lt;/span&gt; is used to reflect the importance of each conditional probability in contributing to the final score.&lt;/p&gt;
&lt;figure align="center"&gt;
&lt;img src="/figures/20160305/CondProb.png" alt="CondProb"&gt;
&lt;figcaption align="center"&gt;Table 1: Conditional probabilities considered in missing word filling, in which "*" denotes an arbitrary word.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h3&gt;Experimental Results&lt;/h3&gt;
&lt;p&gt;The training data contains &lt;span class="math"&gt;\(30,301,028\)&lt;/span&gt; complete sentences, of which the average sentence length is approximately &lt;span class="math"&gt;\(25\)&lt;/span&gt;. In the vocabulary with a size of &lt;span class="math"&gt;\(2,425,337\)&lt;/span&gt;, &lt;span class="math"&gt;\(14,216\)&lt;/span&gt; words that have occurred in at least &lt;span class="math"&gt;\(0.1\%\)&lt;/span&gt; of total sentences are labeled as high-frequency words, and the remaining &lt;span class="math"&gt;\(58,417,315\)&lt;/span&gt; words are labeled as 'UNKA'. To perform the cross validation, in our experiments, the training data is splitted into two part, TRAIN and DEV. The TRAIN set is used to train our models, and the DEV set is applied to test our models.&lt;/p&gt;
&lt;h4&gt;Missing Word Location&lt;/h4&gt;
&lt;p&gt;Table 2 shows the estimation accuracy of the missing word locations for the two proposed approaches, N-gram and WDS. For comparison, we list the corresponding probabilities by chance as well. Each entry shows the probabilities that the correct location is included in the ranked candidate location list returned by each approach, where the list size varies from &lt;span class="math"&gt;\(1\)&lt;/span&gt; to &lt;span class="math"&gt;\(10\)&lt;/span&gt;. The sparse vote penalty coefficient, &lt;span class="math"&gt;\(\gamma\)&lt;/span&gt;, is set to 0.01. In the WDS approach, we consider a word window size &lt;span class="math"&gt;\(W=4\)&lt;/span&gt;, i.e., four pairs of words are taken into account.&lt;/p&gt;
&lt;table class="table table-striped table-bordered table-hover"&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="center"&gt;&lt;/th&gt;
&lt;th align="center"&gt;Top 1&lt;/th&gt;
&lt;th align="center"&gt;Top 2&lt;/th&gt;
&lt;th align="center"&gt;Top 3&lt;/th&gt;
&lt;th align="center"&gt;Top 5&lt;/th&gt;
&lt;th align="center"&gt;Top 10&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="center"&gt;Chance&lt;/td&gt;
&lt;td align="center"&gt;4%&lt;/td&gt;
&lt;td align="center"&gt;8%&lt;/td&gt;
&lt;td align="center"&gt;12%&lt;/td&gt;
&lt;td align="center"&gt;20%&lt;/td&gt;
&lt;td align="center"&gt;40%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;N-gram&lt;/td&gt;
&lt;td align="center"&gt;51.47%&lt;/td&gt;
&lt;td align="center"&gt;63.70%&lt;/td&gt;
&lt;td align="center"&gt;71.00%&lt;/td&gt;
&lt;td align="center"&gt;80.26%&lt;/td&gt;
&lt;td align="center"&gt;91.54%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align="center"&gt;WDS&lt;/td&gt;
&lt;td align="center"&gt;52.06%&lt;/td&gt;
&lt;td align="center"&gt;64.50%&lt;/td&gt;
&lt;td align="center"&gt;71.76%&lt;/td&gt;
&lt;td align="center"&gt;80.91%&lt;/td&gt;
&lt;td align="center"&gt;91.93%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;figcaption align="center"&gt;Table 2: Accuracy of missing word location.&lt;/figcaption&gt;

&lt;h4&gt;Missing Word Filling&lt;/h4&gt;
&lt;p&gt;Table 3 shows the accuracies of filling the missing word given the location. Each row of the second column shows the probability that the correct word is included in the ranked candidate words list returned by the proposed approach.&lt;/p&gt;
&lt;table class="table table-striped table-bordered table-hover"&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align="center"&gt;&lt;/th&gt;
&lt;th align="center"&gt;Top 1&lt;/th&gt;
&lt;th align="center"&gt;Top 2&lt;/th&gt;
&lt;th align="center"&gt;Top 3&lt;/th&gt;
&lt;th align="center"&gt;Top 5&lt;/th&gt;
&lt;th align="center"&gt;Top 10&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td align="center"&gt;Accuracy&lt;/td&gt;
&lt;td align="center"&gt;32.15%&lt;/td&gt;
&lt;td align="center"&gt;41.49%&lt;/td&gt;
&lt;td align="center"&gt;46.23%&lt;/td&gt;
&lt;td align="center"&gt;52.02%&lt;/td&gt;
&lt;td align="center"&gt;59.15%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;figcaption align="center"&gt;Table 3: Accuracy of missing word filling.&lt;/figcaption&gt;

&lt;h3&gt;Acknowledgement&lt;/h3&gt;
&lt;p&gt;I did this project with my partner, &lt;a href="https://zhwa.github.io/"&gt;Zhe Wang&lt;/a&gt;. To see the codes and/or report, &lt;a href="https://github.com/stlong0521/missing-word"&gt;click here&lt;/a&gt; for more information.&lt;/p&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Natural Language Processing"></category></entry><entry><title>Binary and Multiclass Logistic Regression Classifiers</title><link href="https://stlong0521.github.io/20160228%20-%20Logistic%20Regression.html" rel="alternate"></link><updated>2016-02-28T00:00:00-08:00</updated><author><name>Tianlong Song</name></author><id>tag:stlong0521.github.io,2016-02-28:20160228 - Logistic Regression.html</id><summary type="html">&lt;p&gt;The generative classification model, such as Naive Bayes, tries to learn the probabilities and then predict by using Bayes rules to calculate the posterior, &lt;span class="math"&gt;\(p(y|\textbf{x})\)&lt;/span&gt;. However, discrimitive classifiers model the posterior directly. As one of the most popular discrimitive classifiers, logistic regression directly models the linear decision boundary.&lt;/p&gt;
&lt;h3&gt;Binary Logistic Regression Classifier&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;Let us start with the binary case. For an M-dimensional feature vector &lt;span class="math"&gt;\(\textbf{x}=[x_1,x_2,...,x_M]^T\)&lt;/span&gt;, the posterior probability of class &lt;span class="math"&gt;\(y\in\{\pm{1}\}\)&lt;/span&gt; given &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt; is assumed to satisfy
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\ln{\frac{p(y=1|\textbf{x})}{p(y=-1|\textbf{x})}}=\textbf{w}^T\textbf{x},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\textbf{w}=[w_1,w_2,...,w_M]^T\)&lt;/span&gt; is the weighting vector to be learned. Given the constraint that &lt;span class="math"&gt;\(p(y=1|\textbf{x})+p(y=-1|\textbf{x})=1\)&lt;/span&gt;, it follows that
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Prob_Binary}
p(y|\textbf{x})=\frac{1}{1+\exp(-y\textbf{w}^T\textbf{x})}=\sigma(y\textbf{w}^T\textbf{x}),
\end{equation}&lt;/div&gt;
&lt;p&gt;
in which we can observe the logistic sigmoid function &lt;span class="math"&gt;\(\sigma(a)=\frac{1}{1+\exp(-a)}\)&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;Based on the assumptions above, the weighting vector, &lt;span class="math"&gt;\(\textbf{w}\)&lt;/span&gt;, can be learned by maximum likelihood estimation (MLE). More specifically, given training data set &lt;span class="math"&gt;\(\mathcal{D}=\{(\textbf{x}_1,y_1),(\textbf{x}_2,y_2),...,(\textbf{x}_N,y_N)\}\)&lt;/span&gt;,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
\textbf{w}^*&amp;amp;=\max_{\textbf{w}}{\mathcal{L}(\textbf{w})}\\
&amp;amp;=\max_{\textbf{w}}{\sum_{i=1}^N\ln{{p(y_i|\textbf{x}_i)}}}\\
&amp;amp;=\max_{\textbf{w}}{\sum_{i=1}^N{\ln{\frac{1}{1+\exp(-y_i\textbf{w}^T\textbf{x}_i)}}}}\\
&amp;amp;=\min_{\textbf{w}}{\sum_{i=1}^N{\ln{(1+\exp(-y_i\textbf{w}^T\textbf{x}_i))}}}.
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;
We have a convex objective function here, and we can calculate the optimal solution by applying gradient descent. The gradient can be drawn as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
\nabla{\mathcal{L}(\textbf{w})}&amp;amp;=\sum_{i=1}^N{\frac{-y_i\textbf{x}_i\exp(-y_i\textbf{w}^T\textbf{x}_i)}{1+\exp(-y_i\textbf{w}^T\textbf{x}_i)}}\\
&amp;amp;=-\sum_{i=1}^N{y_i\textbf{x}_i(1-p(y_i|\textbf{x}_i))}.
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;
Then, we can learn the optimal &lt;span class="math"&gt;\(\textbf{w}\)&lt;/span&gt; by starting with an initial &lt;span class="math"&gt;\(\textbf{w}_0\)&lt;/span&gt; and iterating as follows:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Iteration_Binary}
\textbf{w}_{t+1}=\textbf{w}_{t}-\eta_t\nabla{\mathcal{L}(\textbf{w})},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\eta_t\)&lt;/span&gt; is the learning step size. It can be invariant to time, but time-varying step sizes could potential reduce the convergence time, e.g., setting &lt;span class="math"&gt;\(\eta_t\propto{1/\sqrt{t}}\)&lt;/span&gt; such that the step size decreases with an increasing time &lt;span class="math"&gt;\(t\)&lt;/span&gt;.&lt;/p&gt;
&lt;h3&gt;Multiclass Logistic Regression Classifier&lt;sup id="fnref:1"&gt;&lt;a class="footnote-ref" href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/h3&gt;
&lt;p&gt;When it is generalized to multiclass case, the logistic regression model needs to adapt accordingly. Now we have &lt;span class="math"&gt;\(K\)&lt;/span&gt; possible classes, that is, &lt;span class="math"&gt;\(y\in\{1,2,..,K\}\)&lt;/span&gt;. It is assumed that the posterior probability of class &lt;span class="math"&gt;\(y=k\)&lt;/span&gt; given &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt; follows
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\ln{p(y=k|\textbf{x})}\propto\textbf{w}_k^T\textbf{x},
\end{equation}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(\textbf{w}_k\)&lt;/span&gt; is a column weighting vector corresponding to class &lt;span class="math"&gt;\(k\)&lt;/span&gt;. Considering all classes &lt;span class="math"&gt;\(k=1,2,...,K\)&lt;/span&gt;, we would have a weighting matrix that includes all &lt;span class="math"&gt;\(K\)&lt;/span&gt; weighting vectors. That is, &lt;span class="math"&gt;\(\textbf{W}=[\textbf{w}_1,\textbf{w}_2,...,\textbf{w}_K]\)&lt;/span&gt;.
Under the constraint
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}
\sum_{k=1}^K{p(y=k|\textbf{x})}=1,
\end{equation}&lt;/div&gt;
&lt;p&gt;
it then follows that
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation} \label{Eqn:Prob_Multiple}
p(y=k|\textbf{x})=\frac{\exp(\textbf{w}_k^T\textbf{x})}{\sum_{j=1}^K{\exp(\textbf{w}_j^T\textbf{x})}}.
\end{equation}&lt;/div&gt;
&lt;p&gt;The weighting matrix, &lt;span class="math"&gt;\(\textbf{W}\)&lt;/span&gt;, can be similarly learned by maximum likelihood estimation (MLE). More specifically, given training data set &lt;span class="math"&gt;\(\mathcal{D}=\{(\textbf{x}_1,y_1),(\textbf{x}_2,y_2),...(\textbf{x}_N,y_N)\}\)&lt;/span&gt;,
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
\textbf{W}^*&amp;amp;=\max_{\textbf{W}}{\mathcal{L}(\textbf{W})}\\
&amp;amp;=\max_{\textbf{W}}{\sum_{i=1}^N\ln{{p(y_i|\textbf{x}_i)}}}\\
&amp;amp;=\max_{\textbf{W}}{\sum_{i=1}^N{\ln{\frac{\exp(\textbf{w}_{y_i}^T\textbf{x})}{\sum_{j=1}^K{\exp(\textbf{w}_j^T\textbf{x})}}}}}.
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;
The gradient of the objective function with respect to each &lt;span class="math"&gt;\(\textbf{w}_k\)&lt;/span&gt; can be calculated as
&lt;/p&gt;
&lt;div class="math"&gt;\begin{align}
\begin{aligned}
\frac{\partial{\mathcal{L}(\textbf{W})}}{\partial{\textbf{w}_k}}&amp;amp;=\sum_{i=1}^N{\textbf{x}_i\left(I(y_i=k)-\frac{\exp(\textbf{w}_k^T\textbf{x})}{\sum_{j=1}^K{\exp(\textbf{w}_j^T\textbf{x})}}\right)}\\
&amp;amp;=\sum_{i=1}^N{\textbf{x}_i(I(y_i=k)-p(y_i=k|\textbf{x}_i))},
\end{aligned}
\end{align}&lt;/div&gt;
&lt;p&gt;
where &lt;span class="math"&gt;\(I(\cdot)\)&lt;/span&gt; is a binary indicator function. Applying gradient descent, the optimal solution can be obtained by iterating as follows:
&lt;/p&gt;
&lt;div class="math"&gt;\begin{equation}\label{Eqn:Iteration_Multiple}
\textbf{w}_{k,t+1}=\textbf{w}_{k,t}+\eta_{t}\frac{\partial{\mathcal{L}(\textbf{W})}}{\partial{\textbf{w}_k}}.
\end{equation}&lt;/div&gt;
&lt;p&gt;
Note that we have "&lt;span class="math"&gt;\(+\)&lt;/span&gt;" in (\ref{Eqn:Iteration_Multiple}) instead of "&lt;span class="math"&gt;\(-\)&lt;/span&gt;" in (\ref{Eqn:Iteration_Binary}), because the maximum likelihood estimation in the binary case is eventually converted to a minimization problem, while here we keep performing maximization.&lt;/p&gt;
&lt;h3&gt;How to Perform Predictions?&lt;/h3&gt;
&lt;p&gt;Once the optimal weights are learned from the logistic regression model, for any new feature vector &lt;span class="math"&gt;\(\textbf{x}\)&lt;/span&gt;, we can easily calculate the probability that it is associated to each class label &lt;span class="math"&gt;\(k\)&lt;/span&gt; by (\ref{Eqn:Prob_Binary}) in the binary case or (\ref{Eqn:Prob_Multiple}) in the multiclass case. With the probabilities for each class label available, we can then perform:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a hard decision by identifying the class label with the highest probability, or&lt;/li&gt;
&lt;li&gt;a soft decision by showing the top &lt;span class="math"&gt;\(k\)&lt;/span&gt; most probable class labels with their corresponding probabilities.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;An Example Applying Multiclass Logistic Regression&lt;/h3&gt;
&lt;p&gt;To see an example applying multiclass logistic regression classification, &lt;a href="https://github.com/stlong0521/logistic-classification"&gt;click here&lt;/a&gt; for more information.&lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;div class="footnote"&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id="fn:1"&gt;
&lt;p&gt;C. M. Bishop, &lt;em&gt;Pattern Recognition and Machine Learning&lt;/em&gt;. New York: Springer, 2006.&amp;#160;&lt;a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;script type="text/javascript"&gt;if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
    var align = "center",
        indent = "0em",
        linebreak = "false";

    if (false) {
        align = (screen.width &lt; 768) ? "left" : align;
        indent = (screen.width &lt; 768) ? "0em" : indent;
        linebreak = (screen.width &lt; 768) ? 'true' : linebreak;
    }

    var mathjaxscript = document.createElement('script');
    var location_protocol = (false) ? 'https' : document.location.protocol;
    if (location_protocol !== 'http' &amp;&amp; location_protocol !== 'https') location_protocol = 'https:';
    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
    mathjaxscript.type = 'text/javascript';
    mathjaxscript.src = location_protocol + '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
    mathjaxscript[(window.opera ? "innerHTML" : "text")] =
        "MathJax.Hub.Config({" +
        "    config: ['MMLorHTML.js']," +
        "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' }, Macros: {} }," +
        "    jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
        "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
        "    displayAlign: '"+ align +"'," +
        "    displayIndent: '"+ indent +"'," +
        "    showMathMenu: true," +
        "    messageStyle: 'normal'," +
        "    tex2jax: { " +
        "        inlineMath: [ ['\\\\(','\\\\)'] ], " +
        "        displayMath: [ ['$$','$$'] ]," +
        "        processEscapes: true," +
        "        preview: 'TeX'," +
        "    }, " +
        "    'HTML-CSS': { " +
        "        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
        "        linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
        "    }, " +
        "}); " +
        "if ('default' !== 'default') {" +
            "MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
            "MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
                "var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
                "VARIANT['normal'].fonts.unshift('MathJax_default');" +
                "VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
                "VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
                "VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
            "});" +
        "}";
    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
&lt;/script&gt;</summary><category term="Machine Learning"></category><category term="Data Mining"></category></entry></feed>