学前基础
原理

词向量+norm+kmeans
import re, numpy as np, pandas as pd, jieba
from gensim.models import Word2Vec
from sklearn.cluster import KMeans
def word_cluster(texts, n_clusters=800):
# 分词
texts = [[word for word in jieba.cut(sentence) if re.fullmatch('[a-zA-Z\u4e00-\u9fa5]+', word)]
for text in texts for sentence in re.split('[\n。…;;!!??]+', text)]
# 词向量
wv = Word2Vec(texts).wv
# 转为单位向量
uv = np.linalg.norm(wv.vectors, axis=1).reshape(-1, 1) # Unit Vector
wv.vectors = wv.vectors / uv # Vector or matrix norm
# 聚类
labels = KMeans(n_clusters).fit(wv.vectors).labels_
# 输出excel
df = pd.DataFrame([(w, labels[e]) for e, w in enumerate(wv.index2word)], columns=['word', 'label'])
df.sort_values(by='label', inplace=True)
df.to_excel('word_cluster.xlsx', index=False)
from data9 import X # 新闻9分类,不导入Y
word_cluster(X)
部分结果展示

补充
-
主要可调参数
-
停词和词性过滤
时间词处理
词窗
词向量维度
sg=1
簇数
失败实验
-
词向量+kmeans:高频词和低频词会被分开
词向量+norm+DBSCAN:大部分词被连成一片(类别0)
LDA(长文切短):大部分词主题概率极低(主题0),一些停词反而有较高的主题权重😓
失败的LDA实验代码
from gensim import corpora, models
import re, jieba, numpy as np, pandas as pd
def word_lda(texts, num_topics=100):
# 分词
words_ls = [[w for w in jieba.cut(s) if re.fullmatch('[a-zA-Z\u4e00-\u9fa5]+', w)]
for t in texts for s in re.split('[\n。…;;!!??]+', t)]
# 构造词典
dictionary = corpora.Dictionary(words_ls)
# 基于词典,使【词】→【稀疏向量】,并将向量放入列表,形成【稀疏向量集】
corpus = [dictionary.doc2bow(words) for words in words_ls]
# lda模型,num_topics设置主题的个数
lda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=num_topics)
# 主题概率矩阵
matrix = lda.state.get_lambda()
matrix = matrix / np.sum(matrix, axis=0)
# 按照主题概率聚类,并存excel
pd.DataFrame({
'word': [dictionary[i] for i in range(len(dictionary))],
'topic': np.argmax(matrix, axis=0),
'probability': np.max(matrix, axis=0),
}).sort_values(by=['topic', 'probability'], ascending=False).to_excel('word_lda.xlsx', index=False)
from data9 import X # 新闻9分类,不导入标签
word_lda(X)
1313



被折叠的 条评论
为什么被折叠?



