【问题标题】:Scipy NNLS using mask使用掩码的 Scipy NNLS
【发布时间】:2017-03-21 10:05:08
【问题描述】:

我正在使用 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, b 上运行 NNLS 将无法正常工作,因为 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

【问题讨论】:

    标签: python numpy optimization scipy lmfit


    【解决方案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来构造行掩码。

    【讨论】:

    • 谢谢。这是完美的!
    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 2020-04-18
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多