我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用scipy.sparse.linalg.aslinearoperator()。
def convert2scipy(LO): """ returns a scipy linear algebra. """ return scipyaslinearoperator(LO)
def convert(self, x): if (isinstance(x, (np.ndarray, sp.spmatrix))): return sla.aslinearoperator(x) else: assert(False)
def test_linear_operator(): npr.seed(0) nx, nineq, neq = 4, 6, 7 Q = npr.randn(nx, nx) G = npr.randn(nineq, nx) A = npr.randn(neq, nx) D = np.diag(npr.rand(nineq)) K_ = np.bmat(( (Q, np.zeros((nx, nineq)), G.T, A.T), (np.zeros((nineq, nx)), D, np.eye(nineq), np.zeros((nineq, neq))), (G, np.eye(nineq), np.zeros((nineq, nineq + neq))), (A, np.zeros((neq, nineq + nineq + neq))) )) Q_lo = sla.aslinearoperator(Q) G_lo = sla.aslinearoperator(G) A_lo = sla.aslinearoperator(A) D_lo = sla.aslinearoperator(D) K = block(( (Q_lo, 0, G.T, A.T), (0, D_lo, 'I', 0), (G_lo, 'I', 0, 0), (A_lo, 0, 0, 0) ), arrtype=sla.LinearOperator) w1 = np.random.randn(K_.shape[1]) assert np.allclose(K_.dot(w1), K.dot(w1)) w2 = np.random.randn(K_.shape[0]) assert np.allclose(K_.T.dot(w2), K.H.dot(w2)) W = np.random.randn(*K_.shape) assert np.allclose(K_.dot(W), K.dot(W))
def J_s(x, c_lens): i = 0 out = [] for n in c_lens: n0 = n * (n + 1) // 2 J = PSD.J(x[i:i + n0]) out.append(sla.aslinearoperator(J)) i += n0 assert i == len(x) return block_diag(out, arrtype=sla.LinearOperator)
def _solve_sparse_cg(X, y, alpha, max_iter=None, tol=1e-3, verbose=0): n_samples, n_features = X.shape X1 = sp_linalg.aslinearoperator(X) coefs = np.empty((y.shape[1], n_features)) if n_features > n_samples: def create_mv(curr_alpha): def _mv(x): return X1.matvec(X1.rmatvec(x)) + curr_alpha * x return _mv else: def create_mv(curr_alpha): def _mv(x): return X1.rmatvec(X1.matvec(x)) + curr_alpha * x return _mv for i in range(y.shape[1]): y_column = y[:, i] mv = create_mv(alpha[i]) if n_features > n_samples: # kernel ridge # w = X.T * inv(X X^t + alpha*Id) y C = sp_linalg.LinearOperator( (n_samples, n_samples), matvec=mv, dtype=X.dtype) coef, info = sp_linalg.cg(C, y_column, tol=tol) coefs[i] = X1.rmatvec(coef) else: # linear ridge # w = inv(X^t X + alpha*Id) * X.T y y_column = X1.rmatvec(y_column) C = sp_linalg.LinearOperator( (n_features, n_features), matvec=mv, dtype=X.dtype) coefs[i], info = sp_linalg.cg(C, y_column, maxiter=max_iter, tol=tol) if info < 0: raise ValueError("Failed with error code %d" % info) if max_iter is None and info > 0 and verbose: warnings.warn("sparse_cg did not converge after %d iterations." % info) return coefs