【问题标题】:Is there a Julia analogue to numpy.argmax?是否有 numpy.argmax 的 Julia 类似物?
【发布时间】:2016-01-13 05:27:18
【问题描述】:

在 Python 中,有numpy.argmax:

In [7]: a = np.random.rand(5,3)

In [8]: a
Out[8]: 
array([[ 0.00108039,  0.16885304,  0.18129883],
       [ 0.42661574,  0.78217538,  0.43942868],
       [ 0.34321459,  0.53835544,  0.72364813],
       [ 0.97914267,  0.40773394,  0.36358753],
       [ 0.59639274,  0.67640815,  0.28126232]])

In [10]: np.argmax(a,axis=1)
Out[10]: array([2, 1, 2, 0, 1])

是否有类似于 Numpy 的 argmax 的 Julia?我只找到了一个indmax,它只接受一个向量,而不是一个二维数组np.argmax

【问题讨论】:

标签: numpy julia argmax


【解决方案1】:

最快的实现通常是findmax(如果你愿意,它允许你一次减少多个维度):

julia> a = rand(5, 3)
5×3 Array{Float64,2}:
 0.867952  0.815068   0.324292
 0.44118   0.977383   0.564194
 0.63132   0.0351254  0.444277
 0.597816  0.555836   0.32167 
 0.468644  0.336954   0.893425

julia> mxval, mxindx = findmax(a; dims=2)
([0.8679518267243425; 0.9773828942695064; … ; 0.5978162823947759; 0.8934254589671011], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 2); … ; CartesianIndex(4, 1); CartesianIndex(5, 3)])

julia> mxindx
5×1 Array{CartesianIndex{2},2}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 2)
 CartesianIndex(3, 1)
 CartesianIndex(4, 1)
 CartesianIndex(5, 3)

【讨论】:

【解决方案2】:

根据 Numpy 文档,argmax 提供以下功能:

numpy.argmax(a, axis=None, out=None)

沿轴返回最大值的索引。

我怀疑单个 Julia 函数可以做到这一点,但将 mapslicesargmax 结合起来就是门票:

julia> a = [ 0.00108039  0.16885304  0.18129883;
             0.42661574  0.78217538  0.43942868;
             0.34321459  0.53835544  0.72364813;
             0.97914267  0.40773394  0.36358753;
             0.59639274  0.67640815  0.28126232] :: Array{Float64,2}

julia> mapslices(argmax,a,dims=2)
5x1 Array{Int64,2}:
 3
 2
 3
 1
 2

当然,因为 Julia 的数组索引是从 1 开始的(而 Numpy 的数组索引是从 0 开始的),所以生成的 Julia 数组的每个元素与生成的 Numpy 数组中的相应元素相比偏移 1。你可能想也可能不想调整它。

如果你想得到一个向量而不是二维数组,你可以简单地在表达式末尾加上[:]

julia> b = mapslices(argmax,a,dims=2)[:]
5-element Array{Int64,1}:
 3
 2
 3
 1
 2

【讨论】:

【解决方案3】:

为了补充 jub0bs 的答案,Julia 1+ 中的 argmax 反映了 np.argmax 的行为,通过将 axis 替换为 dims 关键字,返回 CarthesianIndex 而不是沿给定维度的索引:

julia>  a = [ 0.00108039  0.16885304  0.18129883;

                0.42661574  0.78217538  0.43942868;      

                0.34321459  0.53835544  0.72364813;      

                0.97914267  0.40773394  0.36358753;      

                0.59639274  0.67640815  0.28126232] :: Array{Float64,2}

julia> argmax(a, dims=2)
5×1 Array{CartesianIndex{2},2}:
CartesianIndex(1, 3)
CartesianIndex(2, 2)
CartesianIndex(3, 3)
CartesianIndex(4, 1)
CartesianIndex(5, 2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    相关资源
    最近更新 更多