python tfidf特征变换_使用sklearn提取文本的tfidf特征
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
]
CountVectorizer是通過fit_transform函數將文本中的詞語轉換為詞頻矩陣
get_feature_names()可看到所有文本的關鍵字
vocabulary_可看到所有文本的關鍵字和其位置
toarray()可看到詞頻矩陣的結果
vectorizer = CountVectorizer()
count = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(vectorizer.vocabulary_)
print(count.toarray())
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
{'this': 8, 'is': 3, 'the': 6, 'first': 2, 'document': 1, 'second': 5, 'and': 0, 'third': 7, 'one': 4}
[[0 1 1 1 0 0 1 0 1]
[0 1 0 1 0 2 1 0 1]
[1 0 0 0 1 0 1 1 0]
[0 1 1 1 0 0 1 0 1]]
TfidfTransformer是統計CountVectorizer中每個詞語的tf-idf權值
transformer = TfidfTransformer()
tfidf_matrix = transformer.fit_transform(count)
print(tfidf_matrix.toarray())
[[ 0. 0.43877674 0.54197657 0.43877674 0. 0.
0.35872874 0. 0.43877674]
[ 0. 0.27230147 0. 0.27230147 0. 0.85322574
0.22262429 0. 0.27230147]
[ 0.55280532 0. 0. 0. 0.55280532 0.
0.28847675 0.55280532 0. ]
[ 0. 0.43877674 0.54197657 0.43877674 0. 0.
0.35872874 0. 0.43877674]]
TfidfVectorizer可以把CountVectorizer, TfidfTransformer合并起來,直接生成tfidf值
TfidfVectorizer的關鍵參數:
max_df:這個給定特征可以應用在 tf-idf 矩陣中,用以描述單詞在文檔中的最高出現率。假設一個詞(term)在 80% 的文檔中都出現過了,那它也許(在劇情簡介的語境里)只攜帶非常少信息。
min_df:可以是一個整數(例如5)。意味著單詞必須在 5 個以上的文檔中出現才會被納入考慮。設置為 0.2;即單詞至少在 20% 的文檔中出現 。
ngram_range:這個參數將用來觀察一元模型(unigrams),二元模型( bigrams) 和三元模型(trigrams)。參考n元模型(n-grams)。
tfidf_vec = TfidfVectorizer()
tfidf_matrix = tfidf_vec.fit_transform(corpus)
print(tfidf_vec.get_feature_names())
print(tfidf_vec.vocabulary_)
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
{'this': 8, 'is': 3, 'the': 6, 'first': 2, 'document': 1, 'second': 5, 'and': 0, 'third': 7, 'one': 4}
print(tfidf_matrix.toarray())
[[ 0. 0.43877674 0.54197657 0.43877674 0. 0.
0.35872874 0. 0.43877674]
[ 0. 0.27230147 0. 0.27230147 0. 0.85322574
0.22262429 0. 0.27230147]
[ 0.55280532 0. 0. 0. 0.55280532 0.
0.28847675 0.55280532 0. ]
[ 0. 0.43877674 0.54197657 0.43877674 0. 0.
0.35872874 0. 0.43877674]]
使用gensim的corpora和models也可以實現類似的功能,
參考:
總結
以上是生活随笔為你收集整理的python tfidf特征变换_使用sklearn提取文本的tfidf特征的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot 接口404_资深架
- 下一篇: websocket python爬虫_p