潜在语义分析Latent semantic analysis note(LSA)原理及代码实现

文章参考:http://blog.sina.com.cn/s/blog_62a9902f0101cjl3.html

 

Latent Semantic Analysis (LSA)也被叫做Latent Semantic Indexing(LSI),从字面上的意思理解就是通过分析文档去发现这些文档中潜在的意思和概念。假设每个词仅表示一个概念,并且每个概念仅仅被一个 词所描述,LSA将非常简单从词到概念存在一个简单的映射关系)

 

不幸的是,这个问题并没有如此简单,因为存在不同的词表示同一个意思(同义词),一个词表示多个意思,所有这种二义性(多义性)都会混淆概念以至于有时就算是人也很难理解。

 

例如,银行这个词和抵押、贷款、利率一起出现时往往表示金融机构。但是,和鱼饵,投掷、鱼一起出现时往往表示河岸。

 

潜语义分析工作原理

 

潜语义分析(Latent SemanticAnalysis)源自问题:如何从搜索query中找到相关的文档。当我们试图通过比较词来找到相关的文本时,存在着难以解决的局限 性,那就是在搜索中我们实际想要去比较的不是词,而是隐藏在词之后的意义和概念。潜语义分析试图去解决这个问题,它把词和文档都映射到一个‘概念’空间并 在这个空间内进行比较(注:也就是一种降维技术)。

 

当文档的作者写作的时候,对于词语有着非常宽泛的选择。不同的作者对于词语的选择有着不同的偏好,这样会导致概念的混淆。这种对于词语的随机选择在 词-概念 的关系中引入了噪音。LSA滤除了这样的一些噪音,并且还能够从全部的文档中找到最小的概念集合(为什么是最小?)。

 

为了让这个难题更好解决,LSA引入一些重要的简化:

 

1. 文档被表示为”一堆词(bags of words)”,因此词在文档中出现的位置并不重要,只有一个词的出现次数。

 

2.概念被表示成经常出现在一起的一些词的某种模式。例如“leash”(栓狗的皮带)、“treat”、“obey”(服从)经常出现在关于训练狗的文档中。

 

3.词被认为只有一个意思。这个显然会有反例(bank表示河岸或者金融机构),但是这可以使得问题变得更加容易。(这个简化会有怎样的缺陷呢?)

 

接下来看一个LSA的小例子,Next Part:

一个简单的小例子

一个小例子,我在amazon.com上搜索”investing”(投资) 并且取top10搜索结果的书名。其中一个被废弃了,因为它只含有一个索引词(indexword)和其它标题相同。索引词可以是任何满足下列条件的词:

 

1. 在2个或者2个以上标题中出现 并且

 

2. 不是那种特别常见的词例如 “and”, ”the” 这种(停用词-stopword)。这种词没有包含进来是因为他们本身不存在什么意义。

 

在这个例子中,我们拿掉了如下停用词:“and”, “edition”, “for”, “in”,“little”, “of”, “the”, “to”.

 

下面就是那9个标题,索引词(在2个或2个以上标题出现过的非停用词)被下划线标注:

 

1. The Neatest Little Guide toStock Market Investing

 

2. Investing For Dummies, 4th Edition

 

3. The Little Book of Common SenseInvesting: The OnlyWay to Guarantee Your Fair Share ofStock Market Returns

 

4. The Little Book ofValue Investing

 

5. ValueInvesting: From Graham to Buffett and Beyond

 

6. RichDad's Guide toInvesting: What theRich Invest in,That the Poor and the Middle Class Do Not!

 

7. Investing in Real Estate, 5th Edition

 

8. StockInvesting ForDummies

 

9. RichDad's Advisors: The ABC's ofReal Estate Investing: TheSecrets of Finding Hidden Profits Most Investors Miss

在这个例子里面应用了LSA,我们可以在XY轴的图中画出词和标题的位置(只有2维),并且识别出标题的聚类。蓝色圆圈表示9个标题,红色方块表示11个 索引词。我们不但能够画出标题的聚类,并且由于索引词可以被画在标题一起,我们还可以给这些聚类打标签。例如,蓝色的聚类,包含了T7和T9,是关于 realestate(房地产)的,绿色的聚类,包含了标题T2,T4,T5和T8,是讲valueinvesting(价值投资)的,最后是红色的聚 类,包含了标题T1和T3,是讲stockmarket(股票市场)的。标题T6是孤立点(outlier)

 

LSA的第一步是要去创建词到标题(文档)的矩阵。在这个矩阵里,每一个索引词占据了一行,每一个标题占据一列。每一个 单元(cell)包含了这个词出现在那个标题中的次数。例如,词”book”出现在T3中一次,出现在T4中一次,而”investing”在所有标题中 都出现了一次。一般来说,在LSA中的矩阵会非常大而且会非常稀疏(大部分的单元都是0)。这是因为每个标题或者文档一般只包含所有词汇的一小部分。更复 杂的LSA算法会利用这种稀疏性去改善空间和时间复杂度。

 

在这篇文章中,我们用python代码去实现LSA的所有步骤。我们将介绍所有的代码。Python代码可以在这里被下到(见上)。需要安装NumPy和 SciPy这两个库。

 

NumPy是python的数值计算类,用到了zeros(初始化矩阵),scipy.linalg这个线性代数的库中,我们引入了svd函数也就是做奇异值分解,LSA的核心。

 

  1. fromnumpy importzeros
  2. from scipy.linalgimport svd

Stopwords 是停用词 ignorechars是无用的标点

  1. titles =
  2. [
  3. "The Neatest Little Guide to Stock MarketInvesting",
  4. "Investing For Dummies, 4thEdition",
  5. "The Little Book of Common SenseInvesting: The Only Way to Guarantee Your Fair Share of StockMarket Returns",
  6. "The Little Book of ValueInvesting",
  7. "Value Investing: From Graham to Buffettand Beyond",
  8. "Rich Dad's Guide toInvesting: What the Rich Invest in, That the Poor and the MiddleClass Do Not!",
  9. "Investing in Real Estate, 5thEdition",
  10. "Stock Investing ForDummies",
  11. "Rich Dad's Advisors: The ABC's of RealEstate Investing: The Secrets of Finding Hidden Profits MostInvestors Miss"
  12. ]
  13. stopwords = ['and','edition','for','in','little','of','the','to']
  14. ignorechars = ''''',:'!'''

这里定义了一个LSA的类,包括其初始化过程wdict是词典,dcount用来记录文档号。

  1. classLSA(object):
  2. def__init__(self,stopwords, ignorechars):
  3. self.stopwords =stopwords
  4. self.ignorechars =ignorechars
  5. self.wdict ={}
  6. self.dcount =0

这个函数就是把文档拆成词并滤除停用词和标点,剩下的词会把其出现的文档号填入到wdict中去,例如,词book出现在标题3和4中,则我们有self.wdict['book']= [3, 4]。相当于建了一下倒排。

  1. defparse(self,doc):
  2. words = doc.split(); for w inwords:
  3. w = w.lower().translate(None, self.ignorechars)
  4. if win self.stopwords:
  5. continue
  6. elif win self.wdict:
  7. self.wdict[w].append(self.dcount)
  8. else:
  9. self.wdict[w] =[self.dcount]
  10. self.dcount+= 1

所有的文档被解析之后,所有出现的词(也就是词典的keys)被取出并且排序。建立一个矩阵,其行数是词的个数,列数是文档个数。最后,所有的词和文档对所对应的矩阵单元的值被统计出来。

  1. defbuild(self):
  2. self.keys =[k for kinself.wdict.keys()iflen(self.wdict[k]) >1]
  3. self.keys.sort()
  4. self.A =zeros([len(self.keys),self.dcount])
  5. for i, kin enumerate(self.keys):
  6. for din self.wdict[k]:
  7. self.A[i,d]+= 1

把矩阵打印出来并作图

def printA(self):
print self.A

 

#奇异值分解矩阵为u,s,vt
u,s,vt = svd(self.A)

print """\r"""
print u
print """\r"""
print s
print """\r"""
print vt
print """\r"""

 

 

 

#画图的标题和x轴和y轴的维度名称

 

plt.title("LSI")
plt.xlabel(u'dimention2')
plt.ylabel(u'dimention3')

 

 

 

#画文档标题
titles = ['T1','T2','T3','T4','T5','T6','T7','T8','T9']
vdemention2 = vt[1]
vdemention3 = vt[2]
for j in range(len(vdemention2)):
text(vdemention2[j],vdemention3[j],titles[j])
plot(vdemention2, vdemention3, '.')

 


#画词语
ut = u.T
demention2 = ut[1]
demention3 = ut[2]
for i in range(len(demention2)):
text(demention2[i],demention3[i],self.keys[i])
plot(demention2, demention3, '.')

 

程序入口:

 

mylsa = LSA(stopwords, ignorechars)

 

for t in titles:

 

mylsa.parse(t)

 

mylsa.build()

 

mylsa.printA()

 

代码使用winPython自带spyder运行,以下部分是源代码:

 

[python] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. # -*- coding: utf-8 -*-  
  2. """ 
  3. Created on Wed Jun 11 17:02:39 2014 
  4.  
  5. @author: modified by zhouxu,add plot 
  6. """  
  7.   
  8. from numpy import zeros  
  9. import numpy as np  
  10. from scipy.linalg import svd  
  11.   
  12. titles =[  
  13.     "The Neatest Little Guide to Stock Market Investing",  
  14.     "Investing For Dummies, 4th Edition",  
  15.     "The Little Book of Common Sense Investing: The Only Way to Guarantee Your Fair Share of Stock Market Returns",  
  16.     "The Little Book of Value Investing",  
  17.     "Value Investing: From Graham to Buffett and Beyond",  
  18.     "Rich Dad's Guide to Investing: What the Rich Invest in, That the Poor and the Middle Class Do Not!",  
  19.     "Investing in Real Estate, 5th Edition",  
  20.     "Stock Investing For Dummies",  
  21.     "Rich Dad's Advisors: The ABC's of Real Estate Investing: The Secrets of Finding Hidden Profits Most Investors Miss"  
  22. ]  
  23. stopwords = ['and','edition','for','in','little','of','the','to']  
  24. ignorechars = ''''''',:'!'''  
  25.   
  26.   
  27. class LSA(object):  
  28.     def __init__(self, stopwords, ignorechars):  
  29.         self.stopwords = stopwords  
  30.         self.ignorechars = ignorechars  
  31.         self.wdict = {}  
  32.         self.dcount = 0  
  33.   
  34.     def parse(self, doc):  
  35.         words = doc.split();   
  36.         for w in words:  
  37.             #print self.dcount  
  38.             w = w.lower().translate(Noneself.ignorechars)  
  39.             if w in self.stopwords:  
  40.                 continue  
  41.             elif w in self.wdict:  
  42.                 self.wdict[w].append(self.dcount)  
  43.             else:  
  44.                 self.wdict[w] = [self.dcount]  
  45.         self.dcount += 1  
  46.   
  47.     def build(self):  
  48.         self.keys = [k for k in self.wdict.keys() if len(self.wdict[k]) > 1]  
  49.         self.keys.sort()  
  50.         print self.keys  
  51.         self.A = zeros([len(self.keys), self.dcount])  
  52.         for i, k in enumerate(self.keys):  
  53.             for d in self.wdict[k]:  
  54.                 self.A[i,d] += 1  
  55.       
  56.       
  57.     def printA(self):  
  58.         print self.A  
  59.         u,s,vt = svd(self.A)  
  60.         print """\r"""          
  61.         print u  
  62.         print """\r"""  
  63.         print s  
  64.         print """\r"""          
  65.         print vt  
  66.         print """\r"""    
  67.           
  68.         plt.title("LSA")  
  69.         plt.xlabel(u'dimention2')  
  70.         plt.ylabel(u'dimention3')  
  71.   
  72.         titles = ['T1','T2','T3','T4','T5','T6','T7','T8','T9']  
  73.         vdemention2 = vt[1]  
  74.         vdemention3 = vt[2]  
  75.         for j in range(len(vdemention2)):  
  76.             text(vdemention2[j],vdemention3[j],titles[j])   
  77.         plot(vdemention2, vdemention3, '.')          
  78.           
  79.         ut = u.T  
  80.         demention2 = ut[1]  
  81.         demention3 = ut[2]  
  82.         for i in range(len(demention2)):  
  83.             text(demention2[i],demention3[i],self.keys[i])   
  84.         plot(demention2, demention3, '.')  
  85.           
  86.                   
  87. mylsa = LSA(stopwords, ignorechars)  
  88. for t in titles:  
  89.     mylsa.parse(t)  
  90. mylsa.build()  
  91. mylsa.printA()  

程序运行结果:

 

 

http://blog.csdn.net/bob007/article/details/30496559

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值