2012年9月24日星期一

smart way to add glossary in latex

In latex, glossary could be formatted by table. Here is a simple example. It is quite easy to extend with more items.

\renewcommand\arraystretch{1.5}

\newcommand{\myitem}[2] { \textbf{#1} & #2 \\}

\begin{table}[htbp]
    \begin{tabular}{ll}
          \myitem{SVM}{Support Vector Machine}
    \end{tabular}%
  \label{tab:Glossary}%
\end{table}%


Read more!

2012年8月1日星期三

贝叶斯估计浅析

贝叶斯方法有着非常广泛的应用,但是初学者容易被里面的概率公式的给吓到,以至于望而却步。所以有大师专门写个tutorial,命名为“bayesian inference with tears”。 我本人也深受其苦,多次尝试学习而不得其门而入。终于有一天,一种醍醐灌顶的感觉在脑海中出现,思路一下子清晰了,原来bayes估计竟然是这么一回事。本blog只是为了让还处在痛苦的学习过程中的人能够快速把握概念,理清思路,高手请绕道而行 :)

贝叶斯估计要解决的是概率估计问题,也就是说,已知一些样本,他们满足某种分布,需要估计这种分布的参数或者新数据出现的概率。说到概率估计,就不能不先说说最大似然方法。最大似然是一种最基本的参数估计方法,相信学过概率的人都应该知道。最大似然就是寻找最可能的参数,使得这些采样样本出现的概率最大。举个简单的例子吧。假设一个盒子的高度h满足正态分布$N(h,1)$, 三次测量结果分别为 X={11,10.5,11.5} cm, 根据最大似然方法:

$P(X|h) = \prod_{i=1}^{N}{p(x_i|h)} = \prod_{i=1}^{N}{\frac{1}{2\pi}exp{\{-\frac{(x_i-h)^2}{\sigma^2}\}}$

$h=arg \max_h{P(X|h)} = arg \max_h{log P(X|h)}$
 $ = arg \max_h{exp{\{\sum_{i=1}^{N}{(x_i-h)^2}}\}}$

通过简单计算,可以得到h = 11cm,对新的测量的数据的可能出现概率,则由 $N(11,1)$给出。

最大似然估计是在对被估计量没有任何先验知识的前提下求得的。如果已知被估计参数满足某种分布,则需要用到最大后验估计。比如,在前面提到的例子中,假设h服从正态分布$N(10.5,1)$,要估计h的值,根据贝叶斯理论

$P(h|X) = \frac{P(X|h)P(h)}{P(X)}$
这里$P(X)$ 和我们要估计的参数无关,所以

$h=arg \max_h{P(X|h)} = arg \max_h{P(X|h)P(h)} $

  $= arg \max_h{exp{\{\sum_{i=1}^{N}{(x_i-h)^2}+(h-10.5)^2}}\}}$

通过简单计算,可以得到 h= 10.875cm。根据MAP的结果,对新的测量的数据的可能出现概率,则由 $N(10.875,1)$给出。

贝叶斯估计其实要解决的不是如何去估计参数,而是如何估计新的测量数据的出现的概率的,但其过程并不需要要计算参数h,而是通过对h的积分得出:

$P(x|h) = \int_{h~N(10.5,1)}{p(h|X)p(x|h)}dh$

这个有点想求函数的数学期望。在实际应用中,为了便于计算,一般根据似然函数,对先验概率进行假设,从而使得先验分布和后验概率有相同的表达形式,这就涉及到共轭先验的概念。如果先验概率和似然函数的关系能够使得先验和后验概率有相同的函数形式,则可认为先验概率是似然函数的共轭先验。共轭先验在贝叶斯推理中有非常广泛的应用,很多问题都是通过共轭先验求解的。



Read more!

2012年7月31日星期二

pLSA 浅析

刚读博的时候,就读到过pLSA的文章,当时对里面的概率,分布什么的,一头雾水。三年过去了,整理以往paper又发现当初打印的文章,竟然一下子看懂了。特意整理下,希望为以后看到这个东西的人,有点参考的作用。

PLSA是个从文档中发现topic的算法,它认为文本可以分三个层次来理解。1,文档(d);2,主题(z);3,单词(w),既一个文档包含若干主题,每个主题包含若干单词。从概率层面来讲,这里的包含其实是某种分布。也就是说,一个文档可以看做在一些主题上面的分布(P(z|d),而每个主题看做在单词上面的某种分布(P(w|z))。 pLSA就是对这些分布进行建模。


相信大部分人都可能理解之前的这些内容,关键难点在于求解。其实呢,一切古典概率都是纸老虎,概率,在文本处理里面,本质就是词频。
pLSA模型的目标函数就是使得所有文档单词组合的似然函数最大:

这里就是单词w_i在文档d_j中出现的次数。
问题的解可以用EM算法实现。
首先,对变量初始化。
在E step里面,计算

这里就是求一个文档中的某个单词在某主题下面的分布,一个简单的概率计算,下标省略,注意一致。
在M step,计算

这里求得是在所有文档中一个单词在某个主题下面的概率。
另外一个更新是

这里求的是某文档在主题上面的分布。

关于示例代码,网上很多,比如

#!/usr/bin/env python
from random import random
from math import log, exp

def normalize(P):
    return [p / sum(P) for p in P]

# test data
D = [[2,10,0],[1,5,0],[0,0,8],[0,1,9]]
N = len(D)
W = len(D[0])
print 'D = ', D

#initialize
K = 5
Q = [normalize([random() for n in range(N)]) for k in range(K)]
R = [normalize([random() for w in range(W)]) for k in range(K)]
P = normalize([random() for k in range(K)])

print 'Q = ', Q
print 'R = ', R

#iteration
for loop in range(10):
    # e-step
    C = [[normalize([Q[k][w] * R[k][w] * P[k] for k in range(K)]) for w in range(W)] for n in range(N)]

    # m-step
    for k in range(K):
        Q[k] = normalize([sum([C[n][w][k] * D[n][w] for w in range(W)]) for n in range(N)])
        R[k] = normalize([sum([C[n][w][k] * D[n][w] for n in range(N)]) for w in range(W)])
    P = normalize([sum(D[n][w] * C[n][w][k] for w in range(W) for n in range(N)) for k in range(K)])

    # log likelihood
    L = sum(D[n][w] * log(sum(Q[k][n] * R[k][w] for k in range(K))) for n in range(N) for w in range(W))
    print 'L = ', L


Read more!

2012年6月5日星期二

google Image search API

A python client to query image from google. Though the api service has been tagged as (Deprecated), it will work before a new version is released.


'''
Loosely based on Mike Verdone's excellent twitter library:
http://github.com/sixohsix/twitter/


'''

from exceptions import Exception
from urllib import urlencode
import urllib2

try:
    import json
except ImportError:
    import simplejson as json


class GoogleError(Exception):
    """
    Exception thrown by the search object when there is an
    error interacting with google.com.
    """
    pass

class GoogleImageSearch(object):
    def __init__(self, endpoint, user_agent= None, cache=None):
        self.endpoint = endpoint
        self.cache = cache
        self.user_agent = user_agent

    def __call__(self, **params):
        params['v']='1.0'
        kwargs = dict(params)
        kwargs = urlencode(kwargs)

            # HTTP GET
        req = urllib2.Request('%s?%s' % (self.endpoint, kwargs))
        print req.get_full_url()
        cache_response = True

        if self.user_agent:
            req.add_header('User-Agent', self.user_agent)
        
        try:
            handle = urllib2.urlopen(req)
            response = handle.read()
            if cache_response and self.cache != None:
                self.cache.set('googleimagesearch-' + kwargs, response, time=int(time() + 60))
            response = json.loads(response)
            return response
        except urllib2.HTTPError, e:
            raise GoogleError('google imagesearch sent status %i for method: %s\ndetails: %s' % (e.code, e.fp.read()))

class GoogleImage(GoogleImageSearch):
    def __init__(self, endpoint='https://ajax.googleapis.com/ajax/services/search/images', user_agent='python-googleimage/0.1',  cache=None):
        GoogleImageSearch.__init__(self, endpoint=endpoint, user_agent=user_agent,  cache=cache)


if __name__ == '__main__':
    googleimage =  GoogleImage()
    query = {'q':'EURECOM'}
    print googleimage(**query)


Read more!

2012年5月4日星期五

google release its input tools

It is a real good news, the google official cloud Input editor(chrome) is available online

https://chrome.google.com/webstore/detail/mclkkofklkfljcocdinagocijmpgbhab



Read more!