FelixOtt's picture
Upload folder using huggingface_hub
9877759 verified
Raw History Blame Contribute Delete
12.4 kB
import numpy as np
import matplotlib.pyplot as plt
import os
from glob import glob
from tqdm import tqdm
import sys
def Hbeta(D=np.array([]), beta=1.0):
"""
Compute the perplexity and the P-row for a specific value of the
precision of a Gaussian distribution.
Args:
D (numpy.ndarray): Distance array.
beta (float): Precision of the Gaussian distribution.
Returns:
tuple: A tuple containing perplexity (H) and the P-row (P).
"""
P = np.exp(-D.copy() * beta)
sumP = sum(P)
H = np.log(sumP) + beta * np.sum(D * P) / sumP
P = P / sumP
return H, P
def pca(X=np.array([]), no_dims=50):
# Runs PCA on the NxD array X in order to reduce its dimensionality to no_dims dimensions.
(n, d) = X.shape
X = X - np.tile(np.mean(X, 0), (n, 1))
(l, M) = np.linalg.eig(np.dot(X.T, X))
Y = np.dot(X, M[:, 0:no_dims])
return Y
def x2p(X=np.array([]), tol=1e-5, perplexity=30.0):
"""
Performs a binary search to get P-values in such a way that each
conditional Gaussian has the same perplexity.
"""
(n, d) = X.shape
sum_X = np.sum(np.square(X), 1)
D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X)
P = np.zeros((n, n))
beta = np.ones((n, 1))
logU = np.log(perplexity)
# Loop over all datapoints
for i in range(n):
if i % 100 == 0:
print("Computing P-values for point %d of %d..." % (i, n))
# Compute the Gaussian kernel and entropy for the current precision
betamin = -np.inf
betamax = np.inf
Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))]
(H, thisP) = Hbeta(Di, beta[i])
# Evaluate whether the perplexity is within tolerance
Hdiff = H - logU
tries = 0
while np.abs(Hdiff) > tol and tries < 50:
# If not, increase or decrease precision
if Hdiff > 0:
betamin = beta[i].copy()
if betamax == np.inf or betamax == -np.inf:
beta[i] = beta[i] * 2.
else:
beta[i] = (beta[i] + betamax) / 2.
else:
betamax = beta[i].copy()
if betamin == np.inf or betamin == -np.inf:
beta[i] = beta[i] / 2.
else:
beta[i] = (beta[i] + betamin) / 2.
# Recompute the values
(H, thisP) = Hbeta(Di, beta[i])
Hdiff = H - logU
tries += 1
# Set the final row of P
P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP
# Return final P-matrix
print("Mean value of sigma: %f" % np.mean(np.sqrt(1 / beta)))
return P
def tsne(X=np.array([]), no_dims=2, initial_dims=50, perplexity=30.0):
"""
Runs t-SNE on the dataset in the NxD array X to reduce its
dimensionality to no_dims dimensions. The syntaxis of the function is
`Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array.
"""
if isinstance(no_dims, float):
print("Error: array X should have type float.")
return -1
if round(no_dims) != no_dims:
print("Error: number of dimensions should be an integer.")
return -1
X = pca(X, initial_dims).real
(n, d) = X.shape
max_iter = 1000
initial_momentum = 0.5
final_momentum = 0.8
eta = 500
min_gain = 0.01
Y = np.random.randn(n, no_dims)
dY = np.zeros((n, no_dims))
iY = np.zeros((n, no_dims))
gains = np.ones((n, no_dims))
# Compute P-values
P = x2p(X, 1e-5, perplexity)
P = P + np.transpose(P)
P = P / np.sum(P)
P = P * 4.
P = np.maximum(P, 1e-12)
for iter in range(max_iter):
# Compute pairwise affinities
sum_Y = np.sum(np.square(Y), 1)
num = -2. * np.dot(Y, Y.T)
num = 1. / (1. + np.add(np.add(num, sum_Y).T, sum_Y)) #
num[range(n), range(n)] = 0.
Q = num / np.sum(num)
Q = np.maximum(Q, 1e-12)
# Compute gradient
PQ = P - Q
for i in range(n):
dY[i, :] = np.sum(np.tile(PQ[:, i] * num[:, i], (no_dims, 1)).T * (Y[i, :] - Y), 0)
# Perform the update
if iter < 20:
momentum = initial_momentum
else:
momentum = final_momentum
gains = (gains + 0.2) * ((dY > 0.) != (iY > 0.)) + \
(gains * 0.8) * ((dY > 0.) == (iY > 0.))
gains[gains < min_gain] = min_gain
iY = momentum * iY - eta * (gains * dY)
Y = Y + iY
Y = Y - np.tile(np.mean(Y, 0), (n, 1))
# Compute current value of cost function
if (iter + 1) % 10 == 0:
C = np.sum(P * np.log(P / Q))
print("Iteration %d: error is %f" % (iter + 1, C))
if iter == 100:
P = P / 4.
return Y
import numpy as np
import matplotlib.pyplot as plt
import os
from glob import glob
from tqdm import tqdm
import sys
def Hbeta(D=np.array([]), beta=1.0):
"""
Compute the perplexity and the P-row for a specific value of the
precision of a Gaussian distribution.
Args:
D (numpy.ndarray): Distance array.
beta (float): Precision of the Gaussian distribution.
Returns:
tuple: A tuple containing perplexity (H) and the P-row (P).
"""
# Compute P-row and corresponding perplexity
P = np.exp(-D.copy() * beta)
sumP = np.sum(P)
H = np.log(sumP) + beta * np.sum(D * P) / sumP
P = P / sumP
return H, P
def pca(X=np.array([]), no_dims=50):
"""
Performs PCA on the NxD array X to reduce its dimensionality to no_dims dimensions.
Args:
X (numpy.ndarray): Input data array.
no_dims (int): Number of dimensions to reduce to.
Returns:
numpy.ndarray: The reduced data array.
"""
(n, d) = X.shape
X = X - np.tile(np.mean(X, axis=0), (n, 1))
(l, M) = np.linalg.eig(np.dot(X.T, X))
Y = np.dot(X, M[:, 0:no_dims])
return Y
def x2p(X=np.array([]), tol=1e-5, perplexity=30.0):
"""
Performs a binary search to get P-values such that each
conditional Gaussian has the same perplexity.
Args:
X (numpy.ndarray): Input data array.
tol (float): Tolerance for the perplexity.
perplexity (float): Desired perplexity.
Returns:
numpy.ndarray: The P-values matrix.
"""
(n, d) = X.shape
sum_X = np.sum(np.square(X), axis=1)
D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X)
P = np.zeros((n, n))
beta = np.ones((n, 1))
logU = np.log(perplexity)
# Loop over all data points
for i in range(n):
if i % 100 == 0:
print(f"Computing P-values for point {i} of {n}...")
# Compute the Gaussian kernel and entropy for the current precision
betamin = -np.inf
betamax = np.inf
Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))]
(H, thisP) = Hbeta(Di, beta[i])
# Evaluate whether the perplexity is within tolerance
Hdiff = H - logU
tries = 0
while np.abs(Hdiff) > tol and tries < 50:
# If not, adjust precision
if Hdiff > 0:
betamin = beta[i].copy()
if betamax in [np.inf, -np.inf]:
beta[i] *= 2
else:
beta[i] = (beta[i] + betamax) / 2
else:
betamax = beta[i].copy()
if betamin in [np.inf, -np.inf]:
beta[i] /= 2
else:
beta[i] = (beta[i] + betamin) / 2
# Recompute the values
(H, thisP) = Hbeta(Di, beta[i])
Hdiff = H - logU
tries += 1
# Set the final row of P
P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP
print("Mean value of sigma: %f" % np.mean(np.sqrt(1 / beta)))
return P
def tsne(X=np.array([]), no_dims=2, initial_dims=50, perplexity=30.0):
"""
Runs t-SNE on the dataset in the NxD array X to reduce its
dimensionality to no_dims dimensions.
Args:
X (numpy.ndarray): Input data array.
no_dims (int): Number of dimensions to reduce to.
initial_dims (int): Number of initial dimensions.
perplexity (float): Desired perplexity.
Returns:
numpy.ndarray: The reduced data array.
"""
if isinstance(no_dims, float):
print("Error: array X should have type float.")
return -1
if round(no_dims) != no_dims:
print("Error: number of dimensions should be an integer.")
return -1
X = pca(X, initial_dims).real
(n, d) = X.shape
max_iter = 1000
initial_momentum = 0.5
final_momentum = 0.8
eta = 500
min_gain = 0.01
Y = np.random.randn(n, no_dims)
dY = np.zeros((n, no_dims))
iY = np.zeros((n, no_dims))
gains = np.ones((n, no_dims))
# Compute P-values
P = x2p(X, 1e-5, perplexity)
P = P + np.transpose(P) # Ensure symmetry
P = P / np.sum(P) # Normalize
P = P * 4. # Early exaggeration
P = np.maximum(P, 1e-12) # Avoid numerical issues
for iter in range(max_iter):
# Compute pairwise affinities
sum_Y = np.sum(np.square(Y), axis=1)
num = -2. * np.dot(Y, Y.T)
num = 1. / (1. + np.add(np.add(num, sum_Y).T, sum_Y))
num[np.arange(n), np.arange(n)] = 0. # Avoid self-affinity
Q = num / np.sum(num)
Q = np.maximum(Q, 1e-12) # Avoid numerical issues
# Compute gradient
PQ = P - Q
for i in range(n):
dY[i, :] = np.sum(np.tile(PQ[:, i] * num[:, i], (no_dims, 1)).T * (Y[i, :] - Y), axis=0)
# Perform the update
momentum = initial_momentum if iter < 20 else final_momentum
gains = (gains + 0.2) * ((dY > 0.) != (iY > 0.)) + (gains * 0.8) * ((dY > 0.) == (iY > 0.))
gains[gains < min_gain] = min_gain
iY = momentum * iY - eta * (gains * dY)
Y = Y + iY
Y -= np.tile(np.mean(Y, axis=0), (n, 1)) # Center the data
# Compute current value of cost function
if (iter + 1) % 10 == 0:
C = np.sum(P * np.log(P / Q))
print(f"Iteration {iter + 1}: error is {C:.6f}")
if iter == 100:
P /= 4. # Decrease early exaggeration
return Y
if __name__ == '__main__':
task = sys.argv[2]
if sys.argv[1] == "gnss":
task_class = {0: 3, 1: 5, 2: 7, 3: 9, 4: 11}
colors = {0: "#1f77b4", 1: "#ff7f0e", 2: "#2ca02c", 3: "#d62728",
4: "#9467bd", 5: "#8c564b", 6: "#e377c2", 7: "#7f7f7f",
8: "#bcbd22", 9: "#17becf", 10: "#000000"}
elif sys.argv[1] == "cifar":
task_class = {0: 4, 1: 6, 2: 8, 3: 10}
colors = {0: "#1f77b4", 1: "#ff7f0e", 2: "#2ca02c", 3: "#d62728",
4: "#9467bd", 5: "#8c564b", 6: "#e377c2", 7: "#7f7f7f",
8: "#bcbd22", 9: "#17becf"}
else:
raise Exception("Please provide the name of the dataset.")
# Load embeddings and ground truth of a task
emb_file = f"embeddings_{task}.npy"
ground_truth_file = f"predictions_{task}_tr_pr.npy"
points = np.load(emb_file)
ground_truth = np.load(ground_truth_file)
size = points.shape[1]
labels = ground_truth[:, 0]
# Check if t-SNE embeddings are already computed
tsne_file = f"tsne_embeddings/emb_tsne_{task}.npy"
if not os.path.isfile(tsne_file):
tsne_embs = tsne(points, 2, size, 30.0)
np.save(tsne_file, tsne_embs)
tsne_embs = np.load(tsne_file, allow_pickle=True)
x = tsne_embs
print('t-SNE embeddings shape:', x.shape)
y = labels
colors_list = [colors[cy] for cy in y]
# Plotting the t-SNE results
plt.figure(figsize=(5, 4))
for key, val in colors.items():
if key == task_class[int(task)]:
break
cur_x = x[y == key]
plt.scatter(cur_x[:, 0], cur_x[:, 1], s=8, color=val, label=f"Class: {key}")
# Add legend and save the plot
plt.legend(fontsize=10, loc="lower left", ncol=2, labelspacing=0.03, columnspacing=0.03,
handletextpad=0.03)
plt.tight_layout()
plt.xticks([], [])
plt.yticks([], [])
plt.savefig(f"tsne_plots/tsne_{task}.pdf", dpi=1200)
plt.close()