前文向量语义模型中说明了如何使用共现矩阵(co-occurrence matrix)表示词向量(word vectors)和文档向量(document vectors)。本文作为补充来深入阐述向量相似性指标包括cosine相似性(前面的文章也涉及到)和欧氏距离以及用于降维可视化的PCA方法。
相似性指标
- 欧氏距离
欧几里得距离是连接两个向量的直线段的长度, n n n维向量距离的计算公式如下:
😊python实现如下:
import numpy as np
v = np.array([1,4,6])
w = np.array([2,5,8])
d = np.linalg.norm(v-w) #输出为:2.449489742783178
- cosine
上图的三个corpus中“Agriculture corpus”和“History corpus”有相似的单词总数,而“Food corpus”则相对较少。可以看到,角度比距离更能合理的进行相似性度量。
😊 python实现如下:
import numpy as np
v = np.array([20,40])
w = np.array([30,20])
cosine = np.dot(v,w)/(np.linalg.norm(v) * np.linalg.norm(w)) #输出:0.868
利用两个向量之间的角度余弦值计算相似度相比欧氏距离的优点在于不受向量表示之间大小差异的影响。
主成分分析(PCA,1901)
PCA作为一种降维方法可以为数据找到不相关特征并试图保留尽可能多的信息,从而可视化数据来帮助检查向量之间的关系。上图是将PCA应用于二维空间上的过程示意图。
过程
- 要执行PCA,第一步是要获取一组不相关的特征——对数据进行归一化得到
X
X
X,计算原始数据的协方差矩阵
∑
\sum
∑,最后执行SVD得到3个矩阵从而获得特征值和特征向量。
特征向量: 数据的不相关特征,给出不相关特征的方向
特征值:每个特征下数据集的方差
- 第二步是将数据投射到一组新的特征中去, 即词向量矩阵点乘特征向量矩阵得到你想要维数的新矩阵(对于可视化常保留两个维度)。还可以获得保留在新向量空间中的方差百分比。
😊python实现:
"""
Input:
X: of dimension (m,n) where each row corresponds to a word vector
n_components: Number of components you want to keep.
Output:
X_reduced: data transformed in 2 dims/columns + regenerated original data
"""
# mean center the data
X_demeaned = X - np.expand_dims(np.mean(X,axis=0),axis=0)
# calculate the covariance matrix
covariance_matrix = np.cov(X_demeaned,rowvar=False)
# calculate eigenvectors & eigenvalues of the covariance matrix
eigen_vals, eigen_vecs = np.linalg.eigh(covariance_matrix, UPLO='L')
# sort eigenvalue in increasing order (get the indices from the sort)
idx_sorted = np.argsort(eigen_vals)
# reverse the order so that it's from highest to lowest.
idx_sorted_decreasing = idx_sorted[::-1]
# sort the eigen values by idx_sorted_decreasing
eigen_vals_sorted = eigen_vals[idx_sorted_decreasing]
# sort eigenvectors using the idx_sorted_decreasing indices
eigen_vecs_sorted = eigen_vecs[:,idx_sorted_decreasing]
# select the first n eigenvectors (n is desired dimension
# of rescaled data array, or dims_rescaled_data)
eigen_vecs_subset = eigen_vecs_sorted[:,:n_components]
X_reduced = np.dot(X_demeaned,eigen_vecs_subset)
随后就可以利用PCA将高维的词向量进行降维到二维平面上,从而方便进行可视化。整个源代码见我的github。