我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用scipy.optimize.nnls()。
def fit(self): print "Fitting a model with ", len(self.training_data), " points" labels = np.array([row[2] for row in self.training_data]) data_points = np.array([self._get_features(row) for row in self.training_data]) self.model = nnls(data_points, labels) # TODO: Add a debug logging mode ? # print "Residual norm ", self.model[1] # print "Model ", self.model[0] # Calculate training error training_errors = [] for p in self.training_data: predicted = self.predict(p[0], p[1]) training_errors.append(predicted / p[2]) print "Average training error %f%%" % ((np.mean(training_errors) - 1.0)*100.0 ) return self.model[0]
def decoding(self): D = self.A_true.shape[1] num_doc = self.Y.shape[1] Z = np.asmatrix(np.zeros((D, num_doc))) A = np.asarray(self.A.copy()) Y = np.asarray(self.Y.copy()) for i in range(num_doc): Yi = np.array(Y[:, i]).flatten() t, bla = nnls(A, Yi) Z[:, i] = np.asmatrix(t).transpose() Z = np.asmatrix(Z) return Z
def decoding(self): D = self.A_true.shape[1] num_doc = self.Y.shape[1] Z = np.asmatrix(np.zeros((D, num_doc))) for i in range(num_doc): Yi = np.array(self.Y[:, i].copy()).flatten() A = np.asarray(self.A.copy()) t, bla = nnls(A, Yi) Z[:, i] = np.asmatrix(t).transpose() Z = np.asmatrix(Z) return Z
def nn_omp(X, D, n_nonzero_coefs=None, tol=None): """ The Non Negative OMP algorithm of 'On the Uniqueness of Nonnegative Sparse Solutions to Underdetermined Systems of Equations'""" n_samples = X.shape[1] n_atoms = D.shape[1] Z = np.zeros((n_atoms, n_samples)) _norm = np.sum(D ** 2, axis=0) for i in range(n_samples): x = X[:, i] r = x z = np.zeros(n_atoms) Dx = np.array([]).astype(int) j = 0 if n_nonzero_coefs is not None: tol = 1e-20 def cont_criterion(): not_reached_sparsity = j < n_nonzero_coefs return (not_reached_sparsity and norm(r) > tol) else: cont_criterion = lambda: norm(r) > tol while (cont_criterion()): a = np.dot(D.T, r) a[a < 0] = 0 e = (norm(r) ** 2) - (a ** 2) / _norm k = np.argmin(e) Dx = np.append(Dx, k) z_est = nnls(D[:, Dx], x)[0] r = x - np.dot(D[:, Dx], z_est) j += 1 if j != 0: z[Dx] = z_est Z[:, i] = z return Z
def NNLS(M, U): """ NNLS performs non-negative constrained least squares of each pixel in M using the endmember signatures of U. Non-negative constrained least squares with the abundance nonnegative constraint (ANC). Utilizes the method of Bro. Parameters: M: `numpy array` 2D data matrix (N x p). U: `numpy array` 2D matrix of endmembers (q x p). Returns: `numpy array` An abundance maps (N x q). References: Bro R., de Jong S., Journal of Chemometrics, 1997, 11, 393-401. """ import scipy.optimize as opt N, p1 = M.shape q, p2 = U.shape X = np.zeros((N, q), dtype=np.float32) MtM = np.dot(U, U.T) for n1 in range(N): # opt.nnls() return a tuple, the first element is the result X[n1] = opt.nnls(MtM, np.dot(U, M[n1]))[0] return X
def _train(self, method='nnl1reg', lam_drop=1.0, lam_pot = 0.5, lam_avi = 3.0, **kwargs): ''' determine the model parameters -- lam_drop, lam_pot, lam_avi are the regularization parameters. ''' self.lam_pot = lam_pot self.lam_avi = lam_avi self.lam_drop = lam_drop if len(self.train_titers)==0: print('no titers to train') self.model_params = np.zeros(self.genetic_params+len(self.sera)+len(self.test_strains)) else: if method=='l1reg': # l1 regularized fit, no constraint on sign of effect self.model_params = self.fit_l1reg() elif method=='nnls': # non-negative least square, not regularized self.model_params = self.fit_nnls() elif method=='nnl2reg': # non-negative L2 norm regularized fit self.model_params = self.fit_nnl2reg() elif method=='nnl1reg': # non-negative fit, branch terms L1 regularized, avidity terms L2 regularized self.model_params = self.fit_nnl1reg() print('rms deviation on training set=',np.sqrt(self.fit_func())) # extract and save the potencies and virus effects. The genetic parameters # are subclass specific and need to be process by the subclass self.serum_potency = {serum:self.model_params[self.genetic_params+ii] for ii, serum in enumerate(self.sera)} self.virus_effect = {strain:self.model_params[self.genetic_params+len(self.sera)+ii] for ii, strain in enumerate(self.test_strains)}
def fit_nnls(self): from scipy.optimize import nnls return nnls(self.design_matrix, self.titer_dist)[0]
def nnls(A, B): def func(b): return optimize.nnls(A, b)[0] return np.array(map(func, B))
def _test_nnlsm(): print '\nTesting nnls routines ...' m = 100 n = 10 k = 200 rep = 5 for r in xrange(0, rep): A = np.random.rand(m, n) X_org = np.random.rand(n, k) X_org[np.random.rand(n, k) < 0.5] = 0 B = A.dot(X_org) # B = np.random.rand(m,k) # A = np.random.rand(m,n/2) # A = np.concatenate((A,A),axis=1) # A = A + np.random.rand(m,n)*0.01 # B = np.random.rand(m,k) import time start = time.time() C1, info = nnlsm_blockpivot(A, B) elapsed2 = time.time() - start rel_norm2 = nla.norm(C1 - X_org) / nla.norm(X_org) print 'nnlsm_blockpivot: ', 'OK ' if info[0] else 'Fail',\ 'elapsed:{0:.4f} error:{1:.4e}'.format(elapsed2, rel_norm2) start = time.time() C2, info = nnlsm_activeset(A, B) num_backup = 0 elapsed1 = time.time() - start rel_norm1 = nla.norm(C2 - X_org) / nla.norm(X_org) print 'nnlsm_activeset: ', 'OK ' if info[0] else 'Fail',\ 'elapsed:{0:.4f} error:{1:.4e}'.format(elapsed1, rel_norm1) import scipy.optimize as opt start = time.time() C3 = np.zeros([n, k]) for i in xrange(0, k): res = opt.nnls(A, B[:, i]) C3[:, i] = res[0] elapsed3 = time.time() - start rel_norm3 = nla.norm(C3 - X_org) / nla.norm(X_org) print 'scipy.optimize.nnls: ', 'OK ',\ 'elapsed:{0:.4f} error:{1:.4e}'.format(elapsed3, rel_norm3) if num_backup > 0: break if rel_norm1 > 10e-5 or rel_norm2 > 10e-5 or rel_norm3 > 10e-5: break print ''