99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀用Python給文本創(chuàng)立向量空間模型的教程
用Python給文本創(chuàng)立向量空間模型的教程
2017-08-15
收藏

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

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

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

基本詞頻

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

#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)]

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

根據(jù)每篇文檔中詞的個(gè)數(shù),我們進(jìn)行了文檔量化的第一個(gè)嘗試。但對(duì)于那些已經(jīng)學(xué)過(guò)向量空間模型中“向量”概念的人來(lái)說(shuō),第一次嘗試量化的結(jié)果不能進(jìn)行比較。這是因?yàn)樗鼈儾辉谕辉~匯空間中。

我們真正想要的是,每一篇文件的量化結(jié)果都有相同的長(zhǎng)度,而這里的長(zhǎng)度是由我們語(yǔ)料庫(kù)的詞匯總量決定的。

importstring#allows for format()
    
defbuild_lexicon(corpus):
  lexicon=set()
  fordocincorpus:
    lexicon.update([wordforwordindoc.split()])
  returnlexicon
  
deftf(term, document):
 returnfreq(term, document)
  
deffreq(term, document):
 returndocument.split().count(term)
  
vocabulary=build_lexicon(mydoclist)
  
doc_term_matrix=[]
print'Our vocabulary vector is ['+', '.join(list(vocabulary))+']'
fordocinmydoclist:
  print'The doc is "'+doc+'"'
  tf_vector=[tf(word, doc)forwordinvocabulary]
  tf_vector_string=', '.join(format(freq,'d')forfreqintf_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: '
printdoc_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]

文檔”He likes basketball more than baseball”的詞頻向量為:[0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1]

合在一起,就是我們主文檔的詞矩陣:

[[2, 0, 1, 0, 0, 2, 0, 1, 0, 1, 1], [2, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1]]

好吧,這看起來(lái)似乎很合理。如果你有任何機(jī)器學(xué)習(xí)的經(jīng)驗(yàn),你剛剛看到的是建立一個(gè)特征空間?,F(xiàn)在每篇文檔都在相同的特征空間中,這意味著我們可以在同樣維數(shù)的空間中表示整個(gè)語(yǔ)料庫(kù),而不會(huì)丟失太多信息。

標(biāo)準(zhǔn)化向量,使其L2范數(shù)為1

一旦你在同一個(gè)特征空間中得到了數(shù)據(jù),你就可以開始應(yīng)用一些機(jī)器學(xué)習(xí)方法:分類、聚類等等。但實(shí)際上,我們同樣遇到一些問(wèn)題。單詞并不都包含相同的信息。

如果有些單詞在一個(gè)單一的文件中過(guò)于頻繁地出現(xiàn),它們將擾亂我們的分析。我們想要對(duì)每一個(gè)詞頻向量進(jìn)行比例縮放,使其變得更具有代表性。換句話說(shuō),我們需要進(jìn)行向量標(biāo)準(zhǔn)化。

我們真的沒有時(shí)間過(guò)多地討論關(guān)于這方面的數(shù)學(xué)知識(shí)?,F(xiàn)在僅僅接受這樣一個(gè)事實(shí):我們需要確保每個(gè)向量的L2范數(shù)等于1。這里有一些代碼,展示這是如何實(shí)現(xiàn)的。



importmath
  
defl2_normalizer(vec):
  denom=np.sum([el**2forelinvec])
  return[(el/math.sqrt(denom))forelinvec]
  
doc_term_matrix_l2=[]
forvecindoc_term_matrix:
  doc_term_matrix_l2.append(l2_normalizer(vec))
  
print'A regular old document term matrix: '
printnp.matrix(doc_term_matrix)
print'\nA document term matrix with row-wise L2 norms of 1:'
printnp.matrix(doc_term_matrix_l2)
  
# if you want to check this math, perform the following:
# from numpy import linalg as la
# la.norm(doc_term_matrix[0])
# la.norm(doc_term_matrix_l2[0])

格式化后的舊的文檔詞矩陣:



[[20100201011]
[20101110011]
[01011000111]]

按行計(jì)算的L2范數(shù)為1的文檔詞矩陣:


[[0.577350270.0.288675130.0.0.57735027
0.0.288675130.0.288675130.28867513]
[0.632455530.0.316227770.0.316227770.31622777
0.316227770.0.0.316227770.31622777]
[0.0.408248290.0.408248290.408248290.0.
0.0.408248290.408248290.40824829]]

還不錯(cuò),沒有太深究線性代數(shù)的知識(shí),你就可以馬上看到我們按比例縮小了各個(gè)向量,使它們的每一個(gè)元素都在0到1之間,并且不會(huì)丟失太多有價(jià)值的信息。你看到了,一個(gè)計(jì)數(shù)為1的詞在一個(gè)向量中的值和其在另一個(gè)向量中的值不再相同。

為什么我們關(guān)心這種標(biāo)準(zhǔn)化嗎?考慮這種情況,如果你想讓一個(gè)文檔看起來(lái)比它實(shí)際上和一個(gè)特定主題更相關(guān),你可能會(huì)通過(guò)不斷重復(fù)同一個(gè)詞,來(lái)增加它包含到一個(gè)主題的可能性。坦率地說(shuō),在某種程度上,我們得到了一個(gè)在該詞的信息價(jià)值上衰減的結(jié)果。所以我們需要按比例縮小那些在一篇文檔中頻繁出現(xiàn)的單詞的值。

IDF頻率加權(quán)

我們現(xiàn)在還沒有得到想要的結(jié)果。就像一篇文檔中的所有單詞不具有相同的價(jià)值一樣,也不是全部文檔中的所有單詞都有價(jià)值。我們嘗試?yán)梅次臋n詞頻(IDF)調(diào)整每一個(gè)單詞權(quán)重。我們看看這包含了些什么:



defnumDocsContaining(word, doclist):
doccount=0
fordocindoclist:
iffreq(word, doc) >0:
doccount+=1
returndoccount
defidf(word, doclist):
n_samples=len(doclist)
df=numDocsContaining(word, doclist)
returnnp.log(n_samples/1+df)
my_idf_vector=[idf(word, mydoclist)forwordinvocabulary]
print'Our vocabulary vector is ['+', '.join(list(vocabulary))+']'

print'The inverse document frequency vector is ['+', '.join(format(freq,'f')f



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

反文檔詞頻向量為[1.609438, 1.386294, 1.609438, 1.386294, 1.609438, 1.609438, 1.386294, 1.386294, 1.386294, 1.791759, 1.791759]

現(xiàn)在,對(duì)于詞匯中的每一個(gè)詞,我們都有一個(gè)常規(guī)意義上的信息值,用于解釋他們?cè)谡麄€(gè)語(yǔ)料庫(kù)中的相對(duì)頻率?;叵胍幌?,這個(gè)信息值是一個(gè)“逆”!即信息值越小的詞,它在語(yǔ)料庫(kù)中出現(xiàn)的越頻繁。

我們快得到想要的結(jié)果了。為了得到TF-IDF加權(quán)詞向量,你必須做一個(gè)簡(jiǎn)單的計(jì)算:tf * idf。

現(xiàn)在讓我們退一步想想。回想下線性代數(shù):如果你用一個(gè)AxB的向量乘以另一個(gè)AxB的向量,你將得到一個(gè)大小為AxA的向量,或者一個(gè)標(biāo)量。我們不會(huì)那么做,因?yàn)槲覀兿胍氖且粋€(gè)具有相同維度(1 x詞數(shù)量)的詞向量,向量中的每個(gè)元素都已經(jīng)被自己的idf權(quán)重加權(quán)了。我們?nèi)绾卧赑ython中實(shí)現(xiàn)這樣的計(jì)算呢?

在這里我們可以編寫完整的函數(shù),但我們不那么做,我們將要對(duì)numpy做一個(gè)簡(jiǎn)介。
 

importnumpy as np
  
defbuild_idf_matrix(idf_vector):
  idf_mat=np.zeros((len(idf_vector),len(idf_vector)))
  np.fill_diagonal(idf_mat, idf_vector)
  returnidf_mat
  
my_idf_matrix=build_idf_matrix(my_idf_vector)
  
#print my_idf_matrix

太棒了!現(xiàn)在我們已經(jīng)將IDF向量轉(zhuǎn)化為BxB的矩陣了,矩陣的對(duì)角線就是IDF向量。這意味著我們現(xiàn)在可以用反文檔詞頻矩陣乘以每一個(gè)詞頻向量了。接著,為了確保我們也考慮那些過(guò)于頻繁地出現(xiàn)在文檔中的詞,我們將對(duì)每篇文檔的向量進(jìn)行標(biāo)準(zhǔn)化,使其L2范數(shù)等于1。

doc_term_matrix_tfidf=[]
  
#performing tf-idf matrix multiplication
fortf_vectorindoc_term_matrix:
  doc_term_matrix_tfidf.append(np.dot(tf_vector, my_idf_matrix))
  
#normalizing
doc_term_matrix_tfidf_l2=[]
fortf_vectorindoc_term_matrix_tfidf:
  doc_term_matrix_tfidf_l2.append(l2_normalizer(tf_vector))
                    
printvocabulary
printnp.matrix(doc_term_matrix_tfidf_l2)# np.matrix() just to make it easier to look at
 
set(['me','basketball','Julie','baseball','likes','loves','Jane','Linda','He','than','more'])
 
[[0.572112570.0.286056280.0.0.57211257
0.0.246395470.0.318461530.31846153]
[0.625589020.0.312794510.0.312794510.31279451
0.269426530.0.0.348228730.34822873]
[0.0.360636120.0.360636120.418685570.0.
0.0.360636120.466115420.46611542]]

太棒了!你剛看到了一個(gè)展示如何繁瑣地建立一個(gè)TF-IDF加權(quán)的文檔詞矩陣的例子。

最好的部分來(lái)了:你甚至不需要手動(dòng)計(jì)算上述變量,使用scikit-learn即可。

記住,Python中的一切都是一個(gè)對(duì)象,對(duì)象本身占用內(nèi)存,同時(shí)對(duì)象執(zhí)行操作占用時(shí)間。使用scikit-learn包,以確保你不必?fù)?dān)心前面所有步驟的效率問(wèn)題。

注意:你從TfidfVectorizer/TfidfTransformer得到的值將和我們手動(dòng)計(jì)算的值不同。這是因?yàn)閟cikit-learn使用一個(gè)Tfidf的改進(jìn)版本處理除零的錯(cuò)誤。這里有一個(gè)更深入的討論。

fromsklearn.feature_extraction.textimportCountVectorizer
  
count_vectorizer=CountVectorizer(min_df=1)
term_freq_matrix=count_vectorizer.fit_transform(mydoclist)
print"Vocabulary:", count_vectorizer.vocabulary_
  
fromsklearn.feature_extraction.textimportTfidfTransformer
  
tfidf=TfidfTransformer(norm="l2")
tfidf.fit(term_freq_matrix)
  
tf_idf_matrix=tfidf.transform(term_freq_matrix)
printtf_idf_matrix.todense()
 
Vocabulary: {u'me':8, u'basketball':1, u'julie':4, u'baseball':0, u'likes':5, u'loves':7, u'jane':3, u'linda':6, u'more':9, u'than':10, u'he':2}
[[0.0.0.0.0.289459060.
0.380603870.578918110.578918110.224790780.22479078]
[0.0.0.0.417157590.31725910.3172591
0.0.31725910.63451820.246379990.24637999]
[0.483591210.483591210.483591210.0.0.36778358
0.0.0.0.285616760.28561676]]

實(shí)際上,你可以用一個(gè)函數(shù)完成所有的步驟:TfidfVectorizer


from sklearn.feature_extraction.text import TfidfVectorizer
 
tfidf_vectorizer = TfidfVectorizer(min_df = 1)
tfidf_matrix = tfidf_vectorizer.fit_transform(mydoclist)
 
print tfidf_matrix.todense()
    
[[ 0. 0. 0. 0. 0.28945906 0.
0.38060387 0.57891811 0.57891811 0.22479078 0.22479078]
[ 0. 0. 0. 0.41715759 0.3172591 0.3172591
0. 0.3172591 0.6345182 0.24637999 0.24637999]
[ 0.48359121 0.48359121 0.48359121 0. 0. 0.36778358
0. 0. 0. 0.28561676 0.28561676]]

并且我們可以利用這個(gè)詞匯空間處理新的觀測(cè)文檔,就像這樣:

new_docs = ['He watches basketball and baseball', 'Julie likes to play basketball', 'Jane loves to play baseball']
new_term_freq_matrix = tfidf_vectorizer.transform(new_docs)
print tfidf_vectorizer.vocabulary_
print new_term_freq_matrix.todense()

{u'me': 8, u'basketball': 1, u'julie': 4, u'baseball': 0, u'likes': 5, u'loves': 7, u'jane': 3, u'linda': 6, u'more': 9, u'than': 10, u'he': 2}
[[ 0.57735027 0.57735027 0.57735027 0. 0. 0. 0.
0. 0. 0. 0. ]
[ 0. 0.68091856 0. 0. 0.51785612 0.51785612
0. 0. 0. 0. 0. ]
[ 0.62276601 0. 0. 0.62276601 0. 0. 0.
0.4736296 0. 0. 0. ]]

請(qǐng)注意,在new_term_freq_matrix中并沒有“watches”這樣的單詞。這是因?yàn)槲覀冇糜谟?xùn)練的文檔是mydoclist中的文檔,這個(gè)詞并不會(huì)出現(xiàn)在那個(gè)語(yǔ)料庫(kù)的詞匯中。換句話說(shuō),它在我們的詞匯詞典之外。

回到Amazon評(píng)論文本

練習(xí)2

現(xiàn)在是時(shí)候嘗試使用你學(xué)過(guò)的東西了。利用TfidfVectorizer,你可以在Amazon評(píng)論文本的字符串列表上嘗試建立一個(gè)TF-IDF加權(quán)文檔詞矩。

importos
importcsv
  
#os.chdir('/Users/rweiss/Dropbox/presentations/IRiSS2013/text1/fileformats/')
  
withopen('amazon/sociology_2010.csv','rb') as csvfile:
  amazon_reader=csv.DictReader(csvfile, delimiter=',')
  amazon_reviews=[row['review_text']forrowinamazon_reader]
  
  #your code here!!!



數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }