本文整理汇总了Python中autograd.numpy.eye方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.eye方法的具体用法?Python numpy.eye怎么用?Python numpy.eye使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.eye方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_model_params
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def init_model_params(Dx, Dy, alpha, r, obs, rs = npr.RandomState(0)):
mu0 = np.zeros(Dx)
Sigma0 = np.eye(Dx)
A = np.zeros((Dx,Dx))
for i in range(Dx):
for j in range(Dx):
A[i,j] = alpha**(abs(i-j)+1)
Q = np.eye(Dx)
C = np.zeros((Dy,Dx))
if obs == 'sparse':
C[:Dy,:Dy] = np.eye(Dy)
else:
C = rs.normal(size=(Dy,Dx))
R = r * np.eye(Dy)
return (mu0, Sigma0, A, Q, C, R)
示例2: central
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def central(f0, ds, w):
"""Apply central difference method to estimate derivatives."""
f = lambda o: shift(f0, o)
eye = np.eye(f0.ndim, dtype=int)
offsets = [-eye[d] for d in ds]
if not ds:
return f0
elif len(ds) == 1: # First order derivatives.
i = offsets[0]
return (f(i) - f(-i)) / (2 * w)
elif len(ds) == 2: # Second order derivatives.
i, j = offsets
w2 = np.square(w)
if ds[0] == ds[1]: # d^2/dxdx
return (f(i) - 2 * f0 + f(-i)) / w2
else: # d^2/dxdy
return (f(i + j) - f(i - j) - f(j - i) + f(-i - j)) / (4 * w2)
else:
raise NotImplementedError(ds)
示例3: __init__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def __init__(self, generate_scalar, matrix_class):
rng = np.random.RandomState(SEED)
matrix_pairs = {}
for sz in SIZES:
scalar = generate_scalar(rng)
matrix_pairs[sz] = (
matrix_class(scalar, sz), scalar * np.identity(sz))
if AUTOGRAD_AVAILABLE:
def param_func(param, matrix):
return param * anp.eye(matrix.shape[0])
def get_param(matrix):
return matrix._scalar
else:
param_func, get_param = None, None
super().__init__(
matrix_pairs, get_param, param_func, rng)
示例4: fit_gaussian_draw
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def fit_gaussian_draw(X, J, seed=28, reg=1e-7, eig_pow=1.0):
"""
Fit a multivariate normal to the data X (n x d) and draw J points
from the fit.
- reg: regularizer to use with the covariance matrix
- eig_pow: raise eigenvalues of the covariance matrix to this power to construct
a new covariance matrix before drawing samples. Useful to shrink the spread
of the variance.
"""
with NumpySeedContext(seed=seed):
d = X.shape[1]
mean_x = np.mean(X, 0)
cov_x = np.cov(X.T)
if d==1:
cov_x = np.array([[cov_x]])
[evals, evecs] = np.linalg.eig(cov_x)
evals = np.maximum(0, np.real(evals))
assert np.all(np.isfinite(evals))
evecs = np.real(evecs)
shrunk_cov = evecs.dot(np.diag(evals**eig_pow)).dot(evecs.T) + reg*np.eye(d)
V = np.random.multivariate_normal(mean_x, shrunk_cov, J)
return V
示例5: gmm_sample
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def gmm_sample(self, mean=None, w=None, N=10000,n=10,d=2,seed=10):
np.random.seed(seed)
self.d = d
if mean is None:
mean = np.random.randn(n,d)*10
if w is None:
w = np.random.rand(n)
w = old_div(w,sum(w))
multi = np.random.multinomial(N,w)
X = np.zeros((N,d))
base = 0
for i in range(n):
X[base:base+multi[i],:] = np.random.multivariate_normal(mean[i,:], np.eye(self.d), multi[i])
base += multi[i]
llh = np.zeros(N)
for i in range(n):
llh += w[i] * stats.multivariate_normal.pdf(X, mean[i,:], np.eye(self.d))
#llh = llh/sum(llh)
return X, llh
示例6: get_inertia_tensor_about_point
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def get_inertia_tensor_about_point(self, point):
# Returns the inertia tensor about an arbitrary point.
# Using https://en.wikipedia.org/wiki/Parallel_axis_theorem#Tensor_generalization
R = point - self.xyz_cg
I = self.get_inertia_tensor()
m = self.mass
J = I + m * (np.dot(R, R) * np.eye(3) - np.outer(R, R))
return J
示例7: angle_axis_rotation_matrix
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def angle_axis_rotation_matrix(angle, axis, axis_already_normalized=False):
# Gives the rotation matrix from an angle and an axis.
# An implmentation of https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
# Inputs:
# * angle: can be one angle or a vector (1d ndarray) of angles. Given in radians.
# * axis: a 1d numpy array of length 3 (x,y,z). Represents the angle.
# * axis_already_normalized: boolean, skips normalization for speed if you flag this true.
# Outputs:
# * If angle is a scalar, returns a 3x3 rotation matrix.
# * If angle is a vector, returns a 3x3xN rotation matrix.
if not axis_already_normalized:
axis = axis / np.linalg.norm(axis)
sintheta = np.sin(angle)
costheta = np.cos(angle)
cpm = np.array(
[[0, -axis[2], axis[1]],
[axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]]
) # The cross product matrix of the rotation axis vector
outer_axis = np.outer(axis, axis)
angle = np.array(angle) # make sure angle is a ndarray
if len(angle.shape) == 0: # is a scalar
rot_matrix = costheta * np.eye(3) + sintheta * cpm + (1 - costheta) * outer_axis
return rot_matrix
else: # angle is assumed to be a 1d ndarray
rot_matrix = costheta * np.expand_dims(np.eye(3), 2) + sintheta * np.expand_dims(cpm, 2) + (
1 - costheta) * np.expand_dims(outer_axis, 2)
return rot_matrix
示例8: compute_rotation_matrix_wind_to_geometry
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def compute_rotation_matrix_wind_to_geometry(self):
# Computes the 3x3 rotation matrix required to go from wind axes to geometry axes.
sinalpha = np.sin(np.radians(self.alpha))
cosalpha = np.cos(np.radians(self.alpha))
sinbeta = np.sin(np.radians(self.beta))
cosbeta = np.cos(np.radians(self.beta))
# r=-1*np.array([
# [cosbeta*cosalpha, -sinbeta, cosbeta*sinalpha],
# [sinbeta*cosalpha, cosbeta, sinbeta*sinalpha],
# [-sinalpha, 0, cosalpha]
# ])
eye = np.eye(3)
alpharotation = np.array([
[cosalpha, 0, -sinalpha],
[0, 1, 0],
[sinalpha, 0, cosalpha]
])
betarotation = np.array([
[cosbeta, -sinbeta, 0],
[sinbeta, cosbeta, 0],
[0, 0, 1]
])
axesflip = np.array([
[-1, 0, 0],
[0, 1, 0, ],
[0, 0, -1]
]) # Since in geometry axes, X is downstream by convention, while in wind axes, X is upstream by convetion. Same with Z being up/down respectively.
r = axesflip @ alpharotation @ betarotation @ eye # where "@" is the matrix multiplication operator
return r
示例9: make_gp_funs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def make_gp_funs(cov_func, num_cov_params):
"""Functions that perform Gaussian process regression.
cov_func has signature (cov_params, x, x')"""
def unpack_kernel_params(params):
mean = params[0]
cov_params = params[2:]
noise_scale = np.exp(params[1]) + 0.0001
return mean, cov_params, noise_scale
def predict(params, x, y, xstar):
"""Returns the predictive mean and covariance at locations xstar,
of the latent function value f (without observation noise)."""
mean, cov_params, noise_scale = unpack_kernel_params(params)
cov_f_f = cov_func(cov_params, xstar, xstar)
cov_y_f = cov_func(cov_params, x, xstar)
cov_y_y = cov_func(cov_params, x, x) + noise_scale * np.eye(len(y))
pred_mean = mean + np.dot(solve(cov_y_y, cov_y_f).T, y - mean)
pred_cov = cov_f_f - np.dot(solve(cov_y_y, cov_y_f).T, cov_y_f)
return pred_mean, pred_cov
def log_marginal_likelihood(params, x, y):
mean, cov_params, noise_scale = unpack_kernel_params(params)
cov_y_y = cov_func(cov_params, x, x) + noise_scale * np.eye(len(y))
prior_mean = mean * np.ones(len(y))
return mvn.logpdf(y, prior_mean, cov_y_y)
return num_cov_params + 2, predict, log_marginal_likelihood
# Define an example covariance function.
示例10: init_gmm_params
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def init_gmm_params(num_components, D, scale, rs=npr.RandomState(0)):
return {'log proportions': rs.randn(num_components) * scale,
'means': rs.randn(num_components, D) * scale,
'lower triangles': np.zeros((num_components, D, D)) + np.eye(D)}
示例11: make_psd
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def make_psd(mat): return np.dot(mat.T, mat) + np.eye(mat.shape[0])
示例12: test_inv
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def test_inv():
def fun(x): return np.linalg.inv(x)
D = 8
mat = npr.randn(D, D)
mat = np.dot(mat, mat) + 1.0 * np.eye(D)
check_grads(fun)(mat)
示例13: test_inv_3d
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def test_inv_3d():
fun = lambda x: np.linalg.inv(x)
D = 4
mat = npr.randn(D, D, D) + 5*np.eye(D)
check_grads(fun)(mat)
mat = npr.randn(D, D, D, D) + 5*np.eye(D)
check_grads(fun)(mat)
示例14: test_solve_arg1_1d
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def test_solve_arg1_1d():
D = 8
A = npr.randn(D, D) + 10.0 * np.eye(D)
B = npr.randn(D)
def fun(a): return np.linalg.solve(a, B)
check_grads(fun)(A)
示例15: test_solve_arg2
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import eye [as 别名]
def test_solve_arg2():
D = 6
A = npr.randn(D, D) + 1.0 * np.eye(D)
B = npr.randn(D, D - 1)
def fun(b): return np.linalg.solve(A, b)
check_grads(fun)(B)