scikit-learn進行TFIDF處理


看到https://www.cnblogs.com/pinard/p/6693230.html的博客之后自己實踐了一下

第一種方法也就是CountVectorizer+TfidfTransformer的組合,代碼在下面

from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer

corpus = [
    'This is the first document.',
    'This is the second document.',
    'And the third one',
    'Is this the first document?',
    'I come to American to travel'
]

words = CountVectorizer.fit_transform(corpus)
tfidf = TfidfTransformer().fit_transform(words)

print (cv.get_feature_names())
print (words.toarray())
print (tfidf)

  

CountVectorizer()是一個類,包含了很多方法,比如要打印每個詞就用get_feature_names

之后用fit_transform()處理詞向量,可以打出矩陣,矩陣的每一行是每一個文本(在這里是句子)的詞頻統計,每列是什么詞如上圖

以下是TFIDF的結果:

(0, 10) 0.440270504199
(0, 5) 0.440270504199
(0, 8) 0.370369427837
(0, 4) 0.530388665338
(0, 3) 0.440270504199
(1, 10) 0.410399746731
(1, 5) 0.410399746731
(1, 8) 0.345241204967
(1, 3) 0.410399746731
(1, 7) 0.612800664198
(2, 8) 0.309317493592
(2, 1) 0.549036334
(2, 9) 0.549036334
(2, 6) 0.549036334
(3, 10) 0.440270504199
(3, 5) 0.440270504199
(3, 8) 0.370369427837
(3, 4) 0.530388665338
(3, 3) 0.440270504199
(4, 2) 0.377964473009
(4, 11) 0.755928946018
(4, 0) 0.377964473009
(4, 12) 0.377964473009

在(index1,index2)中:index1表示為第幾個句子或者文檔,index2為所有語料庫中的單詞組成的詞典的序號,之后的數字為該詞所計算得到的TFIDF的結果值

第二種方法就是直接用TfidfVectorizer()

from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
    'This is the first document.',
    'This is the second document.',
    'And the third one',
    'Is this the first document?',
    'I come to American to travel'
]

tfidf = TfidfVectorizer().fit_transform(corpus)
print (tfidf)

結果是一樣的

 

另外的話,對於數據處理還有一種是transform(),它和fit_transform()區別是什么?

區別在哪?

fit_transform()就是將fit()和transform()結合了一下

fit_transform()就是先將數據進行擬合,然后將其標准化

transform()作用是通過找中心和縮放等實現標准化

可以說是:

transform()是一定可以替換成fit_transform(),但是fit_transform()不能替換為transform()

因為中間相差了一個fit()

那么fit()的作用是什么呢?

找到了一個博客http://blog.csdn.net/quiet_girl/article/details/72517053

fit()的作用相當於先找到數據轉換的一個規則再進行標准化,所以已經標准化的數據不需要再進行fit()了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM