本文整理汇总了Python中scipy.linalg.qr方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.qr方法的具体用法?Python linalg.qr怎么用?Python linalg.qr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.linalg
的用法示例。
在下文中一共展示了linalg.qr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def __init__(self,in_channel):
super(InvConv,self).__init__()
weight=np.random.randn(in_channel,in_channel)
q,_=linalg.qr(weight)
w_p,w_l,w_u=linalg.lu(q.astype(np.float32))
w_s=np.diag(w_u)
w_u=np.triu(w_u,1)
u_mask=np.triu(np.ones_like(w_u),1)
l_mask=u_mask.T
self.register_buffer('w_p',torch.from_numpy(w_p))
self.register_buffer('u_mask',torch.from_numpy(u_mask))
self.register_buffer('l_mask',torch.from_numpy(l_mask))
self.register_buffer('l_eye',torch.eye(l_mask.shape[0]))
self.register_buffer('s_sign',torch.sign(torch.from_numpy(w_s)))
self.w_l=torch.nn.Parameter(torch.from_numpy(w_l))
self.w_s=torch.nn.Parameter(torch.log(1e-7+torch.abs(torch.from_numpy(w_s))))
self.w_u=torch.nn.Parameter(torch.from_numpy(w_u))
self.weight=None
self.invweight=None
return
示例2: _absorb_constraints
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def _absorb_constraints(design_matrix, constraints):
"""Absorb model parameters constraints into the design matrix.
:param design_matrix: The (2-d array) initial design matrix.
:param constraints: The 2-d array defining initial model parameters
(``betas``) constraints (``np.dot(constraints, betas) = 0``).
:return: The new design matrix with absorbed parameters constraints.
:raise ImportError: if scipy is not found, used for ``scipy.linalg.qr()``
which is cleaner than numpy's version requiring a call like
``qr(..., mode='complete')`` to get a full QR decomposition.
"""
try:
from scipy import linalg
except ImportError: # pragma: no cover
raise ImportError("Cubic spline functionality requires scipy.")
m = constraints.shape[0]
q, r = linalg.qr(np.transpose(constraints))
return np.dot(design_matrix, q[:, m:])
示例3: haar_measure
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def haar_measure(n):
"""A Random matrix distributed with the Haar measure.
For more details, see :cite:`mezzadri2006`.
Args:
n (int): matrix size
Returns:
array: an nxn random matrix
"""
z = (sp.randn(n, n) + 1j * sp.randn(n, n)) / np.sqrt(2.0)
q, r = qr(z)
d = sp.diagonal(r)
ph = d / np.abs(d)
q = np.multiply(q, ph, q)
return q
示例4: qft_circuit
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def qft_circuit(num_qubits, measure=True):
"""Create a qft circuit.
Args:
num_qubits (int): number of qubits
measure (bool): include measurement in circuit.
Returns:
QftCircuit: A qft circuit.
"""
# Create quantum/classical registers of size n
qr = QuantumRegister(num_qubits)
circuit = QuantumCircuit(qr)
for i in range(num_qubits):
for j in range(i):
circuit.cu1(math.pi/float(2**(i-j)), qr[i], qr[j])
circuit.h(qr[i])
if measure is True:
circuit = _add_measurements(circuit, qr)
return circuit
示例5: simple_u3_circuit
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def simple_u3_circuit(num_qubits, measure=True):
"""Creates a simple circuit composed by u3 gates, with measurements or not
at the end of each qubit.
Args:
num_qubits (int): Number of qubits
measure (bool): Add measurements at the end of each qubit
Returns:
QuantumCircuit: The simple quantum circuit
"""
qr = QuantumRegister(num_qubits)
circuit = QuantumCircuit(qr)
for i in range(num_qubits):
circuit.u3(1.1, 2.2, 3.3, qr[i])
if measure:
circuit = _add_measurements(circuit, qr)
return circuit
示例6: simple_cnot_circuit
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def simple_cnot_circuit(num_qubits, measure=True):
"""Creates a simple circuit composed by cnot gates, with measurements or
not at the end of each qubit.
Args:
num_qubits (int): Number of qubits
measure (bool): Add measurements at the end of each qubit
Returns:
QuantumCircuit: The simple quantum circuit
"""
qr = QuantumRegister(num_qubits)
circuit = QuantumCircuit(qr)
for i in range(num_qubits):
# for the last qubit, we exchange control and target qubits
target_qubit = i + 1 if num_qubits - 1 > i else i - 1
circuit.cx(qr[i], qr[target_qubit])
if measure:
circuit = _add_measurements(circuit, qr)
return circuit
# pylint: disable=invalid-name
示例7: starting_point
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def starting_point(self, random=False):
"""Heuristic to find a starting point candidate
Parameters
----------
random : `bool`
Use a random orthogonal matrix instead of identity
Returns
-------
startint_point : `np.ndarray`, shape=(n_nodes, n_nodes)
A starting point candidate
"""
sqrt_C = sqrtm(self.covariance)
sqrt_L = np.sqrt(self.mean_intensity)
if random:
random_matrix = np.random.rand(self.n_nodes, self.n_nodes)
M, _ = qr(random_matrix)
else:
M = np.eye(self.n_nodes)
initial = np.dot(np.dot(sqrt_C, M), np.diag(1. / sqrt_L))
return initial
示例8: test_delete_1x1_row_col
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def test_delete_1x1_row_col(self):
a, q, r = self.generate('1x1')
q1, r1 = qr_delete(q, r, 0, 1, 'row')
assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
a, q, r = self.generate('1x1')
q1, r1 = qr_delete(q, r, 0, 1, 'col')
assert_unitary(q1)
assert_(q1.dtype == q.dtype)
assert_(q1.shape == q.shape)
assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
# all full qr, row deletes and single column deletes should be able to
# handle any non negative strides. (only row and column vector
# operations are used.) p column delete require fortran ordered
# Q and R and will make a copy as necessary. Economic qr row deletes
# requre a contigous q.
示例9: null_space_method
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def null_space_method(Ao, bo, Co, do, verbose):
A = deepcopy(Ao)
C = deepcopy(Co)
b = deepcopy(bo)
d = deepcopy(do)
m, n = A.shape
p, n = C.shape
Q, R = np.linalg.qr(C.T, 'complete')
Q1 = Q[0:n, 0:p]
Q2 = Q[0:n, p:n]
# Lower triangular matrix!
L = R.T
L = L[0:p, 0:p]
y1 = least_squares(L, d, verbose)
c = b - np.dot( np.dot(A , Q1) , y1)
AQ2 = np.dot(A , Q2)
y2 = least_squares(AQ2 , c, verbose)
x = np.dot(Q1 , y1) + np.dot(Q2 , y2)
cond = np.linalg.cond(AQ2)
if verbose is True:
print('The condition number of the matrix is '+str(cond)+'.')
return x
示例10: predict
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def predict(self, u=0):
"""
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system.
"""
# x = Fx + Bu
self.x = dot(self.F, self.x) + dot(self.B, u)
# P = FPF' + Q
_, P2 = qr(np.hstack([dot(self.F, self._P1_2), self._Q1_2]).T)
self._P1_2 = P2[:self.dim_x, :self.dim_x].T
# copy prior
self.x_prior = np.copy(self.x)
self._P1_2_prior = np.copy(self._P1_2)
示例11: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def __init__(self, in_channel):
super().__init__()
weight = np.random.randn(in_channel, in_channel)
q, _ = la.qr(weight)
w_p, w_l, w_u = la.lu(q.astype(np.float32))
w_s = np.diag(w_u)
w_u = np.triu(w_u, 1)
u_mask = np.triu(np.ones_like(w_u), 1)
l_mask = u_mask.T
w_p = torch.from_numpy(w_p)
w_l = torch.from_numpy(w_l)
w_s = torch.from_numpy(w_s)
w_u = torch.from_numpy(w_u)
self.register_buffer('w_p', w_p)
self.register_buffer('u_mask', torch.from_numpy(u_mask))
self.register_buffer('l_mask', torch.from_numpy(l_mask))
self.register_buffer('s_sign', torch.sign(w_s))
self.register_buffer('l_eye', torch.eye(l_mask.shape[0]))
self.w_l = nn.Parameter(w_l)
self.w_s = nn.Parameter(logabs(w_s))
self.w_u = nn.Parameter(w_u)
示例12: nullspace_qr
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def nullspace_qr(m, tol=1e-7):
"""
Compute the nullspace of a matrix using the QR decomposition.
The QR decomposition is faster but less accurate than the SVD
used by :func:`nullspace`.
Parameters
----------
m : numpy array
An matrix of shape (M,N) whose nullspace to compute.
tol : float (optional)
Nullspace tolerance, used when comparing diagonal values of R with zero.
Returns
-------
An matrix of shape (M,K) whose columns contain nullspace basis vectors.
"""
#if M,N = m.shape, and q,r,p = _spl.qr(...)
# q.shape == (N,N), r.shape = (N,M), p.shape = (M,)
q, r, _ = _spl.qr(m.T, mode='full', pivoting=True)
rank = (_np.abs(_np.diagonal(r)) > tol).sum()
#DEBUG: requires q,r,p = _sql.qr(...) above
#assert( _np.linalg.norm(_np.dot(q,r) - m.T[:,p]) < 1e-8) #check QR decomp
#print("Rank QR = ",rank)
#print('\n'.join(map(str,_np.abs(_np.diagonal(r)))))
#print("Ret = ", q[:,rank:].shape, " Q = ",q.shape, " R = ",r.shape)
return q[:, rank:]
示例13: _weightsamples
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def _weightsamples(self):
reps = int(np.ceil(self.n / self.d))
Q = np.empty((self.d, self.d*reps))
for r in range(reps):
W = self._random.randn(self.d, self.d)
Q[:, (r * self.d):((r + 1) * self.d)] = qr(W)[0]
S = np.sqrt(self._random.chisquare(df=self.d, size=self.d))
weights = np.diag(S).dot(Q[:, :self.n])
return weights
示例14: test_crs_with_specific_constraint
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def test_crs_with_specific_constraint():
from patsy.highlevel import incr_dbuilder, build_design_matrices, dmatrix
x = (-1.5)**np.arange(20)
# Hard coded R values for smooth: s(x, bs="cr", k=5)
# R> knots <- smooth$xp
knots_R = np.array([-2216.837820053100585937,
-50.456909179687500000,
-0.250000000000000000,
33.637939453125000000,
1477.891880035400390625])
# R> centering.constraint <- t(qr.X(attr(smooth, "qrc")))
centering_constraint_R = np.array([[0.064910676323168478574,
1.4519875239407085132,
-2.1947446912471946234,
1.6129783104357671153,
0.064868180547550072235]])
# values for which we want a prediction
new_x = np.array([-3000., -200., 300., 2000.])
result1 = dmatrix("cr(new_x, knots=knots_R[1:-1], "
"lower_bound=knots_R[0], upper_bound=knots_R[-1], "
"constraints=centering_constraint_R)")
data_chunked = [{"x": x[:10]}, {"x": x[10:]}]
new_data = {"x": new_x}
builder = incr_dbuilder("cr(x, df=4, constraints='center')",
lambda: iter(data_chunked))
result2 = build_design_matrices([builder], new_data)[0]
assert np.allclose(result1, result2, rtol=1e-12, atol=0.)
示例15: qr
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import qr [as 别名]
def qr(A):
'''Get square upper triangular matrix of QR decomposition of matrix A'''
N, L = A.shape
if not N >= L:
raise ValueError("Number of columns must exceed number of rows")
Q, R = linalg.qr(A)
return R[:L, :L]