【发布时间】:2019-09-23 01:31:02
【问题描述】:
编辑 2:我对我的问题进行了更好的思考,并意识到这是一种概括的方式,这只是一个基本的问题;
从 Glove 文件 (glove.6B.300d.txt) 创建一个新数组,其中仅包含我在文档中的单词列表。
我知道这实际上与这个特定的 GloVe 文件无关,我应该学习如何对任意两个单词列表执行此操作...
我假设我只是不知道如何正确地查找它以了解如何执行这部分。即我应该寻找什么库/函数/buuzzwords。
编辑 1:我正在添加适用于整个 GloVe 库的代码;
from __future__ import division
from sklearn.cluster import KMeans
from numbers import Number
from pandas import DataFrame
import sys, codecs, numpy
class autovivify_list(dict):
def __missing__(self, key):
value = self[key] = []
return value
def __add__(self, x):
if not self and isinstance(x, Number):
return x
raise ValueError
def __sub__(self, x):
if not self and isinstance(x, Number):
return -1 * x
raise ValueError
def build_word_vector_matrix(vector_file, n_words):
numpy_arrays = []
labels_array = []
with codecs.open(vector_file, 'r', 'utf-8') as f:
for c, r in enumerate(f):
sr = r.split()
labels_array.append(sr[0])
numpy_arrays.append( numpy.array([float(i) for i in sr[1:]]) )
if c == n_words:
return numpy.array( numpy_arrays ), labels_array
return numpy.array( numpy_arrays ), labels_array
def find_word_clusters(labels_array, cluster_labels):
cluster_to_words = autovivify_list()
for c, i in enumerate(cluster_labels):
cluster_to_words[ i ].append( labels_array[c] )
return cluster_to_words
if __name__ == "__main__":
input_vector_file =
'/Users/.../Documents/GloVe/glove.6B/glove.6B.300d.txt'
n_words = 1000
reduction_factor = 0.5
n_clusters = int( n_words * reduction_factor )
df, labels_array = build_word_vector_matrix(input_vector_file,
n_words)
kmeans_model = KMeans(init='k-means++', n_clusters=n_clusters,
n_init=10)
kmeans_model.fit(df)
cluster_labels = kmeans_model.labels_
cluster_inertia = kmeans_model.inertia_
cluster_to_words = find_word_clusters(labels_array,
cluster_labels)
for c in cluster_to_words:
print cluster_to_words[c]
print "\n"
原问题:
假设我有一个特定的文本(比如 500 个字)。 我想做以下事情:
- 创建此文本中所有单词的嵌入(即仅包含这 500 个单词的 GloVe 向量列表)
- 聚类(*这个我知道怎么做)
我该怎么做?
【问题讨论】:
-
请提供 MWE 以展示您尝试过的内容以及您如何准确地表示 Glove 向量。
-
你想从你的词中获得一个新的嵌入集吗?你只有500字的文字吗?你的话是清单吗?回答这些问题可以帮助您找到更好的信息。
-
回答 Tiago Duque:是的,我有一个 500 个单词的文本文件,我可以将它做成一个单词列表,并且我想要一个嵌入这些单词的内容。
标签: python nlp data-science glove