python - 如何使用 t-SNE 进行降维以可视化我的 300 维词嵌入?

标签 python dimensionality-reduction

我目前正在尝试在 2d 中可视化 300 维的词向量。 我尝试了具有不同参数的 t-SNE 并阅读了 https://distill.pub/2016/misread-tsne/ 上的博客但到目前为止我没有得到有用的结果。

我想要一个与几个选定词向量的最近邻居相对应的可视化效果,但二维可视化效果到处都是。

是否不适合使用 TSNE 来解决我的问题?

from sklearn.manifold import TSNE

arr = []

for category in category_embeddings.keys():
    arr.append(category_embeddings[category][0]) 

perplex = 30
tsne_steps = 50000
lr = 10

fig_tsne = plt.figure(figsize=(18, 18), dpi=800)

tsne = TSNE(perplexity=perplex, 
            n_components=2, 
            init='pca', 
            n_iter=tsne_steps, 
            learning_rate=lr, 
            method="exact")

plot_only = len(category_embeddings.keys())
low_dim_embs = tsne.fit_transform(np.asarray(arr))

for i, title in enumerate(category_embeddings.keys()):
    x, y = low_dim_embs[i, :]
    plt.scatter(x, y)
    plt.annotate(
        title,
        xy=(x, y),
        xytext=(5, 2),
        textcoords='offset points',
        ha='right',
        va='bottom')

最佳答案

好的,解决了。

创建距离矩阵并向 TSNE 提供该矩阵会产生更好的 2d 可视化效果。

from sklearn.metrics.pairwise import cosine_distances

c1_c2_cos_dist = {}

# Create distance Matrix
for c1in category_embeddings.keys():
    tmp = {}
    for c2 in category_embeddings.keys():
        cos_dis = cosine_distances(category_embeddings[c1],category_embeddings[
        tmp[c2] = cos_dis[0][0]

    c1_c2_cos_dist[c1] = copy(tmp)

# --- 

from sklearn.manifold import TSNE

arr = []

for category in category_embeddings.keys():
    arr.append(category_embeddings[category][0]) 

perplex = 30
tsne_steps = 50000
lr = 10

fig_tsne = plt.figure(figsize=(18, 18), dpi=800)

tsne = TSNE(perplexity=perplex, 
            n_components=2, 
            metric="precomputed",
            n_iter=tsne_steps, 
            learning_rate=lr)

distMatrix = []
for col in c1_c2_cos_dist.keys():
    arr =[]
    for row in c1_c2_cos_dist[col]:
        arr.append(c1_c2_cos_dist[col][row])
    distMatrix.append(copy(arr))  

distMatrix = np.asarray(distMatrix)
low_dim_embs = tsne.fit_transform(distMatrix)

plot_only = len(category_embeddings.keys())

for i, title in enumerate(category_embeddings.keys()):
    x, y = low_dim_embs[i, :]
    plt.scatter(x, y)
    plt.annotate(
        title,
        xy=(x, y),
        xytext=(5, 2),
        textcoords='offset points',
        ha='right',
        va='bottom')

关于python - 如何使用 t-SNE 进行降维以可视化我的 300 维词嵌入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57055598/

相关文章:

python - 使用 SQLAlchemy 将 Timezone Aware datetime64[ns] 插入 MySQL

python - 在不破坏内存的情况下复制生成器

text - 在自然语言处理(NLP)中,如何进行有效的降维?

python - 构建包含 c 库 (pytidylib) 的 Python Wheel

python - Auth0 PKCE Grant 无法验证代码验证器

python - 电报机器人返回空

r - tsne 初始 PCA 步骤在做什么

python - 在给定的点集中选择最远点的子集

Tensorflow 降低 3 阶张量的维度