我正在学习聚类,并且在几个教程中看到了一些我不太理解的相似性度量部分的内容:
tfidf_vector = TfidfVectorizer()
tfidf_matrix = tfidf_vector.fit_transform(file)
#and/or
count_vector = CountVectorizer()
count_matrix = count_vector.fit_transform(file)
#AND HERE
file_size = len(file)
x = np.zeros((file_size, file_size))
#and here the similarity measures like cosine_similarity, jaccard...
for elm in range(file_size):
x[elm] = cosine_similarity(tfidf_matrix[i:i+1], tfidf_matrix)
y = np.subtract(np.ones((file_size, file_size),dtype = np.float), x)
new_file = np.asarray(y)
w = new_file.reshape((1,file_size,file_size))
为什么我们需要 np.zeros? tfidf_matrix/count_matrix 不足以用于相似性度量吗?
最佳答案
这段代码做了同样的事情(我将i
更改为elm
,因为它看起来像是一个拼写错误)
x = []
for elm in range(file_size):
x.append(cosine_similarity(tfidf_matrix[elm:elm+1], tfidf_matrix)
x = np.asarray(x)
您还可以将 np.zeros 替换为 np.empty。预先创建数组,然后填充数组的每个元素,比追加到列表然后将其转换为 numpy 数组要稍微高效一些。许多其他编程语言需要像 numpy 一样预先分配数组,这就是为什么很多人选择以这种方式填充数组的原因。
然而,由于这是Python,你应该做任何你认为对你自己和其他人来说最容易阅读的方法。
关于python - 了解聚类中的 np.zeros,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51501712/