numpy:高于阈值的最小绝对值
numpy: minimal absolute value above threshold
在多维矩阵中,我喜欢在公差值之上有最小的绝对值。
import numpy as np
np.random.seed(0)
matrix = np.random.randn(5,1,10)
tolerance = 0.1
np.amin(np.abs(matrix), axis=-1)
# array([[0.10321885],
# [0.12167502],
# [0.04575852], # <- should not appear, as below tolerance
# [0.15494743],
# [0.21274028]])
以上代码 returns 最后一个维度的绝对最小值。但我想在确定最小值时忽略小值(接近 0)。因此,在我的 tolerance = 0.1
示例中,第三行应包含第二小的值。
使用 matrix[np.abs(matrix) >= tolerance]
我可以 select 高于 tolerance
的值,但这会使数组变平,因此 np.amin(...)
无法再确定最后一个维度的最小值。
您可以将小于 0.1 的值替换为例如 1,使用 np.where:
np.where(np.abs(matrix)< 0.1,1,np.abs(matrix))
然后在上面应用 np.amin :
np.amin(np.where(np.abs(matrix)< 0.1,1,np.abs(matrix)),axis=-1)
结果:
array([[0.10321885],
[0.12167502],
[0.18718385],
[0.15494743],
[0.21274028]])
在多维矩阵中,我喜欢在公差值之上有最小的绝对值。
import numpy as np
np.random.seed(0)
matrix = np.random.randn(5,1,10)
tolerance = 0.1
np.amin(np.abs(matrix), axis=-1)
# array([[0.10321885],
# [0.12167502],
# [0.04575852], # <- should not appear, as below tolerance
# [0.15494743],
# [0.21274028]])
以上代码 returns 最后一个维度的绝对最小值。但我想在确定最小值时忽略小值(接近 0)。因此,在我的 tolerance = 0.1
示例中,第三行应包含第二小的值。
使用 matrix[np.abs(matrix) >= tolerance]
我可以 select 高于 tolerance
的值,但这会使数组变平,因此 np.amin(...)
无法再确定最后一个维度的最小值。
您可以将小于 0.1 的值替换为例如 1,使用 np.where:
np.where(np.abs(matrix)< 0.1,1,np.abs(matrix))
然后在上面应用 np.amin :
np.amin(np.where(np.abs(matrix)< 0.1,1,np.abs(matrix)),axis=-1)
结果:
array([[0.10321885],
[0.12167502],
[0.18718385],
[0.15494743],
[0.21274028]])