# numpy.linalg.svd

Here are the examples of the python api numpy.linalg.svd taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

## 192 Examples

#### Example 1

Project: pygp
Source File: gplvm.py
```def PCA(Y,components):
"""run PCA, retrieving the first (components) principle components
return [s0,w0]
s0: factors
w0: weights
"""
sv = linalg.svd(Y, full_matrices = 0);
[s0,w0] = [sv[0][:,0:components], SP.dot(SP.diag(sv[1]),sv[2]).T[:,0:components]]
v = s0.std(axis=0)
s0 /= v;
w0 *= v;
return [s0,w0]
```

#### Example 2

Project: pupil
Source File: calibrate.py
```def fit_poly_surface(cal_pt_cloud,n=7):
M = make_model(cal_pt_cloud,n)
U,w,Vt = np.linalg.svd(M[:,:n],full_matrices=0)
V = Vt.transpose()
Ut = U.transpose()
pseudINV = np.dot(V, np.dot(np.diag(1/w), Ut))
cx = np.dot(pseudINV, M[:,n])
cy = np.dot(pseudINV, M[:,n+1])
# compute model error in world screen units if screen_res specified
err_x=(np.dot(M[:,:n],cx)-M[:,n])
err_y=(np.dot(M[:,:n],cy)-M[:,n+1])
return cx,cy,err_x,err_y
```

#### Example 3

Source File: lower_convex_hull.py
```def stacked_lstsq(L, b, rcond=1e-10):
"""
Solve L x = b, via SVD least squares cutting of small singular values
L is an array of shape (..., M, N) and b of shape (..., M).
Returns x of shape (..., N)
This code is necessary until stacked arrays are supported in numpy.linalg.lstsq.
Source: http://stackoverflow.com/questions/30442377/how-to-solve-many-overdetermined-systems-of-linear-equations-using-vectorized-co
"""
u, s, v = np.linalg.svd(L, full_matrices=False)
s_max = s.max(axis=-1, keepdims=True)
s_min = rcond*s_max
inv_s = np.zeros_like(s)
inv_s[s >= s_min] = 1/s[s>=s_min]
x = np.einsum('...ji,...j->...i', v,
inv_s * np.einsum('...ji,...j->...i', u, b.conj()))
return np.conj(x, x)
```

#### Example 4

Project: pymanopt
Source File: grassmann.py
```    def retr(self, X, G):
# Calculate 'thin' qr decomposition of X + G
# XNew, r = np.linalg.qr(X + G)

# We do not need to worry about flipping signs of columns here,
# since only the column space is important, not the actual
# columns. Compare this with the Stiefel manifold.

# Compute the polar factorization of Y = X+G
u, s, vt = svd(X + G, full_matrices=False)
return multiprod(u, vt)
```

#### Example 5

Project: pymanopt
Source File: grassmann.py
```    def exp(self, X, U):
u, s, vt = svd(U, full_matrices=False)
cos_s = np.expand_dims(np.cos(s), -2)
sin_s = np.expand_dims(np.sin(s), -2)

Y = (multiprod(multiprod(X, multitransp(vt) * cos_s), vt) +
multiprod(u * sin_s, vt))

# From numerical experiments, it seems necessary to
# re-orthonormalize. This is overall quite expensive.
if self._k == 1:
Y, unused = np.linalg.qr(Y)
return Y
else:
for i in range(self._k):
Y[i], unused = np.linalg.qr(Y[i])
return Y
```

#### Example 6

Project: pymanopt
Source File: grassmann.py
```    def log(self, X, Y):
ytx = multiprod(multitransp(Y), X)
At = multitransp(Y) - multiprod(ytx, multitransp(X))
Bt = np.linalg.solve(ytx, At)
u, s, vt = svd(multitransp(Bt), full_matrices=False)
arctan_s = np.expand_dims(np.arctan(s), -2)

U = multiprod(u * arctan_s, vt)
return U
```

#### Example 7

Project: RLScore
Source File: linalg.py
```def svd_economy_sized(X):
"""Returns the reduced singular value decomposition of the data matrix X so that only the singular vectors corresponding to the nonzero singular values are returned.

@param X: data matrix whose rows and columns correspond to the data and features, respectively.
@type X: numpy matrix of floats
@return: the nonzero singular values and the corresponding left and right singular vectors of X. The singular vectors are contained in a r*1-matrix, where r is the number of nonzero singular values.
@rtype: a tuple of three numpy matrices"""
evecs, svals, U = la.svd(X, full_matrices=0)
evals = np.multiply(svals, svals)

evecs = evecs[:, svals > 0]
svals = svals[svals > 0]
U = U[svals > 0]
return evecs, svals, U
```

#### Example 8

Project: cortex
Source File: tools.py
```def ortho_weight(ndim, rng=None):
'''Make ortho weight tensor.

'''
if not rng:
rng = rng_
W = rng.randn(ndim, ndim)
u, s, v = np.linalg.svd(W)
return u.astype('float32')
```

#### Example 9

Project: attention-lvcsr
Source File: test_nlinalg.py
```def test_svd():
rng = numpy.random.RandomState(utt.fetch_seed())
A = tensor.matrix("A", dtype=theano.config.floatX)
U, V, T = svd(A)
fn = function([A], [U, V, T])
a = rng.rand(4, 4).astype(theano.config.floatX)
n_u, n_v, n_t = numpy.linalg.svd(a)
t_u, t_v, t_t = fn(a)

assert _allclose(n_u, t_u)
assert _allclose(n_v, t_v)
assert _allclose(n_t, t_t)
```

#### Example 10

Project: lfd
Source File: svds.py
```def svds_slow(x_k33):
s2,u2,v2 = [],[],[]
for x_33 in x_k33:
u,s,vt = np.linalg.svd(x_33)
s2.append(s)
u2.append(u)
v2.append(vt)
s2 = np.array(s2)
u2 = np.array(u2)
v2 = np.array(v2)
return u2,s2,v2
```

#### Example 11

Project: empca
Source File: empca.py
```def classic_pca(data, nvec=None):
"""
Perform classic SVD-based PCA of the data[obs, var].

Returns Model object
"""
u, s, v = N.linalg.svd(data)
if nvec is None:
m = Model(v, data, N.ones(data.shape))
else:
m = Model(v[0:nvec], data, N.ones(data.shape))
return m
```

#### Example 12

```def test_make_low_rank_matrix():
X = make_low_rank_matrix(n_samples=50, n_features=25, effective_rank=5,
tail_strength=0.01, random_state=0)

assert_equal(X.shape, (50, 25), "X shape mismatch")

from numpy.linalg import svd
u, s, v = svd(X)
assert_less(sum(s) - 5, 0.1, "X rank is not approximately 5")
```

#### Example 13

Project: scikit-rf
Source File: mathFunctions.py
```def null(A, eps=1e-15):
'''
calculates the null space of matrix A.
i found this on stack overflow.
'''
u, s, vh = npy.linalg.svd(A)
null_space = npy.compress(s <= eps, vh, axis=0)
return null_space.T
```

#### Example 14

Project: scot
Source File: pca.py
```def pca_svd(x):
"""Calculate PCA using SVD.

Parameters
----------
x : ndarray, shape (channels, samples)
Two-dimensional input data.

Returns
-------
w : ndarray, shape (channels, channels)
Eigenvectors (principal components) (in columns).
s : ndarray, shape (channels,)
Eigenvalues.
"""
w, s, _ = np.linalg.svd(x, full_matrices=False)
return w, s ** 2
```

#### Example 15

Project: statsmodels
Source File: pca.py
```    def _compute_using_svd(self):
"""SVD method to compute eigenvalues and eigenvecs"""
x = self.transformed_data
u, s, v = np.linalg.svd(x)
self.eigenvals = s ** 2.0
self.eigenvecs = v.T
```

#### Example 16

Project: statsmodels
Source File: linalg_decomp_1.py
```    def __init__(self, data=None, sym=None):
super(SvdArray, self).__init__(data=data, sym=sym)

u, s, v = np.linalg.svd(self.x, full_matrices=1)
self.u, self.s, self.v = u, s, v
self.sdiag = linalg.diagsvd(s, *x.shape)
self.sinvdiag = linalg.diagsvd(1./s, *x.shape)
```

#### Example 17

Project: statsmodels
Source File: utils_old.py
```def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.

If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.

"""

if r is None:
r = rank(X)

V, D, U = L.svd(X, full_matrices=0)
order = np.argsort(D)
order = order[::-1]
value = []
for i in range(r):
value.append(V[:,order[i]])
return np.asarray(np.transpose(value)).astype(np.float64)
```

#### Example 18

Project: statsmodels
Source File: tools.py
```def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.

If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.

"""

if r is None:
r = np_matrix_rank(X)

V, D, U = L.svd(X, full_matrices=0)
order = np.argsort(D)
order = order[::-1]
value = []
for i in range(r):
value.append(V[:, order[i]])
return np.asarray(np.transpose(value)).astype(np.float64)
```

#### Example 19

Project: pyscf
Source File: numpy_helper.py
```def solve_lineq_by_SVD(a, b):
''' a * x = b '''
t, w, vH = numpy.linalg.svd(a)
idx = []
for i,wi in enumerate(w):
if wi > LINEAR_DEP_THRESHOLD:
idx.append(i)
if idx:
idx = numpy.array(idx)
tb = numpy.dot(numpy.array(t[:,idx]).T.conj(), numpy.array(b))
x = numpy.dot(numpy.array(vH[idx,:]).T.conj(), tb / w[idx])
else:
x = numpy.zeros_like(b)
return x
```

#### Example 20

Project: histwords
Source File: alignment.py
```def get_procrustes_mat(base_embed, other_embed):
in_base_embed, in_other_embed = intersection_align(base_embed, other_embed, post_normalize=False)
base_vecs = in_base_embed.m
other_vecs = in_other_embed.m
m = other_vecs.T.dot(base_vecs)
u, _, v = np.linalg.svd(m)
ortho = u.dot(v)
return ortho
```

#### Example 21

Project: histwords
Source File: alignment.py
```def smart_procrustes_align(base_embed, other_embed, post_normalize=True):
in_base_embed, in_other_embed = intersection_align(base_embed, other_embed, post_normalize=False)
base_vecs = in_base_embed.m
other_vecs = in_other_embed.m
m = other_vecs.T.dot(base_vecs)
u, _, v = np.linalg.svd(m)
ortho = u.dot(v)
return Embedding((other_embed.m).dot(ortho), other_embed.iw, normalize = post_normalize)
```

#### Example 22

Project: histwords
Source File: alignment.py
```def procrustes_align(base_embed, other_embed):
"""
Align other embedding to base embeddings via Procrustes.
Returns best distance-preserving aligned version of other_embed
NOTE: Assumes indices are aligned
"""
basevecs = base_embed.m - base_embed.m.mean(0)
othervecs = other_embed.m - other_embed.m.mean(0)
m = othervecs.T.dot(basevecs)
u, _, v = np.linalg.svd(m)
ortho = u.dot(v)
fixedvecs = othervecs.dot(ortho)
return Embedding(fixedvecs, other_embed.iw)
```

#### Example 23

Project: LasagneNLP
Source File: nlinalg.py
```    def perform(self, node, inputs, outputs, params=None):
# MAX = 10000.
# MIN = -10000.
try:
(x,) = inputs
(z,) = outputs
s = numpy.linalg.svd(x, compute_uv=False)
log_abs_det = numpy.sum(numpy.log(numpy.abs(s)))
# numpy.clip(log_abs_det, MIN, MAX)
z[0] = numpy.asarray(log_abs_det, dtype=x.dtype)
except Exception:
print('Failed to compute logabsdet of {}.'.format(x))
raise
```

#### Example 24

Project: arctic-capgen-vid
Source File: common.py
```def ortho_weight(ndim):
"""
Random orthogonal weights, we take
the right matrix in the SVD.

Remember in SVD, u has the same # rows as W
and v has the same # of cols as W. So we
are ensuring that the rows are
orthogonal.
"""
W = rng_numpy.randn(ndim, ndim)
u, _, _ = numpy.linalg.svd(W)
return u.astype('float32')
```

#### Example 25

Project: orange
Source File: orngDimRed.py
```    def __init__(self, data, components=1):
(u,d,v) = LinearAlgebra.svd(data)
self.variance = d               # principal components' variance
self.factors = v                # the principal basis
d2 = numpy.power(d,2)
s = numpy.sum(d2)
if s > 1e-6:
s = d2/s
else:
s = 1.0
self.R_squared = s # percentage of total variance explained by individual components
```

#### Example 26

Project: orange
Source File: pls.py
```def svd_xy(X, Y):
""" Return the first left and right singular
vectors of X'Y.

:param X, Y: data matrix
:type X, Y: :class:`numpy.array`

"""
U, s, V = svd(dot(X.T, Y), full_matrices=False)
u = U[:, [0]]
v = V.T[:, [0]]
return u, v
```

#### Example 27

Project: horus
Source File: laser_segmentation.py
```        def fit(self, data):
data_mean = data.mean(axis=0)
x0, y0 = data_mean
if data.shape[0] > 2:  # over determined
u, v, w = np.linalg.svd(data - data_mean)
vec = w[0]
theta = math.atan2(vec[0], vec[1])
elif data.shape[0] == 2:  # well determined
theta = math.atan2(data[1, 0] - data[0, 0], data[1, 1] - data[0, 1])
theta = (theta + math.pi * 5 / 2) % (2 * math.pi)
d = x0 * math.sin(theta) + y0 * math.cos(theta)
return d, theta
```

#### Example 28

Project: horus
Source File: laser_triangulation.py
```    def fit(self, X):
M, Xm = self._compute_m(X)
# U = linalg.svds(M, k=2)[0]
# normal = np.cross(U.T[0], U.T[1])
normal = numpy.linalg.svd(M)[0][:, 2]
if normal[2] < 0:
normal *= -1
dist = np.dot(normal, Xm)
return dist, normal, M
```

#### Example 29

Project: GLRM
Source File: pca_test.py
```def PCA(A, k):
mean_A = tile(A.mean(0), (A.shape[0],1))
A0 = A - mean_A

u, s, v = svd(A0, full_matrices = False)
u, s, v = u[:,:k], diag(sqrt(s[:k])), v[:k,:]
X = hstack((u.dot(s), ones((m,1))))
Y = vstack((s.dot(v), A.mean(0)))

return X, Y
```

#### Example 30

Project: eulerian-audio-magnification
Source File: svd.py
```    def __init__(self, spectrogram=None, filename=None):
if spectrogram is None and filename is None:
print "Must specify either spectrogram or filename"
exit(0)
elif spectrogram is not None and filename is not None:
print "Can't specify both spectrogram and filename"
exit(0)
elif spectrogram is not None:
(self.left, self.sv, self.right) = np.linalg.svd(spectrogram.data, full_matrices=False)
self.params = spectrogram.params
else:
f = open(filename, "rb")
f.close()
```

#### Example 31

```def svd_truncation(spectrogram, k=[0]):
"""Compute SVD of the spectrogram, trunate to *k* components,
reconstitute a new spectrogram."""
# SVD of the spectrogram:
#   u.shape == (num_windows, k)
#   s.shape == (k, k)
#   v.shape == (k, n)
# where
#   k == min(num_windows, n)
(left, sv, right) = np.linalg.svd(spectrogram, full_matrices=False)
zero_out = np.array([i for i in xrange(sv.size) if i not in k])
if zero_out.size:
sv[zero_out] = 0.0
truncated = np.dot(left, sv[:, np.newaxis] * right)
return truncated
```

#### Example 32

Project: APGL
Source File: Util.py
```    @staticmethod
def rank(A, tol=1e-8):
"""
Kindly borrowed from the following forum thread:
http://mail.scipy.org/pipermail/numpy-discussion/2008-February/031218.html
"""
s = numpy.linalg.svd(A, compute_uv=False)
return numpy.sum(numpy.where(s>tol, 1, 0))
```

#### Example 33

Project: cvxpy
Source File: norm_nuc.py
```    def _grad(self, values):
"""Gives the (sub/super)gradient of the atom w.r.t. each argument.

Matrix expressions are vectorized, so the gradient is a matrix.

Args:
values: A list of numeric values for the arguments.

Returns:
A list of SciPy CSC sparse matrices or None.
"""
U, _, V = np.linalg.svd(values[0])
D = U.dot(V)
return [sp.csc_matrix(D.A.ravel(order='F')).T]
```

#### Example 34

Project: STAMP
Source File: PCA.py
```def _pca_svd(data):
u, s, vt = numpy.linalg.svd(data, full_matrices = 0)
pcs = vt
data_count = len(data)
variances = s**2 / data_count
root_data_count = numpy.sqrt(data_count)
stds = s / root_data_count
positions =	u * s
norm_positions = u * root_data_count
return pcs, variances, stds, positions, norm_positions
```

#### Example 35

Project: tractor
Source File: ellipses.py
```    @staticmethod
def fromCovariance(cov):
u,s,v = np.linalg.svd(cov)
r = np.sqrt(s[0])
ab = np.sqrt(s[1] / s[0])
return EllipseE.fromRAbPhi(r, ab, -theta)
```

#### Example 36

Project: conceptors
Source File: net.py
```  def compute_projector(self,
R,
alpha=10):
"""
Compute projector (conceptor)

@param R: state correlation matrix
@param alpha: a designed parameter: aperture
"""

U,S,_=np.linalg.svd(R);
S_new=(np.diag(S).dot(np.linalg.inv(np.diag(S)+alpha**(-2)*np.eye(self.num_neuron))))

C=U.dot(S_new).dot(U.T);

self.Cs[0].append(C);
self.Cs[1].append(U);
self.Cs[2].append(np.diag(S_new));
self.Cs[3].append(S);
```

#### Example 37

Project: pyunlocbox
Source File: functions.py
```    def _prox(self, x, T):
# Gamma is T in the matlab UNLocBox implementation.
gamma = self.lambda_ * T
# TODO: take care of sparse matrices.
U, s, V = np.linalg.svd(x)
s = _soft_threshold(s, gamma)
S = np.diag(s)
return np.dot(U, np.dot(S, V))
```

#### Example 38

Project: pycortex
Source File: svgroi.py
```def _labelpos(pts):
if pts.ndim < 3:
return _center_pts(pts)

ptm = pts.copy().astype(float)
ptm -= ptm.mean(0)
u, s, v = np.linalg.svd(ptm, full_matrices=False)
sp = np.diag(s)
sp[-1,-1] = 0
try:
x, y = _center_pts(np.dot(ptm, np.dot(v.T, sp))[:,:2])
except Exception as e:
print(e)

sp = np.diag(1./(s+np.finfo(float).eps))
pt = np.dot(np.dot(np.array([x,y,0]), sp), v)
return pt + pts.mean(0)
```

#### Example 39

Project: pyglmnet
Source File: utils.py
```def tikhonov_from_prior(PriorCov, n_samples):
"""Given a prior covariance matrix, returns a Tikhonov matrix"""
[U, S, V] = np.linalg.svd(PriorCov, full_matrices=False)
Tau = np.dot(np.diag(1. / np.sqrt(S)), U)
Tau = 1. / np.sqrt(np.float(n_samples)) * Tau / Tau.max()
return Tau
```

#### Example 40

Project: robothon
Source File: test_linalg.py
```    def do(self, a, b):
u, s, vt = linalg.svd(a, 0)
x, residuals, rank, sv = linalg.lstsq(a, b)
assert_almost_equal(b, dot(a, x))
assert_equal(rank, asarray(a).shape[0])
assert_almost_equal(sv, sv.__array_wrap__(s))
assert imply(isinstance(b, matrix), isinstance(x, matrix))
assert imply(isinstance(b, matrix), isinstance(residuals, matrix))
```

#### Example 41

Project: robothon
Source File: test_regression.py
```    def test_svd_build(self, level = rlevel):
"""Ticket 627."""
a = array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]])
m, n = a.shape
u, s, vh = linalg.svd(a)

b = dot(transpose(u[:, n:]), a)

assert_array_almost_equal(b, np.zeros((2, 2)))
```

#### Example 42

```    def decompose(self, features): # features are of dimension NUMVOXELSxNUMFEATURES
# sanity checks
self.numComponents = self.checkNumComponents(features.shape[1], self.numComponents)

# use singular value decomposition (SVD)
meanData = self.meanData(features)
features_centered = features - meanData

U,s,Vh = numpy.linalg.svd(features_centered, full_matrices=False)
ZV = (U*s).T #equivalent: numpy.dot(Vh, features.T)
FZ = Vh
# preselect components
ZV = ZV[range(0, self.numComponents), :]
FZ = FZ[:, range(0, self.numComponents)]
return FZ, ZV
```

#### Example 43

```def objective(X_1, g_2, X_2, g_3, X_3):
"""
Objective function for Robust PCA:
Noise - squared frobenius norm (makes X_i small)
Background - nuclear norm (makes X_i low rank)
Foreground - entrywise L1 norm (makes X_i small)
"""
tmp = svd(X_3,compute_uv=0)
tmp = tmp.reshape((len(tmp),1))
return norm(X_1,'fro')**2 + g_2*norm(hstack(X_2),1) + g_3*norm(tmp,1)
```

#### Example 44

```def objective(X_1, g_2, X_2, g_3, X_3):
"""
Objective function for Robust PCA:
Noise - squared frobenius norm (makes X_i small)
Background - nuclear norm (makes X_i low rank)
Foreground - entrywise L1 norm (makes X_i small)
"""
tmp = svd(X_3,compute_uv=0)
tmp = tmp.reshape((len(tmp),1))
return norm(X_1,'fro')**2 + g_2*norm(hstack(X_2),1) + g_3*norm(tmp,1)
```

#### Example 45

Project: rapprentice
Source File: svds.py
```def svds_slow(x_k33):
s2,u2,v2 = [],[],[]
for x_33 in x_k33:
u,s,vt = np.linalg.svd(x_33)
s2.append(s)
u2.append(u)
v2.append(vt)
s2 = np.array(s2)
u2 = np.array(u2)
v2 = np.array(v2)
return u2,s2,v2
```

#### Example 46

Project: pyLAR
Source File: op.py
```def __iter_L(L, epsilon):
"""Helper for opursuit(...).
"""
U,S,V = np.linalg.svd(L, full_matrices=False)
S = np.diag(S)
for i in range(0,np.amin(S.shape)):
if S[i,i]>epsilon :
S[i,i] = S[i,i] - epsilon
elif S[i,i]<-epsilon:
S[i,i] = S[i,i] + epsilon
else:
S[i,i] = 0
return np.mat(U)*np.mat(S)*np.mat(V)
```

#### Example 47

Project: pyLAR
Source File: op.py
```def __iter_L(L, epsilon):
"""Helper for opursuit(...).
"""
U,S,V = np.linalg.svd(L, full_matrices=False)
S = np.diag(S)
for i in range(0,np.amin(S.shape)):
if S[i,i]>epsilon :
S[i,i] = S[i,i] - epsilon
elif S[i,i]<-epsilon:
S[i,i] = S[i,i] + epsilon
else:
S[i,i] = 0
return np.mat(U)*np.mat(S)*np.mat(V)
```

#### Example 48

Project: regreg
Source File: svd_norms.py
```    def compute_and_store_svd(self, X):
"""
Compute and store svd of X for use in multiple function calls.
"""
self._md5x = md5(X).hexdigest()
self._X = X
self.SVD = np.linalg.svd(X, full_matrices=0)
return self.SVD
```

#### Example 49

Project: regreg
Source File: svd_norms.py
```    def compute_and_store_svd(self, X):
"""
Compute and store svd of X for use in multiple function calls.
"""
self._md5x = md5(X).hexdigest()
self._X = X
self.SVD = np.linalg.svd(X, full_matrices=0)
return self.SVD
```

#### Example 50

Project: Conceptor
Source File: reservoir.py
```    def compute_projector(self,
R,
alpha = 10):
"""
Compute projector (conceptor matrix)

@param R: network state correlation matrix
@param alpha: aperture
"""

U, S, _ = np.linalg.svd(R)
S_new = (np.diag(S).dot(np.linalg.inv(np.diag(S) + alpha ** (-2) * np.eye(self.size_net))))

C = U.dot(S_new).dot(U.T)

self.Cs[0].append(C)
self.Cs[1].append(U)
self.Cs[2].append(np.diag(S_new))
self.Cs[3].append(S)
```