日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python tfidf特征变换_使用sklearn提取文本的tfidf特征

發布時間:2025/3/12 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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特征的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。