def test_types(self):
def check(dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
w, v = np.linalg.eigh(x)
assert_equal(w.dtype, get_real_dtype(dtype))
assert_equal(v.dtype, dtype)
for dtype in [single, double, csingle, cdouble]:
yield check, dtype
python类eigh()的实例源码
def test_invalid(self):
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
assert_raises(ValueError, np.linalg.eigh, x, "lower")
assert_raises(ValueError, np.linalg.eigh, x, "upper")
def getPCAVideo(I):
ICov = I.dot(I.T)
[lam, V] = linalg.eigh(ICov)
lam[lam < 0] = 0
V = V*np.sqrt(lam[None, :])
return V
def train(self):
super().train()
sigma = self.Sigma_hat
D_, U = LA.eigh(sigma)
D = np.diagflat(D_)
self.A = np.power(LA.pinv(D), 0.5) @ U.T
def train(self):
super().train()
W = self.Sigma_hat
# prior probabilities (K, 1)
Pi = self.Pi
# class centroids (K, p)
Mu = self.Mu
p = self.p
# the number of class
K = self.n_class
# the dimension you want
L = self.L
# Mu is (K, p) matrix, Pi is (K, 1)
mu = np.sum(Pi * Mu, axis=0)
B = np.zeros((p, p))
for k in range(K):
# vector @ vector equal scalar, use vector[:, None] to transform to matrix
# vec[:, None] equal to vec.reshape((1, vec.shape[0]))
B = B + Pi[k]*((Mu[k] - mu)[:, None] @ ((Mu[k] - mu)[None, :]))
# Be careful, the `eigh` method get the eigenvalues in ascending , which is opposite to R.
Dw, Uw = LA.eigh(W)
# reverse the Dw_ and Uw
Dw = Dw[::-1]
Uw = np.fliplr(Uw)
W_half = self.math.pinv(np.diagflat(Dw**0.5) @ Uw.T)
B_star = W_half.T @ B @ W_half
D_, V = LA.eigh(B_star)
# reverse V
V = np.fliplr(V)
# overwrite `self.A` so that we can reuse `predict` method define in parent class
self.A = np.zeros((L, p))
for l in range(L):
self.A[l, :] = W_half @ V[:, l]
test_regression.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def test_eigh_build(self, level=rlevel):
# Ticket 662.
rvals = [68.60568999, 89.57756725, 106.67185574]
cov = array([[77.70273908, 3.51489954, 15.64602427],
[3.51489954, 88.97013878, -1.07431931],
[15.64602427, -1.07431931, 98.18223512]])
vals, vecs = linalg.eigh(cov)
assert_array_almost_equal(vals, rvals)
test_linalg.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def test_types(self):
def check(dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
w, v = np.linalg.eigh(x)
assert_equal(w.dtype, get_real_dtype(dtype))
assert_equal(v.dtype, dtype)
for dtype in [single, double, csingle, cdouble]:
yield check, dtype
test_linalg.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def test_invalid(self):
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
assert_raises(ValueError, np.linalg.eigh, x, "lower")
assert_raises(ValueError, np.linalg.eigh, x, "upper")
def __newgammaD(self, theta, l):
""" Apply Eqns. 22-24 in Vidal 2003 to update gamma^D
(gamma of the next qbit).
"""
rhoDK = self.__rhoDK(theta, self.coefs[l-1].lam)
#diagonalize
idx = self.chi * self.hdim
rhoDKflat = rhoDK.reshape([idx, idx])
evals, evecs = la.eigh(rhoDKflat) #note rho is a density matrix and thus
#hermitian
evals = evals[:self.chi]
evecs = evecs[:,:self.chi]
return evecs
def test_eigh_build(self, level=rlevel):
# Ticket 662.
rvals = [68.60568999, 89.57756725, 106.67185574]
cov = array([[77.70273908, 3.51489954, 15.64602427],
[3.51489954, 88.97013878, -1.07431931],
[15.64602427, -1.07431931, 98.18223512]])
vals, vecs = linalg.eigh(cov)
assert_array_almost_equal(vals, rvals)
def test_types(self):
def check(dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
w, v = np.linalg.eigh(x)
assert_equal(w.dtype, get_real_dtype(dtype))
assert_equal(v.dtype, dtype)
for dtype in [single, double, csingle, cdouble]:
yield check, dtype
def test_invalid(self):
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
assert_raises(ValueError, np.linalg.eigh, x, "lower")
assert_raises(ValueError, np.linalg.eigh, x, "upper")
def plot_ellipsoid(self):
q = 0.60
r = ops.get_ellipse_rad(q)
H = ops.get_hessian(self.X)
eigv, rotation = la.eigh(H)
center = self.Bh
u = np.linspace(0.0, 2.0 * np.pi, 100)
v = np.linspace(0.0, np.pi, 100)
x = (r/math.sqrt(eigv[0])) * np.outer(np.cos(u), np.sin(v))
y = (r/math.sqrt(eigv[1])) * np.outer(np.sin(u), np.sin(v))
z = (r/math.sqrt(eigv[2])) * np.outer(np.ones_like(u), np.cos(v))
ux = (r/math.sqrt(eigv[0]))* np.outer(np.cos(u), np.sin(v))
uy = (r/math.sqrt(eigv[1])) * np.outer(np.sin(u), np.sin(v))
uz = (r/math.sqrt(eigv[2])) * np.outer(np.ones_like(u), np.cos(v))
for i in range(len(x)):
for j in range(len(x)):
[x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center
# plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y,z, rstride=2, cstride=5, color='g', alpha=0.5)
ax.plot_surface(ux, uy, uz, rstride=2, cstride=5, color='r', alpha=0.5)
plt.axis('equal')
plt.show()
def pca_fit(X, var_ratio=1, return_transform=True):
"""
Parameters
----------
X : array_like
An array of data samples with shape (n_samples, n_features).
var_ratio : float
The variance ratio to be captured (Default value = 1).
return_transform : bool
Whether to apply the transformation to the given data.
Returns
-------
array_like
If return_transform is True, an array with shape (n_samples, n_components) which is the input samples projected
onto `n_components` principal components. Otherwise the first `n_components` eigenvectors of the covariance
matrix corresponding to the `n_components` largest eigenvalues are returned as rows.
"""
cov_ = np.cov(X, rowvar=False) # Mean is removed
evals, evecs = LA.eigh(cov_) # Get eigenvalues in ascending order, eigenvectors in columns
evecs = np.fliplr(evecs) # Flip eigenvectors to get them in descending eigenvalue order
if var_ratio == 1:
L = evecs.T
else:
evals = np.flip(evals, axis=0)
var_exp = np.cumsum(evals)
var_exp = var_exp / var_exp[-1]
n_components = np.argmax(np.greater_equal(var_exp, var_ratio))
L = evecs.T[:n_components] # Set the first n_components eigenvectors as rows of L
if return_transform:
return X.dot(L.T)
else:
return L
def test_eigh_build(self, level=rlevel):
# Ticket 662.
rvals = [68.60568999, 89.57756725, 106.67185574]
cov = array([[77.70273908, 3.51489954, 15.64602427],
[3.51489954, 88.97013878, -1.07431931],
[15.64602427, -1.07431931, 98.18223512]])
vals, vecs = linalg.eigh(cov)
assert_array_almost_equal(vals, rvals)
def test_types(self):
def check(dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
w, v = np.linalg.eigh(x)
assert_equal(w.dtype, get_real_dtype(dtype))
assert_equal(v.dtype, dtype)
for dtype in [single, double, csingle, cdouble]:
yield check, dtype
def test_invalid(self):
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
assert_raises(ValueError, np.linalg.eigh, x, "lower")
assert_raises(ValueError, np.linalg.eigh, x, "upper")
def _get_whitening_matrix(self):
Xcov = numpy.dot(self.silences.T, self.silences)/self.silences.shape[0]
d,V = eigh(Xcov)
D = numpy.diag(1./numpy.sqrt(d + self.fudge))
self.whitening_matrix = numpy.dot(numpy.dot(V,D), V.T).astype(numpy.float32)
def __init__(self, ctr, am):
self.n = len(ctr) # dimension
self.ctr = np.array(ctr) # center coordinates
self.am = np.array(am) # precision matrix (inverse of covariance)
# Volume of ellipsoid is the volume of an n-sphere divided
# by the (determinant of the) Jacobian associated with the
# transformation, which by definition is the precision matrix.
self.vol = vol_prefactor(self.n) / np.sqrt(linalg.det(self.am))
# The eigenvalues (l) of `a` are (a^-2, b^-2, ...) where
# (a, b, ...) are the lengths of principle axes.
# The eigenvectors (v) are the normalized principle axes.
l, v = linalg.eigh(self.am)
if np.all((l > 0.) & (np.isfinite(l))):
self.axlens = 1. / np.sqrt(l)
else:
raise ValueError("The input precision matrix defining the "
"ellipsoid {0} is apparently singular with "
"l={1} and v={2}.".format(self.am, l, v))
# Scaled eigenvectors are the axes, where `axes[:,i]` is the
# i-th axis. Multiplying this matrix by a vector will transform a
# point in the unit n-sphere to a point in the ellipsoid.
self.axes = np.dot(v, np.diag(self.axlens))
# Amount by which volume was increased after initialization (i.e.
# cumulative factor from `scale_to_vol`).
self.expand = 1.
def test_eigh_build(self, level=rlevel):
# Ticket 662.
rvals = [68.60568999, 89.57756725, 106.67185574]
cov = array([[77.70273908, 3.51489954, 15.64602427],
[3.51489954, 88.97013878, -1.07431931],
[15.64602427, -1.07431931, 98.18223512]])
vals, vecs = linalg.eigh(cov)
assert_array_almost_equal(vals, rvals)