我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用scipy.sparse.identity()。
def suggest(self, method=s.RANDOM, eps=1e-8, *args, **kwargs): if method not in s.suggest_methods: raise Exception("Unknown suggest method: %s\n", method) if method == s.RANDOM: x = np.random.randn(self.n) elif method == s.SPECTRAL: if self.spectral_sol is None: self.spectral_sol, self.spectral_bound = solve_spectral(self.qcqp_form, *args, **kwargs) if self.maximize_flag: self.spectral_bound *= -1 x = self.spectral_sol elif method == s.SDR: if self.sdr_sol is None: self.sdr_sol, self.sdr_bound = solve_sdr(self.qcqp_form, *args, **kwargs) if self.maximize_flag: self.sdr_bound *= -1 self.mu = np.asarray(self.sdr_sol[:-1, -1]).flatten() self.Sigma = self.sdr_sol[:-1, :-1] - self.mu*self.mu.T + eps*sp.identity(self.n) x = np.random.multivariate_normal(self.mu, self.Sigma) assign_vars(self.prob.variables(), x) f0 = self.qcqp_form.f0.eval(x) if self.maximize_flag: f0 *= -1 return (f0, max(self.qcqp_form.violations(x)))
def edgeCurl(self): """The edgeCurl property.""" if self.nCy > 1: raise NotImplementedError('Edge curl not yet implemented for ' 'nCy > 1') if getattr(self, '_edgeCurl', None) is None: # 1D Difference matricies dr = sp.spdiags((np.ones((self.nCx+1, 1))*[-1, 1]).T, [-1, 0], self.nCx, self.nCx, format="csr") dz = sp.spdiags((np.ones((self.nCz+1, 1))*[-1, 1]).T, [0, 1], self.nCz, self.nCz+1, format="csr") # 2D Difference matricies Dr = sp.kron(sp.identity(self.nNz), dr) Dz = -sp.kron(dz, sp.identity(self.nCx)) A = self.area E = self.edge # Edge curl operator self._edgeCurl = (utils.sdiag(1/A)*sp.vstack((Dz, Dr)) * utils.sdiag(E)) return self._edgeCurl
def test_invXXXBlockDiagonal(self): a = [np.random.rand(5, 1) for i in range(4)] B = inv2X2BlockDiagonal(*a) A = sp.vstack((sp.hstack((sdiag(a[0]), sdiag(a[1]))), sp.hstack((sdiag(a[2]), sdiag(a[3]))))) Z2 = B*A - sp.identity(10) self.assertTrue(np.linalg.norm(Z2.todense().ravel(), 2) < TOL) a = [np.random.rand(5, 1) for i in range(9)] B = inv3X3BlockDiagonal(*a) A = sp.vstack((sp.hstack((sdiag(a[0]), sdiag(a[1]), sdiag(a[2]))), sp.hstack((sdiag(a[3]), sdiag(a[4]), sdiag(a[5]))), sp.hstack((sdiag(a[6]), sdiag(a[7]), sdiag(a[8]))))) Z3 = B*A - sp.identity(15) self.assertTrue(np.linalg.norm(Z3.todense().ravel(), 2) < TOL)
def test_invPropertyTensor2D(self): M = discretize.TensorMesh([6, 6]) a1 = np.random.rand(M.nC) a2 = np.random.rand(M.nC) a3 = np.random.rand(M.nC) prop1 = a1 prop2 = np.c_[a1, a2] prop3 = np.c_[a1, a2, a3] for prop in [4, prop1, prop2, prop3]: b = invPropertyTensor(M, prop) A = makePropertyTensor(M, prop) B1 = makePropertyTensor(M, b) B2 = invPropertyTensor(M, prop, returnMatrix=True) Z = B1*A - sp.identity(M.nC*2) self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL) Z = B2*A - sp.identity(M.nC*2) self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL)
def test_invPropertyTensor3D(self): M = discretize.TensorMesh([6, 6, 6]) a1 = np.random.rand(M.nC) a2 = np.random.rand(M.nC) a3 = np.random.rand(M.nC) a4 = np.random.rand(M.nC) a5 = np.random.rand(M.nC) a6 = np.random.rand(M.nC) prop1 = a1 prop2 = np.c_[a1, a2, a3] prop3 = np.c_[a1, a2, a3, a4, a5, a6] for prop in [4, prop1, prop2, prop3]: b = invPropertyTensor(M, prop) A = makePropertyTensor(M, prop) B1 = makePropertyTensor(M, b) B2 = invPropertyTensor(M, prop, returnMatrix=True) Z = B1*A - sp.identity(M.nC*3) self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL) Z = B2*A - sp.identity(M.nC*3) self.assertTrue(np.linalg.norm(Z.todense().ravel(), 2) < TOL)
def get_item_representations(self, features=None): """ Get the latent representations for items given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_items, n_item_features], optional Each row contains that item's weights over features. An identity matrix will be used if not supplied. Returns ------- (item_biases, item_embeddings): (np.float32 array of shape n_items, np.float32 array of shape [n_items, num_components] Biases and latent representations for items. """ self._check_initialized() if features is None: return self.item_biases, self.item_embeddings features = sp.csr_matrix(features, dtype=CYTHON_DTYPE) return features * self.item_biases, features * self.item_embeddings
def get_user_representations(self, features=None): """ Get the latent representations for users given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_users, n_user_features], optional Each row contains that user's weights over features. An identity matrix will be used if not supplied. Returns ------- (user_biases, user_embeddings): (np.float32 array of shape n_users np.float32 array of shape [n_users, num_components] Biases and latent representations for users. """ self._check_initialized() if features is None: return self.user_biases, self.user_embeddings features = sp.csr_matrix(features, dtype=CYTHON_DTYPE) return features * self.user_biases, features * self.user_embeddings
def A_to_diffusion_kernel(A, k): """ Computes [A**0, A**1, ..., A**k] :param A: 2d numpy array :param k: integer, degree of series :return: 3d numpy array [A**0, A**1, ..., A**k] """ assert k >= 0 Apow = [np.identity(A.shape[0])] if k > 0: d = A.sum(0) Apow.append(A / (d + 1.0)) for i in range(2, k + 1): Apow.append(np.dot(A / (d + 1.0), Apow[-1])) return np.transpose(np.asarray(Apow, dtype='float32'), (1, 0, 2))
def sparse_A_to_diffusion_kernel(A, k): assert k >= 0 num_nodes = A.shape[0] Apow = [sp.identity(num_nodes)] if k > 0: d = A.sum(0) Apow.append(A / (d + 1.0)) for i in range(2, k + 1): Apow.append((A / (d + 1.0)).dot(Apow[-1])) return Apow
def dc_split(self, use_eigen_split=False): n = self.P.shape[0] if self.P.nnz == 0: # P is zero P1, P2 = sp.csr_matrix((n, n)), sp.csr_matrix((n, n)) if use_eigen_split: lmb, Q = LA.eigh(self.P.todense()) P1 = sum([Q[:, i]*lmb[i]*Q[:, i].T for i in range(n) if lmb[i] > 0]) P2 = sum([-Q[:, i]*lmb[i]*Q[:, i].T for i in range(n) if lmb[i] < 0]) assert abs(np.sum(P1 - P2 - self.P)) < 1e-8 else: lmb_min = np.min(LA.eigh(self.P.todense())[0]) if lmb_min < 0: P1 = self.P + (1-lmb_min)*sp.identity(n) P2 = (1-lmb_min)*sp.identity(n) else: P1 = self.P P2 = sp.csr_matrix((n, n)) f1 = QuadraticFunction(P1, self.q, self.r) f2 = QuadraticFunction(P2, sp.csc_matrix((n, 1)), 0) return (f1, f2) # Returns the one-variable function when regarding f(x) # as a quadratic expression in x[k]. # f is an instance of QuadraticFunction # return value is an instance of OneVarQuadraticFunction # TODO: speedup
def admm_phase2(x0, prob, rho, tol=1e-2, num_iters=1000, viol_lim=1e4): logging.info("Starting ADMM phase 2 with rho %.3f", rho) bestx = np.copy(x0) z = np.copy(x0) xs = [np.copy(x0) for i in range(prob.m)] us = [np.zeros(prob.n) for i in range(prob.m)] if prob.rho != rho: prob.rho = rho zlhs = 2*(prob.f0.P + rho*prob.m*sp.identity(prob.n)).tocsc() prob.z_solver = SLA.factorized(zlhs) last_z = None for t in range(num_iters): rhs = 2*rho*(sum(xs)-sum(us)) - prob.f0.qarray z = prob.z_solver(rhs) # TODO: parallel x/u-updates for i in range(prob.m): xs[i] = onecons_qcqp(z + us[i], prob.fi(i)) for i in range(prob.m): us[i] += z - xs[i] # TODO: termination condition if last_z is not None and LA.norm(last_z - z) < tol: break last_z = z maxviol = max(prob.violations(z)) logging.info("Iteration %d, violation %.3f", t, maxviol) if maxviol > viol_lim: break bestx = np.copy(prob.better(z, bestx)) return bestx
def permuteCC(self): # TODO: cache these? P = SortGrid(self.gridCC) return sp.identity(self.nC).tocsr()[P,:]
def permuteF(self): # TODO: cache these? P = SortGrid(self.gridFx) P += SortGrid(self.gridFy, offset=self.nFx) if self.dim == 3: P += SortGrid(self.gridFz, offset=self.nFx+self.nFy) return sp.identity(self.nF).tocsr()[P,:]
def permuteE(self): # TODO: cache these? if self.dim == 2: P = SortGrid(self.gridFy) P += SortGrid(self.gridFx, offset=self.nEx) return sp.identity(self.nE).tocsr()[P, :] if self.dim == 3: P = SortGrid(self.gridEx) P += SortGrid(self.gridEy, offset=self.nEx) P += SortGrid(self.gridEz, offset=self.nEx+self.nEy) return sp.identity(self.nE).tocsr()[P, :]
def speye(n): """Sparse identity""" return sp.identity(n, format="csr")
def _getInnerProductProjectionMatrices(self, projType, tensorType): """ :param str projType: 'F' for faces 'E' for edges :param TensorType tensorType: type of the tensor: TensorType(mesh, sigma) """ assert isinstance(tensorType, TensorType), 'tensorType must be an instance of TensorType.' assert projType in ['F', 'E'], "projType must be 'F' for faces or 'E' for edges" d = self.dim # We will multiply by sqrt on each side to keep symmetry V = sp.kron(sp.identity(d), sdiag(np.sqrt((2**(-d))*self.vol))) nodes = ['000', '100', '010', '110', '001', '101', '011', '111'][:2**d] if projType == 'F': locs = { '000': [('fXm',), ('fXm', 'fYm'), ('fXm', 'fYm', 'fZm')], '100': [('fXp',), ('fXp', 'fYm'), ('fXp', 'fYm', 'fZm')], '010': [ None , ('fXm', 'fYp'), ('fXm', 'fYp', 'fZm')], '110': [ None , ('fXp', 'fYp'), ('fXp', 'fYp', 'fZm')], '001': [ None , None , ('fXm', 'fYm', 'fZp')], '101': [ None , None , ('fXp', 'fYm', 'fZp')], '011': [ None , None , ('fXm', 'fYp', 'fZp')], '111': [ None , None , ('fXp', 'fYp', 'fZp')] } proj = getattr(self, '_getFaceP' + ('x'*d))() elif projType == 'E': locs = { '000': [('eX0',), ('eX0', 'eY0'), ('eX0', 'eY0', 'eZ0')], '100': [('eX0',), ('eX0', 'eY1'), ('eX0', 'eY1', 'eZ1')], '010': [ None , ('eX1', 'eY0'), ('eX1', 'eY0', 'eZ2')], '110': [ None , ('eX1', 'eY1'), ('eX1', 'eY1', 'eZ3')], '001': [ None , None , ('eX2', 'eY2', 'eZ0')], '101': [ None , None , ('eX2', 'eY3', 'eZ1')], '011': [ None , None , ('eX3', 'eY2', 'eZ2')], '111': [ None , None , ('eX3', 'eY3', 'eZ3')] } proj = getattr(self, '_getEdgeP' + ('x'*d))() return [V*proj(*locs[node][d-1]) for node in nodes]
def _getEdgePx(M): """Returns a function for creating projection matrices""" def Px(xEdge): assert xEdge == 'eX0', 'xEdge = {0!s}, not eX0'.format(xEdge) return sp.identity(M.nC) return Px
def __call__(self, t, fields, dt, pars, hook=null_hook): """Perform a step of the solver: took a time and a system state as a triflow Fields container and return the next time step with updated container. Parameters ---------- t : float actual time step fields : triflow.Fields actual system state in a triflow Fields container dt : float temporal step-size pars : dict physical parameters of the model hook : callable, optional any callable taking the actual time, fields and parameters and return modified fields and parameters. Will be called every internal time step and can be used to include time dependent or conditionnal parameters, boundary conditions... Returns ------- tuple : t, fields updated time and fields container """ # noqa fields = fields.copy() fields, pars = hook(t, fields, pars) F = self._model.F(fields, pars) J = self._model.J(fields, pars) U = fields.uflat B = dt * (F - self._theta * J @ U) + U J = (sps.identity(U.size, format='csc') - self._theta * dt * J) fields.fill(self._solver(J, B)) fields, _ = hook(t + dt, fields, pars) return t + dt, fields
def _construct_feature_matrices(self, n_users, n_items, user_features, item_features): if user_features is None: user_features = sp.identity(n_users, dtype=CYTHON_DTYPE, format='csr') else: user_features = user_features.tocsr() if item_features is None: item_features = sp.identity(n_items, dtype=CYTHON_DTYPE, format='csr') else: item_features = item_features.tocsr() if n_users > user_features.shape[0]: raise Exception('Number of user feature rows does not equal ' 'the number of users') if n_items > item_features.shape[0]: raise Exception('Number of item feature rows does not equal ' 'the number of items') # If we already have embeddings, verify that # we have them for all the supplied features if self.user_embeddings is not None: assert self.user_embeddings.shape[0] >= user_features.shape[1] if self.item_embeddings is not None: assert self.item_embeddings.shape[0] >= item_features.shape[1] user_features = self._to_cython_dtype(user_features) item_features = self._to_cython_dtype(item_features) return user_features, item_features
def A_to_pre_sparse_diffusion_kernel(A, k, threshold): Apow = [np.identity(A.shape[0])] if k > 0: d = A.sum(0) Apow.append(A / (d + 1.0)) Apow[-1][Apow[-1] <= threshold] = 0.0 for i in range(2, k + 1): Apow.append(np.dot(A / (d + 1.0), Apow[-1])) return np.transpose(np.asarray(Apow, dtype='float32'), (1, 0, 2))
def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: # M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec
def get_movielens_100k(min_positive_score=4): movielens_100k_dict = datasets.fetch_movielens(indicator_features=True, genre_features=True) def flip_ratings(ratings_matrix): ratings_matrix.data = np.array([1 if rating >= min_positive_score else -1 for rating in ratings_matrix.data]) return ratings_matrix test_interactions = flip_ratings(movielens_100k_dict['test']) train_interactions = flip_ratings(movielens_100k_dict['train']) # Create indicator features for all users num_users = train_interactions.shape[0] user_features = sp.identity(num_users) return train_interactions, test_interactions, user_features, movielens_100k_dict['item_features']