Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
np.random.seed(0)
mask = np.ones([size, size], dtype=np.bool)
coef = np.zeros((size, size))
coef[0:roi_size, 0:roi_size] = -1.
coef[-roi_size:, -roi_size:] = 1.
X = np.random.randn(n_samples, size**2)
for x in X: # smooth data
x[:] = ndimage.gaussian_filter(x.reshape(size, size), sigma=1.0).ravel()
X -= X.mean(axis=0)
X /= X.std(axis=0)
y = np.dot(X, coef.ravel())
noise = np.random.randn(y.shape[0])
noise_coef = (linalg.norm(y, 2) / np.exp(snr / 20.)) / linalg.norm(noise, 2)
y += noise_coef * noise # add noise
###############################################################################
# Hierarchical clustering
A = grid_to_graph(n_x=size, n_y=size)
hc = hierarchical_clustering.HierarchicalClustering(clf, A)
time1 = clock()
tab = hc.fit(X, y, n_iterations, verbose=1)
time2 = clock()
execution_time = (time2 -time1)
# Plotting the result
# Computing an array of the fitted coefs
tab2 = tab.copy()
coefs=hc.coef_
for i in np.unique(tab):
D = eyecolumn(n,np.s_[m:])
C = sp.linalg.qr(2*np.random.rand(n,n-m) - 1,mode='economic')[0]
evals , V = sp.linalg.eig(np.c_[A,C])
K = np.linalg.cond(V)
X = V[:m,:]
Y = V[m:,:]
upp0 = [0]*n
for x in range(n):
upp0[x] = sp.linalg.norm( (C-evals[x]*D).dot(Y[:,x])
) / sp.linalg.norm(X[:,x])
f = np.argsort(upp0)[0]
e_f = evals[f]
upper1 = upp0[f]
upper2 = sp.linalg.svdvals(A - e_f*B)[-1]
lower0 = upper2/(K+1)
radius = upper2*K
return upper2 , upper1 , lower0 , e_f , radius
from scipy import linalg
self._standardized_forecasts_error = np.zeros(
self.forecasts_error.shape, dtype=self.dtype)
for t in range(self.forecasts_error_cov.shape[2]):
if self.nmissing[t] > 0:
self._standardized_forecasts_error[:, t] = np.nan
if self.nmissing[t] < self.k_endog:
mask = ~self.missing[:, t].astype(bool)
F = self.forecasts_error_cov[np.ix_(mask, mask, [t])]
try:
upper, _ = linalg.cho_factor(F[:, :, 0])
self._standardized_forecasts_error[mask, t] = (
linalg.solve_triangular(
upper, self.forecasts_error[mask, t],
trans=1))
except linalg.LinAlgError:
self._standardized_forecasts_error[mask, t] = (
np.nan)
return self._standardized_forecasts_error
solve_func = lambda b : linalg.solve(matrix, b)
handle_pairs = np.zeros((2*num_handles, dim))
def nowarp_template(X, smoothness_scale, l2_scale, loss='quadratic'):
"""
Solves for the optimal template assuming no warping.
"""
K, T, N = X.shape
if loss == 'quadratic':
A = _diff_gramian(T, smoothness_scale * K, l2_scale * K)
A[-1] += K
B = np.sum(X, axis=0)
return sci.linalg.solveh_banded(A, B)
else:
raise NotImplementedError
def lu_factor(cls, A, out = None):
"""
univariate Taylor arithmetic of scipy.linalg.lu_factor
"""
D,P,N = A.data.shape[:3]
if out is None:
LU = A.zeros_like()
PIV = cls(numpy.zeros((D,P,N))) # permutation
for p in range(P):
# D = 0
lu, piv = scipy.linalg.lu_factor(A.data[0,p])
w = algopy.utils.piv2mat(piv)
LU.data[0,p] = lu
PIV.data[0,p] = piv
L0 = numpy.tril(lu, -1) + numpy.eye(N)
U0 = numpy.triu(lu, 0)
# allocate temporary storage
L0inv = numpy.linalg.inv(L0)
U0inv = numpy.linalg.inv(U0)
dF = numpy.zeros((N,N),dtype=float)
for d in range(1,D):
dF *= 0
for i in range(1,d):
def get_entropy(self):
'''Computes the von Neumann Entropy as S = -tr( Ai * log(Ai) ) where Ai is the vector
of eigenvalues of Tij.'''
Ai, _ = scipy.linalg.eigh(self.Tij)
if not self.qc.mo_spec.spinpolarized:
Ai /= 2
Ai = Ai[numpy.where(Ai > 0)]
return -1 * sum(Ai * numpy.log(Ai))
def _check_central(mps, n):
print("Check central: ", n)
mps = cp.deepcopy(mps)
mps.calc_l()
#mps.simple_renorm()
mps.calc_r()
nums = []
errs = []
for m in range(0, n):
err = la.norm(mps.l[m] - sp.eye(mps.l[m].shape[0]))
if err > 1e-6:
#if m == 0:
# print mps.l[0]
nums.append(m)
errs.append(err)
for m in range(n, mps.N + 1):
err = la.norm(mps.r[m] - sp.eye(mps.r[m].shape[0]))
if err > 1e-6:
nums.append(m)
errs.append(err)
print(nums)
print(errs)
def _fit_ellipsoid_partial(locations, cy):
"""identify only 5 ellipsoid parameters (y-center determined by e.g. Cz)"""
a = np.vstack([locations[:, 0]**2,
locations[:, 1]**2 - 2 * locations[:, 1] * cy,
locations[:, 2]**2,
locations[:, 0]*2,
locations[:, 2]*2]).T
x = sp.linalg.lstsq(a, np.ones(locations.shape[0]))[0]
c = [-x[3] / x[0], cy, -x[4] / x[2]]
gam = 1 + x[3]**2 / x[0] + x[4]**2 / x[2]
r = np.sqrt([gam / x[0], gam / x[1], gam / x[2]])
return c, r
def _golub_welsch(orders, coeff1, coeff2):
"""Recurrence coefficients to abscisas and weights."""
abscisas, weights = [], []
for dim, order in enumerate(orders):
if order:
bands = numpy.zeros((2, order))
bands[0] = coeff1[dim, :order]
bands[1, :-1] = numpy.sqrt(coeff2[dim, 1:order])
vals, vecs = scipy.linalg.eig_banded(bands, lower=True)
abscisa, weight = vals.real, vecs[0, :]**2
indices = numpy.argsort(abscisa)
abscisa, weight = abscisa[indices], weight[indices]
else:
abscisa, weight = numpy.array([coeff1[dim, 0]]), numpy.array([1.])
abscisas.append(abscisa)
weights.append(weight)
return abscisas, weights