kmeans聚類非常好用,強烈推薦強烈推薦強烈推薦

2021-10-02 02:19:06 字數 1763 閱讀 9699

# -*- coding: utf-8 -*-

import jieba

from sklearn.feature_extraction.text import countvectorizer

from sklearn.feature_extraction.text import tfidftransformer

from sklearn.cluster import kmeans

class kmeansclustering():

def __init__(self, stopwords_path=none):

self.stopwords = self.load_stopwords(stopwords_path)

self.vectorizer = countvectorizer()

self.transformer = tfidftransformer()

def load_stopwords(self, stopwords=none):

"""載入停用詞

:param stopwords:

:return:

"""if stopwords:

with open(stopwords, 'r', encoding='utf-8') as f:

return [line.strip() for line in f]

else:

return

def get_text_tfidf_matrix(self, corpus):

"""獲取tfidf矩陣

:param corpus:

:return:

"""tfidf = self.transformer.fit_transform(self.vectorizer.fit_transform(corpus))

# 獲取詞袋中所有詞語

# words = self.vectorizer.get_feature_names()

# 獲取tfidf矩陣中權重

weights = tfidf.toarray()

return weights

def kmeans(self, corpus_path, n_clusters=5):

"""kmeans文字聚類

:param corpus_path: 語料路徑(每行一篇),文章id從0開始

:param n_clusters: :聚類類別數目

:return:

"""corpus = self.preprocess_data(corpus_path)

weights = self.get_text_tfidf_matrix(corpus)

clf = kmeans(n_clusters=n_clusters)

# clf.fit(weights)

y = clf.fit_predict(weights)

# 中心點

# centers = clf.cluster_centers_

# 用來評估簇的個數是否合適,距離約**明簇分得越好,選取臨界點的簇的個數

# score = clf.inertia_

if __name__ == '__main__':

kmeans = kmeansclustering(stopwords_path='../data/stop_words.txt')

result = kmeans.kmeans('../data/keyword.txt', n_clusters=50)

print(result)

了解Cookie 強烈推薦

目錄 cookie的誕生 cookie的處理分為 伺服器端的傳送與解析 傳送cookie cookie 是怎麼工作的?cookie是由伺服器端生成,傳送給user agent,瀏覽器會將cookie的key value儲存到某個目錄下的文字檔案內,下次請求同一 時就傳送該cookie給伺服器,對co...

女孩到女人(強烈推薦)

我一直想找乙個理想的男友,結果總是很鬱悶。5歲時,我喜歡和乙個叫仔仔的男生玩,他有兩顆虎牙不算帥,但當他手裡有兩個 紅桔的時候,他會把那個大的給我吃。現在我再遇到他時,他手邊 有乙個5歲的女孩正 在叫他爸爸。16歲,我有點喜歡我們的生物老師,其實現在看起來,那就是 一種純純的喜歡。生物老師瘦瘦的白白...

接單平台強烈推薦彙總

1 程式設計師客棧 10 碼市 11 豬八戒網 100 開源眾包 101 碼易 110 雲沃客 111 特讚 1000 特創易 1001 智城外包網 1010 一品威客 1011 實現網 1100 猿急送 1101 人人開發 1110 開發邦 1111 電鴨社群 10000 快碼 10001 英選 ...