gpt4 book ai didi

python - 如何对 Word2Vec 进行聚类

转载 作者:行者123 更新时间:2023-11-28 20:58:04 25 4
gpt4 key购买 nike

我有一个半结构化数据集,每一行都属于一个用户:

id, skills
0,"java, python, sql"
1,"java, python, spark, html"
2, "business management, communication"

为什么是半结构化是因为以下技能只能从 580 个唯一值的列表中选择。

我的目标是对用户进行聚类,或者根据相似的技能组合找到相似的用户。我尝试过使用 Word2Vec 模型,它给了我很好的结果来识别相似的技能集——例如。

model.most_similar(["Data Science"])

给我 -

[('Data Mining', 0.9249375462532043),
('Data Visualization', 0.9111810922622681),
('Big Data', 0.8253220319747925),...

这为我提供了一个非常好的模型来识别个人技能而不是一组技能。我如何利用 Word2Vec 模型提供的向量成功地对相似用户组进行聚类?

最佳答案

您需要使用 Word2Vec 模型对字符串进行矢量化。你可以这样实现:

model = KeyedVectors.load("path/to/your/model") 
w2v_vectors = model.wv.vectors # here you load vectors for each word in your model
w2v_indices = {word: model.wv.vocab[word].index for word in model.wv.vocab} # here you load indices - with whom you can find an index of the particular word in your model

然后你可以这样使用is:

def vectorize(line): 
words = []
for word in line: # line - iterable, for example list of tokens
try:
w2v_idx = w2v_indices[word]
except KeyError: # if you does not have a vector for this word in your w2v model, continue
continue
words.append(w2v_vectors[w2v_idx])
if words:
words = np.asarray(words)
min_vec = words.min(axis=0)
max_vec = words.max(axis=0)
return np.concatenate((min_vec, max_vec))
if not words:
return None

然后您会收到一个向量,它代表您的行(文档等)。

收到每条线的所有向量后,您需要进行聚类,您可以使用 sklearn 中的 DBSCAN 进行聚类。

from sklearn.cluster import DBSCAN
dbscan = DBSCAN(metric='cosine', eps=0.07, min_samples=3) # you can change these parameters, given just for example
cluster_labels = dbscan.fit_predict(X) # where X - is your matrix, where each row corresponds to one document (line) from the docs, you need to cluster

祝你好运!

关于python - 如何对 Word2Vec 进行聚类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52049511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com