Skip to main content
 首页 » 编程设计

python之在 SCIPY 线性规划方案中缩放矩阵变量的最佳方法

2024年10月24日14jillzhang

我在 NNLS in scipy 下实现了以下优化方案.

import numpy as np 
from scipy.optimize import nnls  
from scipy import stats 
 
#Define problem 
A = np.array([[60., 90., 120.],  
              [30., 120., 90.]]) 
 
b = np.array([6700.5, 699.,]) 
 
# Add ones to ensure the solution sums to 1 
b = np.hstack([b,1.0]) 
A = np.vstack([A,np.ones(3)]) 
 
x, rnorm = nnls(A,b) 
print x 
# the solution is 
# [ 93.97933792   0.           0.        ] 
# we expect it to sum to 1 if it's not skewed 

如您所见,b 向量比 A 中的值高得多。 我的问题是扩展 A 和 b 的最佳/合理方法是什么,以便解决方案 没有倾斜。

注意A和b都是未经预处理的基因表达原始数据。

请您参考如下方法:

如果你想包含等式约束,你不能真正使用 nnls 例程,因为它不适合等式。如果你受限于 scipy 提供的内容,你可以使用这个:

import numpy as np 
from scipy.optimize import minimize 
 
#Define problem 
A = np.array([[60., 90., 120.],  
              [30., 120., 90.]]) 
 
b = np.array([6700.5, 699.,]) 
 
#----------------------------- 
# I tried rescaling the data by adding this two lines, 
# so that they're in same scale. 
# but why the solution is different? 
#    x: array([ 1.,  0.,  0.]) 
# What's the correct way to go? 
#----------------------------- 
# A = A/np.linalg.norm(A,axis=0) 
# b = b/np.linalg.norm(b)     
 
def f(x): 
    return np.linalg.norm(A.dot(x) - b) 
 
cons ={'type': 'eq', 
       'fun': lambda x: sum(x) - 1} 
 
x0 = [1, 0, 0]  # initial guess 
minimize(f, x0, method='SLSQP', bounds=((0, np.inf),)*3, constraints=cons) 

输出:

 status: 0 
 success: True 
    njev: 2 
    nfev: 10 
     fun: 6608.620222860367 
       x: array([ 0.,  0.,  1.]) 
 message: 'Optimization terminated successfully.' 
     jac: array([ -62.50927734, -100.675354  , -127.78314209,    0.        ]) 
     nit: 2 

这会直接最小化目标函数,同时还会施加您感兴趣的等式约束。

如果速度很重要,您可以添加 jacobian 和 hessian 信息,或者更好的是,使用适当的 QP 求解器,由 cvxopt 提供.