我正在尝试重现本文的结果:https://arxiv.org/pdf/1607.06520.pdf
具体这部分:
To identify the gender subspace, we took the ten gender pair difference vectors and computed its principal components (PCs). As Figure 6 shows, there is a single direction that explains the majority of variance in these vectors. The first eigenvalue is significantly larger than the rest.
我使用与作者相同的词向量集(Google 新闻语料库,300 维),并将其加载到 word2vec。
作者所指的“十个性别对差异向量”是根据以下词对计算得出的:
我通过以下方式计算了每个归一化向量之间的差异:
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-
negative300.bin', binary = True)
model.init_sims()
pairs = [('she', 'he'),
('her', 'his'),
('woman', 'man'),
('Mary', 'John'),
('herself', 'himself'),
('daughter', 'son'),
('mother', 'father'),
('gal', 'guy'),
('girl', 'boy'),
('female', 'male')]
difference_matrix = np.array([model.word_vec(a[0], use_norm=True) - model.word_vec(a[1], use_norm=True) for a in pairs])
然后我根据论文对生成的矩阵执行 PCA,其中包含 10 个组件:
from sklearn.decomposition import PCA
pca = PCA(n_components=10)
pca.fit(difference_matrix)
但是,当我查看 pca.explained_variance_ratio_
时,我得到了非常不同的结果:
array([ 2.83391436e-01, 2.48616155e-01, 1.90642492e-01,
9.98411858e-02, 5.61260498e-02, 5.29706681e-02,
2.75670634e-02, 2.21957722e-02, 1.86491774e-02,
1.99108478e-32])
或用图表:
第一个分量在应该高于 60% 的情况下占方差的不到 30%!
我得到的结果与我尝试对随机选择的向量进行 PCA 时得到的结果相似,所以我一定做错了什么,但我不知道是什么。
注意:我尝试过不对向量进行归一化,但得到了相同的结果。
最佳答案
他们在 github 上发布了论文的代码:https://github.com/tolga-b/debiaswe
具体来说,您可以在 this 中查看他们创建 PCA 图的代码。文件。
以下是该文件中的相关代码片段:
def doPCA(pairs, embedding, num_components = 10):
matrix = []
for a, b in pairs:
center = (embedding.v(a) + embedding.v(b))/2
matrix.append(embedding.v(a) - center)
matrix.append(embedding.v(b) - center)
matrix = np.array(matrix)
pca = PCA(n_components = num_components)
pca.fit(matrix)
# bar(range(num_components), pca.explained_variance_ratio_)
return pca
根据代码,看起来他们正在获取一对中的每个单词与该对的平均向量之间的差异。对我来说,不清楚这就是他们在论文中的意思。但是,我用他们的配对运行了这段代码,并能够从论文中重新创建图表:
关于python - word2vec 嵌入上的 PCA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48019843/