如何在Scipy中找到已弃用函数的替代方法?

5
例如,根据文档,这个threshold函数已经被弃用。
然而,文档没有提到任何替代方法。它只是在未来被废弃了吗?还是已经有了替代方法?如果有,如何找到替代函数?

1
正如文档所述,只需使用 numpy.clip() - 这是 scipy 列表 上的对话。 - AChampion
@AChampion 谢谢!但是我觉得numpy.clip有些不同。比如,怎样将小数变为零?numpy.clip只会将数值限制在区间的边界上。 - user15964
2
如果你有一个数组 a,那么 a[a < cutoff] = 0 将会把所有小于 cutoff 的元素都变成零。 - σηγ
@σηγ 非常感谢您。 - user15964
2个回答

3

需要花点功夫来查找,但是这里是 threshold 的代码(scipy/stats/mstats_basic.py):

def threshold(a, threshmin=None, threshmax=None, newval=0):
    a = ma.array(a, copy=True)
    mask = np.zeros(a.shape, dtype=bool)
    if threshmin is not None:
        mask |= (a < threshmin).filled(False)

    if threshmax is not None:
        mask |= (a > threshmax).filled(False)

    a[mask] = newval
    return a

但在此之前,我从文档中逆向工程了它:
文档中的示例数组:
In [152]: a = np.array([9, 9, 6, 3, 1, 6, 1, 0, 0, 8])
In [153]: stats.threshold(a, threshmin=2, threshmax=8, newval=-1)
/usr/local/bin/ipython3:1: DeprecationWarning: `threshold` is deprecated!
stats.threshold is deprecated in scipy 0.17.0
  #!/usr/bin/python3
Out[153]: array([-1, -1,  6,  3, -1,  6, -1, -1, -1,  8])

建议的替换方案
In [154]: np.clip(a,2,8)
Out[154]: array([8, 8, 6, 3, 2, 6, 2, 2, 2, 8])
....

将剪裁尽量减少或最大化是有意义的;另一方面,阈值将所有超出范围的值转换为其他值,例如0或-1。听起来并不那么有用。但实现起来并不难:

In [156]: mask = (a<2)|(a>8)
In [157]: mask
Out[157]: array([ True,  True, False, False,  True, False,  True,  True,  True, False], dtype=bool)
In [158]: a1 = a.copy()
In [159]: a1[mask] = -1
In [160]: a1
Out[160]: array([-1, -1,  6,  3, -1,  6, -1, -1, -1,  8])

本质上来说,这和我引用的代码是一样的,只是在处理最小值或最大值的None情况方面有所不同。


谢谢。看起来np.clip并不是threshold的直接替代品。 - user15964

0

就算价值不高,np.clip如果使用得当,可以直接替代threshold:

np.clip(array-threshold,0,1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接