溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Scikit-learn文本聚類實例分析

發(fā)布時間:2022-01-10 11:36:33 來源:億速云 閱讀:101 作者:柒染 欄目:開發(fā)技術(shù)

Scikit-learn文本聚類實例分析,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

# -*- coding=utf-8 -*-
"""
text category
"""
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)
print len(twenty_train.data)
len(twenty_train.filenames)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twenty_train.data)
print X_train_counts.shape
print count_vect.vocabulary_.get('algorithm')
tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)
print X_train_tf.shape
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tf_transformer.fit_transform(X_train_counts)
print X_train_tfidf.shape
clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target)
docs_new = ['God is love', 'OpenGl on the Gpu is fast']
X_new_counts = count_vect.transform(docs_new)
X_new_tfidf = tfidf_transformer.fit_transform(X_new_counts)
predicted = clf.predict(X_new_tfidf)
for doc, category in zip(docs_new, predicted):
    print '%r=>%s' % (doc, twenty_train.target_names[category]

對fetch_20newsgroups中的2257條文檔進行分類

  1. 統(tǒng)計每個詞出現(xiàn)的次數(shù)

  2. 用tf-idf統(tǒng)計詞頻,tf是在一個文檔里每個單詞出現(xiàn)的次數(shù)除以文檔的單詞總數(shù),idf是總的文檔數(shù)除以包含該單詞的文檔數(shù),再取對數(shù);tf * idf就是這里用到的值,值越大表明單詞越重要,或越相關(guān)。

例子具體做法:

  1. 先計算了每個單詞出現(xiàn)的次數(shù)

  2. 然后計算了tf-idf值

  3. 然后帶入模型進行訓練

  4. 最后預(yù)測了兩個新文檔的類型

結(jié)果:

'God is love'=> soc.religion.christian
'OpenGL on the GPU is fast'=> comp.graphics

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI