通過對特征做一個kmeans聚類,將聚類的結果做為文本的標簽值,可以使得樣本的特征更多
我們從sklearn.cluster中導入Kmeans建立模型進行聚類
代碼:
第一步:使用Dataframe格式化數據和使用數據格式化數據
第二步:對字符串進行分詞和去除停用詞,並使用' '.join完成連接
第三步:使用np.vectorizer向量化函數,調用函數進行分詞和去除停用詞
第四步:使用Tfidfvectorizer構造詞袋模型
第五步:使用cosine_similarity構造相關性矩陣
第六步:對相關性矩陣進行聚類操作,將增加的聚類標簽添加到原始數據中
import pandas as pd import numpy as np import re import nltk #pip install nltk corpus = ['The sky is blue and beautiful.', 'Love this blue and beautiful sky!', 'The quick brown fox jumps over the lazy dog.', 'The brown fox is quick and the blue dog is lazy!', 'The sky is very blue and the sky is very beautiful today', 'The dog is lazy but the brown fox is quick!' ] labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals'] # 第一步:構建DataFrame格式數據 corpus = np.array(corpus) corpus_df = pd.DataFrame({'Document': corpus, 'categoray': labels}) # 第二步:構建函數進行分詞和停用詞的去除 # 載入英文的停用詞表 stopwords = nltk.corpus.stopwords.words('english') # 建立詞分割模型 cut_model = nltk.WordPunctTokenizer() # 定義分詞和停用詞去除的函數 def Normalize_corpus(doc): # 去除字符串中結尾的標點符號 doc = re.sub(r'[^a-zA-Z0-9\s]', '', string=doc) # 是字符串變小寫格式 doc = doc.lower() # 去除字符串兩邊的空格 doc = doc.strip() # 進行分詞操作 tokens = cut_model.tokenize(doc) # 使用停止用詞表去除停用詞 doc = [token for token in tokens if token not in stopwords] # 將去除停用詞后的字符串使用' '連接,為了接下來的詞袋模型做准備 doc = ' '.join(doc) return doc # 第三步:向量化函數和調用函數 # 向量化函數,當輸入一個列表時,列表里的數將被一個一個輸入,最后返回也是一個個列表的輸出 Normalize_corpus = np.vectorize(Normalize_corpus) # 調用函數進行分詞和去除停用詞 corpus_norm = Normalize_corpus(corpus) # 第四步:使用TfidVectorizer進行TF-idf詞袋模型的構建 from sklearn.feature_extraction.text import TfidfVectorizer Tf = TfidfVectorizer(use_idf=True) Tf.fit(corpus_norm) vocs = Tf.get_feature_names() corpus_array = Tf.transform(corpus_norm).toarray() corpus_norm_df = pd.DataFrame(corpus_array, columns=vocs) print(corpus_norm_df.head()) # 第四步:使用TfidVectorizer進行TF-idf詞袋模型的構建 from sklearn.feature_extraction.text import TfidfVectorizer Tf = TfidfVectorizer(use_idf=True) Tf.fit(corpus_norm) vocs = Tf.get_feature_names() corpus_array = Tf.transform(corpus_norm).toarray() corpus_norm_df = pd.DataFrame(corpus_array, columns=vocs) print(corpus_norm_df.head()) # 第五步:使用cosine_similarity構造相關性矩陣 from sklearn.metrics.pairwise import cosine_similarity similarity_matrix = cosine_similarity(corpus_array) similarity_matrix_df = pd.DataFrame(similarity_matrix) # 第六步:構造聚類特征,這里主要是對相關性矩陣做的一種聚類,也可以對詞袋模型特征做 from sklearn.cluster import KMeans model = KMeans(n_clusters=2) model.fit(np.array(similarity_matrix)) print(model.labels_) corpus_norm_df['k_labels'] = np.array(model.labels_) print(corpus_norm_df.head())