Scipy NNLS 使用掩码

Scipy NNLS using mask

我正在使用 scipy 执行非负最小二乘法。一个简单的例子如下:

import numpy as np
from scipy.optimize import nnls

A = np.array([[60, 70, 120, 60],[60, 90, 120, 70]], dtype='float32')
b = np.array([6, 5])
x, res = nnls(A, b)

现在,我的情况是 Ab 中的某些条目可能会丢失 (np.NaN)。像,

A_2 = A.copy()
A_2[0,2] = np.NaN

当然,运行 A_2 上的 NNLS,b 将不起作用,因为 scipy 不期望 infnan

我们如何执行 NNLS 从计算中屏蔽掉丢失的条目。实际上,这应该转化为

Minimize |(A_2.x- b)[mask]|

其中掩码可以定义为:

mask = ~np.isnan(A_2)

一般来说,Ab 中都可能缺少条目。

可能有帮助:

[1] How to include constraint to Scipy NNLS function solution so that it sums to 1

我认为您可以先计算掩码(确定要包括哪些点),然后执行 NNLS。给定面具

In []: mask
Out[]: 
array([[ True,  True, False,  True],
       [ True,  True,  True,  True]], dtype=bool)

您可以通过沿第一个轴使用 np.all 检查列中的所有值是否都是 True 来验证是否包含一个点。

In []: np.all(mask, axis=0)
Out[]: array([ True,  True, False,  True], dtype=bool)

这可以用作 A 的列掩码。

In []: nnls(A_2[:,np.all(mask, axis=0)], b)
Out[]: (array([ 0.09166667,  0.        ,  0.        ]), 0.7071067811865482)

同样的想法可以用于b构造行掩码。