Python 如何获得numpy矩阵中绝对值的最高元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17794266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the highest element in absolute value in a numpy matrix?
提问by qed
Here is what I am currently doing, it works but it's a little cumbersome:
这是我目前正在做的事情,它有效,但有点麻烦:
x = np.matrix([[1, 1], [2, -3]])
xmax = x.flat[abs(x).argmax()]
回答by Daniel
The only thing that I could think of, which looks even worse, is:
我唯一能想到的,看起来更糟的是:
xmax=x[np.unravel_index(abs(x).argmax(), x.shape)]
回答by A.Wan
EDIT: My answer is off-topic, sorry. As Ophion pointed out this would return the index, not the value - you have to use flat
with my "xmax
" (which is really "xmaxInd
") to get the proper value. Ergo I think your solution is best.
编辑:我的回答是题外话,抱歉。正如 Ophion 指出的那样,这将返回索引,而不是值——您必须使用flat
我的“xmax
”(实际上是“xmaxInd
”)来获得正确的值。因此,我认为您的解决方案是最好的。
After experimenting a bit I realized you can just do this:
经过一番试验后,我意识到你可以这样做:
x = np.matrix([[1,1], [2,-3]])
absX = abs(x)
xmax = argmax(absX)
It seems that numpy allows you to take the abs
as well as the argmax
of a matrix. How convenient!
看来,numpy的让你拿abs
,以及作为argmax
一个矩阵。多么方便!
timeit
checks:
timeit
检查:
def meth1():
x = np.matrix([[1,1],[2,-3]])
xmax = x.flat[abs(x).argmax()]
def meth2():
x = np.matrix([[1,1],[2,-3]])
xmax = argmax(abs(x))
t1 = timeit.Timer("meth1()","from __main__ import meth1")
t2 = timeit.Timer("meth2()","from __main__ import meth2")
mean(t1.repeat(1,100000))
gives Out[99]: 7.854323148727417
mean(t2.repeat(1,100000))
gives Out[98]: 7.7788529396057129
mean(t1.repeat(1,100000))
给予Out[99]: 7.854323148727417
mean(t2.repeat(1,100000))
给予Out[98]: 7.7788529396057129
So meth2()
is slightly faster. Probably because it doesn't involve calling flat
.
所以meth2()
稍微快一点。可能是因为它不涉及调用flat
.
回答by aestrivex
I think this is a pretty straightforward way, which might be slightly better if code readability is your primary concern. But really, your way is just as elegant.
我认为这是一种非常简单的方法,如果代码可读性是您的主要关注点,这可能会稍微好一些。但实际上,你的方式同样优雅。
np.min(x) if np.max(abs(x)) == abs(np.min(x)) else np.max(x)
回答by Martin Spacek
I was looking for a way to get the signed values of the maximum absolute values of an N-dimensional array along a specified axis, which none of these answers handle. So, I put together a function to do it. No promises, but it works as far as I've tested it:
我正在寻找一种方法来获取沿指定轴的 N 维数组的最大绝对值的有符号值,这些答案都没有处理。所以,我组合了一个函数来做到这一点。没有承诺,但据我测试它有效:
def maxabs(a, axis=None):
"""Return slice of a, keeping only those values that are furthest away
from 0 along axis"""
maxa = a.max(axis=axis)
mina = a.min(axis=axis)
p = abs(maxa) > abs(mina) # bool, or indices where +ve values win
n = abs(mina) > abs(maxa) # bool, or indices where -ve values win
if axis == None:
if p: return maxa
else: return mina
shape = list(a.shape)
shape.pop(axis)
out = np.zeros(shape, dtype=a.dtype)
out[p] = maxa[p]
out[n] = mina[n]
return out
回答by JoeCondron
The value you're looking for has to be either x.max()
or x.min()
so you could do
您正在寻找的价值,必须为x.max()
或x.min()
那么你可以这样做
max(x.min(), x.max(), key=abs)
which is similar to aestrivex's solution but perhaps more readable? Note this will return the minimum in the case where x.min()
and x.max()
have the same absolute value e.g. -5
and 5
. If you have a preference just order the inputs to max
accordingly.
这类似于 aestrivex 的解决方案,但可能更具可读性?请注意,在x.min()
和x.max()
具有相同绝对值(例如-5
和 )的情况下,这将返回最小值5
。如果您有偏好,只需相应地对输入进行max
排序。
回答by kxr
This one computes the absolute max'es fast - respecting an arbitrary axis
argument in the same way as np.max
and np.argmax
themselves do.
这个快速计算绝对最大值 -axis
以np.max
与np.argmax
他们自己相同的方式尊重任意参数。
def absmaxND(a, axis=None):
amax = a.max(axis)
amin = a.min(axis)
return np.where(-amin > amax, amin, amax)
For long arrays its about 2.5x faster than a.flat[abs(a).argmax()]
even for the simple case axis=None
- because it doesn't render abs() of the original big array.
对于长数组,它a.flat[abs(a).argmax()]
甚至比简单情况快 2.5 倍axis=None
- 因为它不呈现原始大数组的 abs() 。
回答by Дмитрий Пасько
I use it
我用这个
dt = np.random.rand(50000,500)-0.5
# ur
xmax = dt.flat[abs(dt).argmax()] #230 ms
# new
newdt = np.array([dt.min(),dt.max()]) # 56ms
xmax = newdt.flat[abs(newdt).argmax()] # 4ms
it is almost 4 times faster (60 ms against 230)!!
它几乎快了 4 倍(60 毫秒对 230 毫秒)!!