Spaces:
Running
Running
File size: 5,076 Bytes
e2b757a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# %%
import asyncio
import pickle as pk
import time
import warnings
import matplotlib as mpl
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np
import torch
from matplotlib import cm
from matplotlib.animation import FuncAnimation
from matplotlib.gridspec import GridSpec
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits.mplot3d import Axes3D, axes3d
from sklearn.decomposition import PCA
warnings.filterwarnings("ignore", category=UserWarning)
# file_path = "word_embeddings_mpnet.pth"
# embeddings_dict = torch.load(file_path)
# # %%
# words = list(embeddings_dict.keys())
# sentences = [[word] for word in words]
# vectors = list(embeddings_dict.values())
# vectors_list = []
# for item in vectors:
# vectors_list.append(item.tolist())
# vector_list = vectors_list[:10]
# # %%
# # pca = PCA(n_components=3)
# # pca = pca.fit(vectors_list)
# # pk.dump(pca, open("pca_mpnet.pkl", "wb"))
# score = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
# %%
def display_words(words, vector_list, score, bold):
# %%
plt.ioff()
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
plt.rcParams["image.cmap"] = "magma"
colormap = cm.get_cmap("magma") # You can choose any colormap you like
# Normalize the float values to the range [0, 1]
score = np.array(score)
norm = plt.Normalize(0, 10) # type: ignore
colors = colormap(norm(score))
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.w_zaxis.set_pane_color(
(0.87, 0.91, 0.94, 0.8)
) # Set the z-axis face color (gray)
ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Transparent x-axis line
ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Transparent y-axis line
ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Turn off axis labels
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
ax.grid(False)
# %%
data_pca = vector_list
if len(data_pca) > 1:
# for i in range(len(data_pca) - 1):
# data = np.append(
# data_pca,
# [norm_distance(data_pca[0], data_pca[i + 1], score[i + 1])],
# axis=0,
# )
# Create copies of the zero-th element of data_pca
data_pca0 = np.repeat(data_pca[0][None, :], len(data_pca) - 1, axis=0)
# Use these arrays to construct the calls to norm_distance_v
data = norm_distance_v(data_pca0, data_pca[1:], score[1:])
else:
data = data_pca.transpose()
(
x,
y,
z,
) = data
center_x = x[0]
center_y = y[0]
center_z = z[0]
# %%
ax.autoscale(enable=True, axis="both", tight=True)
# if bold == -1:
# k = len(words) - 1
# else:
# k = repeated
for i, word in enumerate(words):
if i == bold:
fontsize = "large"
fontweight = "demibold"
else:
fontsize = "medium"
fontweight = "normal"
ax.text(
x[i],
y[i],
z[i] + 0.05,
word,
fontsize=fontsize,
fontweight=fontweight,
alpha=1,
)
# ax.text(
# x[0],
# y[0],
# z[0] + 0.05,
# words[0],
# fontsize="medium",
# fontweight="normal",
# alpha=1,
# )
ax.scatter(x, y, z, c="black", marker="o", s=75, cmap="magma", vmin=0, vmax=10)
scatter = ax.scatter(
x,
y,
z,
marker="o",
s=70,
c=colors,
cmap="magma",
vmin=0,
vmax=10,
)
# cax = fig.add_subplot(gs[1, :]) # cb = plt.colorbar(sc, cax=cax)
# a = fig.colorbar(
# mappable=scatter,
# ax=ax,
# cmap="magma",
# norm=mpl.colors.Normalize(vmin=0, vmax=10),
# orientation="horizontal",
# )
fig.colorbar(
cm.ScalarMappable(norm=mpl.colors.Normalize(0, 10), cmap="magma"),
ax=ax,
orientation="horizontal",
)
# cbar.set_label("Score Values")
def update(frame):
distance = 0.5 * (score.max() - score.min())
ax.set_xlim(center_x - distance, center_x + distance)
ax.set_ylim(center_y - distance, center_y + distance)
ax.set_zlim(center_z - distance, center_z + distance)
ax.view_init(elev=20, azim=frame)
# %%
# Create the animation
frames = np.arange(0, 360, 5)
ani = FuncAnimation(fig, update, frames=frames, interval=120)
ani.save("3d_rotation.gif", writer="pillow", dpi=140)
plt.close(fig)
# %%
def norm_distance_v(orig, points, distances):
# Calculate the vector AB
AB = points - orig
# Calculate the normalized vector AB
Normalized_AB = AB / np.linalg.norm(AB, axis=1, keepdims=True)
# Specify the desired distance from point A
d = 10 - (distances.reshape(-1, 1) * 1)
# Calculate the new points C
C = orig + (Normalized_AB * d)
C = np.append([orig[0]], C, axis=0)
return np.array([C[:, 0], C[:, 1], C[:, 2]])
|