Skip to content

Instantly share code, notes, and snippets.

View wangz10's full-sized avatar
🎯
Focusing

Zichen Wang wangz10

🎯
Focusing
View GitHub Profile
In [1]: import numpy as np
...: import jax.numpy as jnp
...: from jax import random, jit
In [2]: def slow_f(x):
...: # Element-wise ops see a large benefit from fusion
...: return x * x + x * 2.0
...:
...: # use XLA to compile the function
...: fast_f = jit(slow_f)
# Compute covariance matrix
C = np.dot(X.T, X) / (n-1)
# Eigen decomposition
eigen_vals, eigen_vecs = np.linalg.eig(C)
# SVD
U, Sigma, Vh = np.linalg.svd(X,
full_matrices=False,
compute_uv=True)
# Relationship between singular values and eigen values:
print(np.allclose(np.square(Sigma) / (n - 1), eigen_vals)) # True
@wangz10
wangz10 / svd_np.py
Created March 16, 2019 14:29
Perform SVD with numpy
def svd(X):
# Data matrix X, X doesn't need to be 0-centered
n, m = X.shape
# Compute full SVD
U, Sigma, Vh = np.linalg.svd(X,
full_matrices=False, # It's not necessary to compute the full matrix of U or V
compute_uv=True)
# Transform X with SVD components
X_svd = np.dot(U, np.diag(Sigma))
return X_svd
@wangz10
wangz10 / pca_eigen_docomposition_np.py
Created March 16, 2019 14:25
Perform PCA by eigen decomposition
def pca(X):
# Data matrix X, assumes 0-centered
n, m = X.shape
assert np.allclose(X.mean(axis=0), np.zeros(m))
# Compute covariance matrix
C = np.dot(X.T, X) / (n-1)
# Eigen decomposition
eigen_vals, eigen_vecs = np.linalg.eig(C)
# Project X onto PC space
X_pca = np.dot(X, eigen_vecs)
def interpolate_from_a_to_b_for_c(model, X, labels, a=None, b=None, x_c=None, alpha=0.):
'''Perform interpolation between two classes a and b for any sample x_c.
model: a trained generative model
X: data in the original space with shape: (n_samples, n_features)
labels: array of class labels (n_samples, )
a, b: class labels a and b
x_c: input sample to manipulate (1, n_features)
alpha: scalar for the magnitude and direction of the interpolation
'''
# Encode samples to the latent space
@wangz10
wangz10 / jointplot_w_hue.py
Last active September 26, 2018 16:18 — forked from ruxi/jointplot_w_hue.py
jointplot_w_hue
__author__ = "lewis.r.liu@gmail.com"
__copyright__ = "Copyright 2018, github.com/ruxi"
__license__ = "MIT"
__version__ = 0.0.1
# update: Mar 5 , 2018
# created: Feb 19, 2018
# desc: seaborn jointplot with 'hue'
# prepared for issue: https://github.com/mwaskom/seaborn/issues/365
"""
@wangz10
wangz10 / .gitignore
Last active August 29, 2015 14:24 — forked from cornhundred/.gitignore
d3_clustergram
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #