本文整理汇总了Python中numpy.diag_indices_from方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.diag_indices_from方法的具体用法?Python numpy.diag_indices_from怎么用?Python numpy.diag_indices_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.diag_indices_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: corr_equi
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def corr_equi(k_vars, rho):
'''create equicorrelated correlation matrix with rho on off diagonal
Parameters
----------
k_vars : int
number of variables, correlation matrix will be (k_vars, k_vars)
rho : float
correlation between any two random variables
Returns
-------
corr : ndarray (k_vars, k_vars)
correlation matrix
'''
corr = np.empty((k_vars, k_vars))
corr.fill(rho)
corr[np.diag_indices_from(corr)] = 1
return corr
示例2: block_covariance
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def block_covariance(self):
"return average covariance within block"
if self._block_covariance is None:
if self.ndb <= 1: # point kriging
self._block_covariance = self.unbias
else:
cov = list()
for x1, y1, z1 in zip(self.xdb, self.ydb, self.zdb):
for x2, y2, z2 in zip(self.xdb, self.ydb, self.zdb):
# cov.append(self._cova3((x1, y1, z1), (x2, y2, z2)))
cov.append(cova3(
(x1, y1, z1), (x2, y2, z2),
self.rotmat, self.maxcov, self.nst,
self.it, self.cc, self.aa_hmax))
cov = np.array(cov).reshape((self.ndb, self.ndb))
cov[np.diag_indices_from(cov)] -= self.c0
self._block_covariance = np.mean(cov)
return self._block_covariance
示例3: diag_indices_from
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def diag_indices_from(arr):
"""
Return the indices to access the main diagonal of an n-dimensional array.
See `diag_indices` for full details.
Args:
arr (cupy.ndarray): At least 2-D.
.. seealso:: :func:`numpy.diag_indices_from`
"""
if not isinstance(arr, cupy.ndarray):
raise TypeError("Argument must be cupy.ndarray")
if not arr.ndim >= 2:
raise ValueError("input array must be at least 2-d")
# For more than d=2, the strided formula is only valid for arrays with
# all dimensions equal, so we check first.
if not cupy.all(cupy.diff(arr.shape) == 0):
raise ValueError("All dimensions of input must be of equal length")
return diag_indices(arr.shape[0], arr.ndim)
示例4: first_fit
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def first_fit(self, train_x, train_y):
""" Fit the regressor for the first time. """
train_x, train_y = np.array(train_x), np.array(train_y)
self._x = np.copy(train_x)
self._y = np.copy(train_y)
self._distance_matrix = edit_distance_matrix(self._x)
k_matrix = bourgain_embedding_matrix(self._distance_matrix)
k_matrix[np.diag_indices_from(k_matrix)] += self.alpha
self._l_matrix = cholesky(k_matrix, lower=True) # Line 2
self._alpha_vector = cho_solve(
(self._l_matrix, True), self._y) # Line 3
self._first_fitted = True
return self
示例5: do_lagrange
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def do_lagrange(ma, vb, factor):
"""
Lagrange multipliers.
Parameters
----------
ma : NumPy matrix
vb : NumPy vector
factor : float
"""
mac = copy.deepcopy(ma)
ind = np.diag_indices_from(mac)
logger.log(5, 'A:\n{}'.format(mac))
mac[ind] = mac[ind] + factor
logger.log(5, 'A:\n{}'.format(mac))
changes = solver(mac, vb)
return [('LAGRANGE F{}'.format(factor), changes)]
示例6: do_levenberg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def do_levenberg(ma, vb, factor):
"""
Lagrange multipliers.
Parameters
----------
ma : NumPy matrix
vb : NumPy vector
factor : float
"""
mac = copy.deepcopy(ma)
ind = np.diag_indices_from(mac)
mac[ind] = mac[ind] + factor
logger.log(5, 'A:\n{}'.format(mac))
changes = solver(mac, vb)
return [('LM {}'.format(factor), changes)]
示例7: _kalman_correct
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def _kalman_correct(x, P, z, H, R, gain_factor, gain_curve):
PHT = np.dot(P, H.T)
S = np.dot(H, PHT) + R
e = z - H.dot(x)
L = cholesky(S, lower=True)
inn = solve_triangular(L, e, lower=True)
if gain_curve is not None:
q = (np.dot(inn, inn) / inn.shape[0]) ** 0.5
f = gain_curve(q)
if f == 0:
return inn
L *= (q / f) ** 0.5
K = cho_solve((L, True), PHT.T, overwrite_b=True).T
if gain_factor is not None:
K *= gain_factor[:, None]
U = -K.dot(H)
U[np.diag_indices_from(U)] += 1
x += K.dot(z - H.dot(x))
P[:] = U.dot(P).dot(U.T) + K.dot(R).dot(K.T)
return inn
示例8: order_cl_pixels
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def order_cl_pixels(x_pix,y_pix):
dist = distance.cdist(np.array([x_pix,y_pix]).T,np.array([x_pix,y_pix]).T)
dist[np.diag_indices_from(dist)]=100.0
ind = np.argmin(x_pix) # select starting point on left side of image
clinds = [ind]
count = 0
while count<len(x_pix):
t = dist[ind,:].copy()
if len(clinds)>2:
t[clinds[-2]]=t[clinds[-2]]+100.0
t[clinds[-3]]=t[clinds[-3]]+100.0
ind = np.argmin(t)
clinds.append(ind)
count=count+1
x_pix = x_pix[clinds]
y_pix = y_pix[clinds]
return x_pix,y_pix
示例9: test_symmetrical_mi_nonzero
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def test_symmetrical_mi_nonzero():
# test that the MI matrix for sets of uncorrelated things results
# in zero MI
nonzero_mi_funcs = [nonzero_mi_np, nonzero_mi_ra, nonzero_mi_list]
for a, n_states in (f() for f in nonzero_mi_funcs):
mi = mutual_info.mi_matrix(a, a, n_states, n_states)
assert_almost_equal(mi[-1, -2], 0.86114, decimal=3)
mi[-1, -2] = mi[-2, -1] = 0
assert_almost_equal(np.diag(mi), 0.86114, decimal=2)
mi[np.diag_indices_from(mi)] = 0
assert_allclose(mi, 0, atol=1e-3)
示例10: test_symmetrical_mi_nonzero_int_shape_spec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def test_symmetrical_mi_nonzero_int_shape_spec():
# test that when we use an integer (rather than a list of integers)
# that we correctly assume that the integer is just repeated for all
# of the various features.
nonzero_mi_funcs = [nonzero_mi_np, nonzero_mi_ra, nonzero_mi_list]
for a, n_states in (f() for f in nonzero_mi_funcs):
mi = mutual_info.mi_matrix(a, a, 5, 5)
assert_almost_equal(mi[-1, -2], 0.86114, decimal=3)
mi[-1, -2] = mi[-2, -1] = 0
assert_almost_equal(np.diag(mi), 0.86114, decimal=2)
mi[np.diag_indices_from(mi)] = 0
assert_allclose(mi, 0, atol=1e-3)
示例11: energy_nuc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def energy_nuc(mol, charges=None, coords=None):
'''Compute nuclear repulsion energy (AU) or static Coulomb energy
Returns
float
'''
if charges is None: charges = mol.atom_charges()
if len(charges) <= 1:
return 0
#e = 0
#for j in range(len(mol._atm)):
# q2 = charges[j]
# r2 = coords[j]
# for i in range(j):
# q1 = charges[i]
# r1 = coords[i]
# r = numpy.linalg.norm(r1-r2)
# e += q1 * q2 / r
rr = inter_distance(mol, coords)
rr[numpy.diag_indices_from(rr)] = 1e200
if CHECK_GEOM and numpy.any(rr < 1e-5):
for atm_idx in numpy.argwhere(rr<1e-5):
logger.warn(mol, 'Atoms %s have the same coordinates', atm_idx)
raise RuntimeError('Ill geometry')
e = numpy.einsum('i,ij,j->', charges, 1./rr, charges) * .5
return e
示例12: inter_distance
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def inter_distance(mol, coords=None):
'''
Inter-particle distance array
'''
if coords is None: coords = mol.atom_coords()
rr = numpy.linalg.norm(coords.reshape(-1,1,3) - coords, axis=2)
rr[numpy.diag_indices_from(rr)] = 0
return rr
示例13: matrix_sign
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def matrix_sign(M):
""" The "sign" matrix of `M` """
#Notes: sign(M) defined s.t. eigvecs of sign(M) are evecs of M
# and evals of sign(M) are +/-1 or 0 based on sign of eigenvalues of M
#Using the extremely numerically stable (but expensive) Schur method
# see http://www.maths.manchester.ac.uk/~higham/fm/OT104HighamChapter5.pdf
N = M.shape[0]; assert(M.shape == (N, N)), "M must be square!"
T, Z = _spl.schur(M, 'complex') # M = Z T Z^H where Z is unitary and T is upper-triangular
U = _np.zeros(T.shape, 'complex') # will be sign(T), which is easy to compute
# (U is also upper triangular), and then sign(M) = Z U Z^H
# diagonals are easy
U[_np.diag_indices_from(U)] = _np.sign(_np.diagonal(T))
#Off diagonals: use U^2 = I or TU = UT
# Note: Tij = Uij = 0 when i > j and i==j easy so just consider i<j case
# 0 = sum_k Uik Ukj = (i!=j b/c off-diag)
# FUTURE: speed this up by using np.dot instead of sums below
for j in range(1, N):
for i in range(j - 1, -1, -1):
S = U[i, i] + U[j, j]
if _np.isclose(S, 0): # then use TU = UT
if _np.isclose(T[i, i] - T[j, j], 0): # then just set to zero
U[i, j] = 0.0 # TODO: check correctness of this case
else:
U[i, j] = T[i, j] * (U[i, i] - U[j, j]) / (T[i, i] - T[j, j]) + \
sum([U[i, k] * T[k, j] - T[i, k] * U[k, j] for k in range(i + 1, j)]) \
/ (T[i, i] - T[j, j])
else: # use U^2 = I
U[i, j] = - sum([U[i, k] * U[k, j] for k in range(i + 1, j)]) / S
return _np.dot(Z, _np.dot(U, _np.conjugate(Z.T)))
#Quick & dirty - not always stable:
#U,_,Vt = _np.linalg.svd(M)
#return _np.dot(U,Vt)
示例14: fun
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def fun(self, x):
dx, dy, dz = self._compute_coordinate_deltas(x)
with np.errstate(divide='ignore'):
dm1 = (dx**2 + dy**2 + dz**2) ** -0.5
dm1[np.diag_indices_from(dm1)] = 0
return 0.5 * np.sum(dm1)
示例15: grad
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag_indices_from [as 别名]
def grad(self, x):
dx, dy, dz = self._compute_coordinate_deltas(x)
with np.errstate(divide='ignore'):
dm3 = (dx**2 + dy**2 + dz**2) ** -1.5
dm3[np.diag_indices_from(dm3)] = 0
grad_x = -np.sum(dx * dm3, axis=1)
grad_y = -np.sum(dy * dm3, axis=1)
grad_z = -np.sum(dz * dm3, axis=1)
return np.hstack((grad_x, grad_y, grad_z))