当前位置: 首页>>代码示例>>Python>>正文


Python optimize.nnls方法代码示例

本文整理汇总了Python中scipy.optimize.nnls方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.nnls方法的具体用法?Python optimize.nnls怎么用?Python optimize.nnls使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.optimize的用法示例。


在下文中一共展示了optimize.nnls方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fit

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
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] 
开发者ID:amplab,项目名称:ernest,代码行数:18,代码来源:predictor.py

示例2: optimize

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def optimize(self):
    try:
      prev_cost = self.error()
      prev_w = self.w.copy()
      nz_idcs = self.w > 0
      res = nnls(self.A[:, nz_idcs], self.b, maxiter=100*self.A.shape[1])
      self.w[nz_idcs] = res[0]
      new_cost = self.error()
      if new_cost > prev_cost*(1.+util.TOL):
        raise NumericalPrecisionError('self.optimize() returned a solution with increasing error. Numeric limit possibly reached: preverr = ' + str(prev_cost) + ' err = ' + str(new_cost) + '.\n \
                                        If the two errors are very close, try running bc.util.tolerance(tol) with tol > current tol = ' + str(util.TOL) + ' before running')
    except NumericalPrecisionError as e:
      self.log.warning(e)
      self.w = prev_w
      self.reached_numeric_limit = True
      return 
开发者ID:trevorcampbell,项目名称:bayesian-coresets,代码行数:18,代码来源:snnls.py

示例3: iter_solver

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def iter_solver(self, A, W, H, k, it):
        if not sps.issparse(A):
            for j in iter(range(0, H.shape[0])):
                res = opt.nnls(W, A[:, j])
                H[j, :] = res[0]
        else:
            for j in iter(range(0, H.shape[0])):
                res = opt.nnls(W, A[:, j].toarray()[:, 0])
                H[j, :] = res[0]

        if not sps.issparse(A):
            for j in iter(range(0, W.shape[0])):
                res = opt.nnls(H, A[j, :])
                W[j, :] = res[0]
        else:
            for j in iter(range(0, W.shape[0])):
                res = opt.nnls(H, A[j, :].toarray()[0,:])
                W[j, :] = res[0]
        return (W, H) 
开发者ID:kimjingu,项目名称:nonnegfac-python,代码行数:21,代码来源:nmf.py

示例4: _mge_1d

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def _mge_1d(r_array, flux_r, N=20, linspace=False):
    """

    :param r_array:
    :param flux_r:
    :param N:
    :return:
    """
    if linspace is True:
        sigmas = np.linspace(r_array[0], r_array[-1] / 2, N + 2)[1:-1]
    else:
        sigmas = np.logspace(np.log10(r_array[0]), np.log10((r_array[-1] + 0.0000001) / 2.), N + 2)[1:-1]
    # sigmas = np.linspace(r_array[0], r_array[-1]/2, N + 2)[1:-1]

    A = np.zeros((len(flux_r), N))
    for j in np.arange(A.shape[1]):
        A[:, j] = gaussian(r_array, sigmas[j], 1.)
    amplitudes, norm = nnls(A, flux_r)
    return amplitudes, sigmas, norm 
开发者ID:sibirrer,项目名称:lenstronomy,代码行数:21,代码来源:multi_gauss_expansion.py

示例5: change_component_set

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def change_component_set(self, new_component_list):
        """
        Change the set of basis components without 
        changing the bulk composition. 

        Will raise an exception if the new component set is 
        invalid for the given composition.

        Parameters
        ----------
        new_component_list : list of strings
            New set of basis components.
        """
        composition = np.array([self.atomic_composition[element]
                                for element in self.element_list])
        component_matrix = np.zeros((len(new_component_list), len(self.element_list)))
        
        for i, component in enumerate(new_component_list):
            formula = dictionarize_formula(component)
            for element, n_atoms in formula.items():
                component_matrix[i][self.element_list.index(element)] = n_atoms

        sol = nnls(component_matrix.T, composition)
        if sol[1] < 1.e-12:
            component_amounts = sol[0]
        else:
            raise Exception('Failed to change component set. '
                            'Could not find a non-negative least squares solution. '
                            'Can the bulk composition be described with this set of components?')

        composition = OrderedCounter(dict(zip(new_component_list, component_amounts)))
        self.__init__(composition, 'molar') 
开发者ID:geodynamics,项目名称:burnman,代码行数:34,代码来源:composition.py

示例6: solution_bounds

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def solution_bounds(endmember_occupancies):
    """
    Parameters
    ----------
    endmember_occupancies : 2d array of floats
        A 1D array for each endmember in the solid solution,
        containing the number of atoms of each element on each site.

    Returns
    -------
    solution_bounds : 2d array of floats
        An abbreviated version of endmember_occupancies, 
        where the columns represent the independent compositional 
        bounds on the solution
    """
    # Find bounds for the solution
    i_sorted =zip(*sorted([(i,
                            sum([1 for val in endmember_occupancies.T[i]
                                 if val>1.e-10]))
                           for i in range(len(endmember_occupancies.T))
                                          if np.any(endmember_occupancies.T[i] > 1.e-10)],
                          key=lambda x: x[1]))[0]

    solution_bounds = endmember_occupancies[:,i_sorted[0],np.newaxis]
    for i in i_sorted[1:]:
        if np.abs(nnls(solution_bounds, endmember_occupancies.T[i])[1]) > 1.e-10:
            solution_bounds = np.concatenate((solution_bounds,
                                              endmember_occupancies[:,i,np.newaxis]),
                                             axis=1)
    return solution_bounds 
开发者ID:geodynamics,项目名称:burnman,代码行数:32,代码来源:processchemistry.py

示例7: optimize_weights

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def optimize_weights(num_bones, Tr, C, verts0, K, nnls_soft_constr_weight=1.e+4):
    """ optimize for blending weights according to section 4.4 """
    # reshape Tr according to section 4.3 into 
    # a matrix of d * P of 4-vectors
    # TODO: not sure if this is correct already
    #       during iteration this step sometimes increases the residual :-(
    num_verts = verts0.shape[0]
    Tr1 = Tr.reshape((-1, num_bones, 4))
    new_W = np.zeros((num_bones, num_verts))
    for i in xrange(num_verts):
        # form complete system matrix Sigma * w = y
        Sigma = np.inner(Tr1, V.hom4(verts0[i]))
        #import ipdb; ipdb.set_trace()
        y = C[:,i]
        # choose K columns that individually best explain the residual
        error = ( (Sigma - y[:,np.newaxis]) ** 2 ).sum(axis=0)
        k_best = np.argsort(error)[:K]
        # solve nonlinear least squares problem
        # with additional convexity constraint sum(k_weighs) = 1
        Sigma = Sigma[:,k_best]
        #k_weights0 = W[k_best, i]
        k_weights, _ = nnls(
            np.vstack((Sigma, nnls_soft_constr_weight * np.ones(K))),
            np.append(y, nnls_soft_constr_weight))
        new_W[k_best, i] = k_weights
    return new_W 
开发者ID:tneumann,项目名称:skinning_decomposition_kavan,代码行数:28,代码来源:decompose_kavan.py

示例8: test_nnls

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def test_nnls(self):
        a = arange(25.0).reshape(-1,5)
        x = arange(5.0)
        y = dot(a,x)
        x, res = nnls(a,y)
        assert_(res < 1e-7)
        assert_(norm(dot(a,x)-y) < 1e-7) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:9,代码来源:test_nnls.py

示例9: __init__

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def __init__(self, x, y, n_blocks=None, nn=False, separators=None):
        Jackknife.__init__(self, x, y, n_blocks, separators)
        if nn:  # non-negative least squares
            func = lambda x, y: np.atleast_2d(nnls(x, np.array(y).T[0])[0])
        else:
            func = lambda x, y: np.atleast_2d(
                np.linalg.lstsq(x, np.array(y).T[0])[0])

        self.est = func(x, y)
        self.delete_values = self.delete_values(x, y, func, self.separators)
        self.pseudovalues = self.delete_values_to_pseudovalues(
            self.delete_values, self.est)
        (self.jknife_est, self.jknife_var, self.jknife_se, self.jknife_cov) =\
            self.jknife(self.pseudovalues) 
开发者ID:JonJala,项目名称:mtag,代码行数:16,代码来源:jackknife.py

示例10: test_maxiter

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def test_maxiter(self):
        # test that maxiter argument does stop iterations
        # NB: did not manage to find a test case where the default value
        # of maxiter is not sufficient, so use a too-small value
        rndm = np.random.RandomState(1234)
        a = rndm.uniform(size=(100, 100))
        b = rndm.uniform(size=100)
        with assert_raises(RuntimeError):
            nnls(a, b, maxiter=1) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:11,代码来源:test_nnls.py

示例11: _reweight

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def _reweight(self, f):
    self.w[f] = 1.
    nz_idcs = self.w > 0
    res = nnls(self.A[:, nz_idcs], self.b, maxiter=100*self.A.shape[1])
    self.w[nz_idcs] = res[0]
    return 
开发者ID:trevorcampbell,项目名称:bayesian-coresets,代码行数:8,代码来源:orthopursuit.py

示例12: select

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def select(self):
    #do least squares on active set
    res = nnls(self.A[:, self.active_idcs].T, self.b, maxiter=100*self.A.shape[1])

    x_opt = self.A.dot(res[0])
    w_opt = np.zeros(self.w.shape[0])
    w_opt[self.active_idcs] = res[0]
    xw = self.A.dot(self.w)
    sdir = x_opt - xw
    sdir /= np.sqrt((sdir**2).sum())

    #do line search towards x_opt

    #find earliest gamma for which a variable joins the active set
    #anywhere gamma_denom = 0 or gamma < 0, the variable never enters the active set 
    gamma_nums = (sdir - self.x).dot(self.b - xw)
    gamma_denoms = (sdir - self.x).dot(x_opt - xw)
    good_idcs = np.logical_not(np.logical_or(gamma_denoms == 0, gamma_nums*gamma_denoms < 0))
    gammas = np.inf*np.ones(gamma_nums.shape[0])
    gammas[good_idcs] = gamma_nums[good_idcs]/gamma_denoms[good_idcs]
    f_least_angle = gammas.argmin()
    gamma_least_angle = gammas[f_least_angle]

    #find earliest gamma for which a variable leaves the active set
    f_leave_active = -1
    gamma_leave_active = np.inf
    gammas[:] = np.inf
    leave_idcs = w_opt < 0
    gammas[leave_idcs] = self.wts[leave_idcs]/(self.wts[leave_idcs] - w_opt[leave_idcs])
    f_leave_active = gammas.argmin()
    gamma_leave_active = gammas[f_leave_active] 
开发者ID:trevorcampbell,项目名称:bayesian-coresets,代码行数:33,代码来源:lar.py

示例13: nnls

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def nnls(A, B):
    def func(b):
        return optimize.nnls(A, b)[0]
    return np.array(map(func, B)) 
开发者ID:yihui-he,项目名称:channel-pruning,代码行数:6,代码来源:decompose.py

示例14: _train

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
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.

        Parameters
        ----------
        method : str, optional
            Description
        lam_drop : float, optional
            Description
        lam_pot : float, optional
            Description
        lam_avi : float, optional
            Description
        **kwargs
            Description
        '''
        self.lam_pot = lam_pot
        self.lam_avi = lam_avi
        self.lam_drop = lam_drop
        if len(self.train_titers)==0:
            raise InsufficientDataException("Error: No titers in training set.")
        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)} 
开发者ID:nextstrain,项目名称:augur,代码行数:43,代码来源:titer_model.py

示例15: fit_nnls

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import nnls [as 别名]
def fit_nnls(self):
        from scipy.optimize import nnls
        return nnls(self.design_matrix, self.titer_dist)[0] 
开发者ID:nextstrain,项目名称:augur,代码行数:5,代码来源:titer_model.py


注:本文中的scipy.optimize.nnls方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。