国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

用Python給文本創(chuàng)立向量空間模型的教程

2020-02-23 00:49:45
字體:
來源:轉載
供稿:網(wǎng)友

我們需要開始思考如何將文本集合轉化為可量化的東西。最簡單的方法是考慮詞頻。

我將盡量嘗試不使用NLTK和Scikits-Learn包。我們首先使用Python講解一些基本概念。

基本詞頻

首先,我們回顧一下如何得到每篇文檔中的詞的個數(shù):一個詞頻向量。
 

#examples taken from here: http://stackoverflow.com/a/1750187 mydoclist = ['Julie loves me more than Linda loves me','Jane likes me more than Julie loves me','He likes basketball more than baseball'] #mydoclist = ['sun sky bright', 'sun sun bright'] from collections import Counter for doc in mydoclist:  tf = Counter()  for word in doc.split():    tf[word] +=1  print tf.items()[('me', 2), ('Julie', 1), ('loves', 2), ('Linda', 1), ('than', 1), ('more', 1)][('me', 2), ('Julie', 1), ('likes', 1), ('loves', 1), ('Jane', 1), ('than', 1), ('more', 1)][('basketball', 1), ('baseball', 1), ('likes', 1), ('He', 1), ('than', 1), ('more', 1)]

這里我們引入了一個新的Python對象,被稱作為Counter。該對象只在Python2.7及更高的版本中有效。Counters非常的靈活,利用它們你可以完成這樣的功能:在一個循環(huán)中進行計數(shù)。

根據(jù)每篇文檔中詞的個數(shù),我們進行了文檔量化的第一個嘗試。但對于那些已經(jīng)學過向量空間模型中“向量”概念的人來說,第一次嘗試量化的結果不能進行比較。這是因為它們不在同一詞匯空間中。

我們真正想要的是,每一篇文件的量化結果都有相同的長度,而這里的長度是由我們語料庫的詞匯總量決定的。
 

import string #allows for format()   def build_lexicon(corpus):  lexicon = set()  for doc in corpus:    lexicon.update([word for word in doc.split()])  return lexicon def tf(term, document): return freq(term, document) def freq(term, document): return document.split().count(term) vocabulary = build_lexicon(mydoclist) doc_term_matrix = []print 'Our vocabulary vector is [' + ', '.join(list(vocabulary)) + ']'for doc in mydoclist:  print 'The doc is "' + doc + '"'  tf_vector = [tf(word, doc) for word in vocabulary]  tf_vector_string = ', '.join(format(freq, 'd') for freq in tf_vector)  print 'The tf vector for Document %d is [%s]' % ((mydoclist.index(doc)+1), tf_vector_string)  doc_term_matrix.append(tf_vector)     # here's a test: why did I wrap mydoclist.index(doc)+1 in parens? it returns an int...  # try it! type(mydoclist.index(doc) + 1) print 'All combined, here is our master document term matrix: 'print doc_term_matrix

我們的詞向量為[me, basketball, Julie, baseball, likes, loves, Jane, Linda, He, than, more]

文檔”Julie loves me more than Linda loves me”的詞頻向量為:[2, 0, 1, 0, 0, 2, 0, 1, 0, 1, 1]

文檔”Jane likes me more than Julie loves me”的詞頻向量為:[2, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1]

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 弥渡县| 盱眙县| 莲花县| 吴堡县| 平陆县| 昌黎县| 秦皇岛市| 永嘉县| 阿合奇县| 象山县| 吴忠市| SHOW| 康乐县| 泸定县| 安龙县| 福贡县| 河源市| 兴化市| 读书| 牙克石市| 唐海县| 南和县| 云和县| 蓬安县| 包头市| 新余市| 台中市| 鹿泉市| 阜城县| 兴隆县| 名山县| 即墨市| 保康县| 洛阳市| 昔阳县| 舒城县| 耒阳市| 凤冈县| 孙吴县| 鹿邑县| 兴山县|