我正在学习聚类,并且在一些教程中看到了一些在相似性度量中我不太了解的东西:
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是否足以用于相似性度量?
答案 0 :(得分:1)
这段代码做同样的事情(我将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,所以您应该做自己认为是最简单的方式来进行自己和他人的阅读。