本文整理匯總了Python中numpy.eye方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.eye方法的具體用法?Python numpy.eye怎麽用?Python numpy.eye使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.eye方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: classical_mds
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def classical_mds(self, D):
'''
Classical multidimensional scaling
Parameters
----------
D : square 2D ndarray
Euclidean Distance Matrix (matrix containing squared distances between points
'''
# Apply MDS algorithm for denoising
n = D.shape[0]
J = np.eye(n) - np.ones((n,n))/float(n)
G = -0.5*np.dot(J, np.dot(D, J))
s, U = np.linalg.eig(G)
# we need to sort the eigenvalues in decreasing order
s = np.real(s)
o = np.argsort(s)
s = s[o[::-1]]
U = U[:,o[::-1]]
S = np.diag(s)[0:self.dim,:]
self.X = np.dot(np.sqrt(S),U.T)
示例2: output_shrink
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def output_shrink(K, L):
"""
shrink the convolution output to half the size.
used when both the annihilating filter and the uniform samples of sinusoids satisfy
Hermitian symmetric.
:param K: the annihilating filter size: K + 1
:param L: length of the (complex-valued) b vector
:return:
"""
out_len = L - K
if out_len % 2 == 0:
half_out_len = np.int(out_len / 2.)
mtx_r = np.hstack((np.eye(half_out_len),
np.zeros((half_out_len, half_out_len))))
mtx_i = mtx_r
else:
half_out_len = np.int((out_len + 1) / 2.)
mtx_r = np.hstack((np.eye(half_out_len),
np.zeros((half_out_len, half_out_len - 1))))
mtx_i = np.hstack((np.eye(half_out_len - 1),
np.zeros((half_out_len - 1, half_out_len))))
return linalg.block_diag(mtx_r, mtx_i)
示例3: mtx_updated_G
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def mtx_updated_G(phi_recon, M, mtx_amp2visi_ri, mtx_fri2visi_ri):
"""
Update the linear transformation matrix that links the FRI sequence to the
visibilities by using the reconstructed Dirac locations.
:param phi_recon: the reconstructed Dirac locations (azimuths)
:param M: the Fourier series expansion is between -M to M
:param p_mic_x: a vector that contains microphones' x-coordinates
:param p_mic_y: a vector that contains microphones' y-coordinates
:param mtx_freq2visi: the linear mapping from Fourier series to visibilities
:return:
"""
L = 2 * M + 1
ms_half = np.reshape(np.arange(-M, 1, step=1), (-1, 1), order='F')
phi_recon = np.reshape(phi_recon, (1, -1), order='F')
mtx_amp2freq = np.exp(-1j * ms_half * phi_recon) # size: (M + 1) x K
mtx_amp2freq_ri = np.vstack((mtx_amp2freq.real, mtx_amp2freq.imag[:-1, :])) # size: (2M + 1) x K
mtx_fri2amp_ri = linalg.lstsq(mtx_amp2freq_ri, np.eye(L))[0]
# projection mtx_freq2visi to the null space of mtx_fri2amp
mtx_null_proj = np.eye(L) - np.dot(mtx_fri2amp_ri.T,
linalg.lstsq(mtx_fri2amp_ri.T, np.eye(L))[0])
G_updated = np.dot(mtx_amp2visi_ri, mtx_fri2amp_ri) + \
np.dot(mtx_fri2visi_ri, mtx_null_proj)
return G_updated
示例4: _N
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def _N(self,s,r):
"""
Lagrange's interpolate function
params:
s,r:natural position of evalue point.2-array.
returns:
2x(2x4) shape function matrix.
"""
la1=(1-s)/2
la2=(1+s)/2
lb1=(1-r)/2
lb2=(1+r)/2
N1=la1*lb1
N2=la1*lb2
N3=la2*lb1
N4=la2*lb2
N=np.hstack(N1*np.eye(2),N2*np.eye(2),N3*np.eye(2),N4*np.eye(2))
return N
示例5: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def __init__(self):
"""Initialize variable used by Kalman Filter class
Args:
None
Return:
None
"""
self.dt = 0.005 # delta time
self.A = np.array([[1, 0], [0, 1]]) # matrix in observation equations
self.u = np.zeros((2, 1)) # previous state vector
# (x,y) tracking object center
self.b = np.array([[0], [255]]) # vector of observations
self.P = np.diag((3.0, 3.0)) # covariance matrix
self.F = np.array([[1.0, self.dt], [0.0, 1.0]]) # state transition mat
self.Q = np.eye(self.u.shape[0]) # process noise matrix
self.R = np.eye(self.b.shape[0]) # observation noise matrix
self.lastResult = np.array([[0], [255]])
示例6: betaseries_file
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def betaseries_file(tmpdir_factory,
deriv_betaseries_fname=deriv_betaseries_fname):
bfile = tmpdir_factory.mktemp("beta").ensure(deriv_betaseries_fname)
np.random.seed(3)
num_trials = 40
tgt_corr = 0.1
bs1 = np.random.rand(num_trials)
# create another betaseries with a target correlation
bs2 = minimize(lambda x: abs(tgt_corr - pearsonr(bs1, x)[0]),
np.random.rand(num_trials)).x
# two identical beta series
bs_data = np.array([[[bs1, bs2]]])
# the nifti image
bs_img = nib.Nifti1Image(bs_data, np.eye(4))
bs_img.to_filename(str(bfile))
return bfile
示例7: test_output
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def test_output():
shape = (2,2)
ones = mx.nd.ones(shape)
zeros = mx.nd.zeros(shape)
out = mx.nd.zeros(shape)
mx.nd.ones(shape, out=out)
assert_almost_equal(out.asnumpy(), ones.asnumpy())
mx.nd.zeros(shape, out=out)
assert_almost_equal(out.asnumpy(), zeros.asnumpy())
mx.nd.full(shape, 2, out=out)
assert_almost_equal(out.asnumpy(), ones.asnumpy() * 2)
arange_out = mx.nd.arange(0, 20, dtype='int64')
assert_almost_equal(arange_out.asnumpy(), np.arange(0, 20))
N_array = np.random.randint(1, high=8, size=10)
M_array = np.random.randint(1, high=8, size=10)
k_array = np.random.randint(-10, high=10, size=10)
for i in range(10):
N = N_array[i]
M = M_array[i]
k = k_array[i]
assert_almost_equal(np.eye(N, M, k), mx.nd.eye(N, M, k).asnumpy())
assert_almost_equal(np.eye(N, k=k), mx.nd.eye(N, k=k).asnumpy())
示例8: set_camera
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def set_camera(self, fov_vertical, z_near, z_far, aspect):
width = 2*np.tan(np.deg2rad(fov_vertical)/2.0)*z_near*aspect;
height = 2*np.tan(np.deg2rad(fov_vertical)/2.0)*z_near;
egl_program = self.egl_program
c = np.eye(4, dtype=np.float32)
c[3,3] = 0
c[3,2] = -1
c[2,2] = -(z_near+z_far)/(z_far-z_near)
c[2,3] = -2.0*(z_near*z_far)/(z_far-z_near)
c[0,0] = 2.0*z_near/width
c[1,1] = 2.0*z_near/height
c = c.T
projection_matrix_o = glGetUniformLocation(egl_program, 'uProjectionMatrix')
projection_matrix = np.eye(4, dtype=np.float32)
projection_matrix[...] = c
projection_matrix = np.reshape(projection_matrix, (-1))
glUniformMatrix4fv(projection_matrix_o, 1, GL_FALSE, projection_matrix)
示例9: rotate_camera_to_point_at
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def rotate_camera_to_point_at(up_from, lookat_from, up_to, lookat_to):
inputs = [up_from, lookat_from, up_to, lookat_to]
for i in range(4):
inputs[i] = normalize(np.array(inputs[i]).reshape((-1,)))
up_from, lookat_from, up_to, lookat_to = inputs
r1 = r_between(lookat_from, lookat_to)
new_x = np.dot(r1, np.array([1, 0, 0]).reshape((-1, 1))).reshape((-1))
to_x = normalize(np.cross(lookat_to, up_to))
angle = np.arccos(np.dot(new_x, to_x))
if angle > ANGLE_EPS:
if angle < np.pi - ANGLE_EPS:
ax = normalize(np.cross(new_x, to_x))
flip = np.dot(lookat_to, ax)
if flip > 0:
r2 = get_r_matrix(lookat_to, angle)
elif flip < 0:
r2 = get_r_matrix(lookat_to, -1. * angle)
else:
# Angle of rotation is too close to 180 degrees, direction of rotation
# does not matter.
r2 = get_r_matrix(lookat_to, angle)
else:
r2 = np.eye(3)
return np.dot(r2, r1)
示例10: test_givens_inverse
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def test_givens_inverse():
r"""
The Givens rotation in OpenFermion is defined as
.. math::
\begin{pmatrix}
\cos(\theta) & -e^{i \varphi} \sin(\theta) \\
\sin(\theta) & e^{i \varphi} \cos(\theta)
\end{pmatrix}.
confirm numerically its hermitian conjugate is it's inverse
"""
a = numpy.random.random() + 1j * numpy.random.random()
b = numpy.random.random() + 1j * numpy.random.random()
ab_rotation = givens_matrix_elements(a, b, which='right')
assert numpy.allclose(ab_rotation.dot(numpy.conj(ab_rotation).T),
numpy.eye(2))
assert numpy.allclose(numpy.conj(ab_rotation).T.dot(ab_rotation),
numpy.eye(2))
示例11: test_circuit_generation_and_accuracy
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def test_circuit_generation_and_accuracy():
for dim in range(2, 10):
qubits = cirq.LineQubit.range(dim)
u_generator = numpy.random.random(
(dim, dim)) + 1j * numpy.random.random((dim, dim))
u_generator = u_generator - numpy.conj(u_generator).T
assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)
unitary = scipy.linalg.expm(u_generator)
circuit = cirq.Circuit()
circuit.append(optimal_givens_decomposition(qubits, unitary))
fermion_generator = QubitOperator(()) * 0.0
for i, j in product(range(dim), repeat=2):
fermion_generator += jordan_wigner(
FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))
true_unitary = scipy.linalg.expm(
get_sparse_operator(fermion_generator).toarray())
assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
numpy.eye(2 ** dim, dtype=complex))
test_unitary = cirq.unitary(circuit)
assert numpy.isclose(
abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
示例12: energy_from_opdm
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def energy_from_opdm(opdm, constant, one_body_tensor, two_body_tensor):
"""
Evaluate the energy of an opdm assuming the 2-RDM is opdm ^ opdm
:param opdm: single spin-component of the full spin-orbital opdm.
:param constant: constant shift to the Hamiltonian. Commonly this is the
nuclear repulsion energy.
:param one_body_tensor: spatial one-body integrals
:param two_body_tensor: spatial two-body integrals
:return:
"""
spin_opdm = np.kron(opdm, np.eye(2))
spin_tpdm = 2 * wedge(spin_opdm, spin_opdm, (1, 1), (1, 1))
molecular_hamiltonian = generate_hamiltonian(constant=constant,
one_body_integrals=one_body_tensor,
two_body_integrals=two_body_tensor)
rdms = InteractionRDM(spin_opdm, spin_tpdm)
return rdms.expectation(molecular_hamiltonian).real
示例13: netflix
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def netflix(es, ps, e0, l=.0001):
"""Combine predictions with the optimal weights to minimize RMSE.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the ridge regression
Returns:
(tuple):
- (np.array): ensemble predictions
- (np.array): weights for input predictions
"""
m = len(es)
n = len(ps[0])
X = np.stack(ps).T
pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2)
w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy)
return X.dot(w), w
示例14: fit
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def fit(self, Xs, Xt):
'''
Fit source and target using KMM (compute the coefficients)
:param Xs: ns * dim
:param Xt: nt * dim
:return: Coefficients (Pt / Ps) value vector (Beta in the paper)
'''
ns = Xs.shape[0]
nt = Xt.shape[0]
if self.eps == None:
self.eps = self.B / np.sqrt(ns)
K = kernel(self.kernel_type, Xs, None, self.gamma)
kappa = np.sum(kernel(self.kernel_type, Xs, Xt, self.gamma) * float(ns) / float(nt), axis=1)
K = matrix(K)
kappa = matrix(kappa)
G = matrix(np.r_[np.ones((1, ns)), -np.ones((1, ns)), np.eye(ns), -np.eye(ns)])
h = matrix(np.r_[ns * (1 + self.eps), ns * (self.eps - 1), self.B * np.ones((ns,)), np.zeros((ns,))])
sol = solvers.qp(K, -kappa, G, h)
beta = np.array(sol['x'])
return beta
示例15: fit
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import eye [as 別名]
def fit(self, Xs, Xt):
'''
Transform Xs and Xt
:param Xs: ns * n_feature, source feature
:param Xt: nt * n_feature, target feature
:return: Xs_new and Xt_new after TCA
'''
X = np.hstack((Xs.T, Xt.T))
X /= np.linalg.norm(X, axis=0)
m, n = X.shape
ns, nt = len(Xs), len(Xt)
e = np.vstack((1 / ns * np.ones((ns, 1)), -1 / nt * np.ones((nt, 1))))
M = e * e.T
M = M / np.linalg.norm(M, 'fro')
H = np.eye(n) - 1 / n * np.ones((n, n))
K = kernel(self.kernel_type, X, None, gamma=self.gamma)
n_eye = m if self.kernel_type == 'primal' else n
a, b = np.linalg.multi_dot([K, M, K.T]) + self.lamb * np.eye(n_eye), np.linalg.multi_dot([K, H, K.T])
w, V = scipy.linalg.eig(a, b)
ind = np.argsort(w)
A = V[:, ind[:self.dim]]
Z = np.dot(A.T, K)
Z /= np.linalg.norm(Z, axis=0)
Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T
return Xs_new, Xt_new