小编Car*_*osH的帖子

脾气暴躁:argmax多轴无循环

我有一个N维数组(名为A)。对于A的第一轴的每一行,我想获得沿A的其他轴的最大值的坐标。然后,我将返回一个二维数组,其中包含第一轴的每一行的最大值的坐标的A。

我已经使用循环解决了我的问题,但是我想知道是否有更有效的方法可以做到这一点。我当前的解决方案(对于示例数组A)如下:

import numpy as np

A=np.reshape(np.concatenate((np.arange(0,12),np.arange(0,-4,-1))),(4,2,2))
maxpos=np.empty(shape=(4,2))
for n in range(0, 4):
    maxpos[n,:]=np.unravel_index(np.argmax(A[n,:,:]), A[n,:,:].shape)
Run Code Online (Sandbox Code Playgroud)

在这里,我们将有:

A: 
[[[ 0  1]
  [ 2  3]]

 [[ 4  5]
  [ 6  7]]

 [[ 8  9]
  [10 11]]

 [[ 0 -1]
  [-2 -3]]]

maxpos:
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 0.  0.]]
Run Code Online (Sandbox Code Playgroud)

如果有多个最大化器,我不介意选择哪个。

我尝试使用np.apply_over_axes,但是我没有设法使它返回我想要的结果。

python numpy vectorization argmax

4
推荐指数
1
解决办法
3569
查看次数

Python 3 - 使用不同的args处理相同的函数

在python 3中,我试图同时运行多个参数的相同函数.我在Windows 7中使用Python 3.5.2,Anaconda 4.1.1(64位)中的多处理.我收到有关spawn.py的以下错误:

在当前进程完成其自举阶段之前,已尝试启动新进程.

这可能意味着您没有使用fork来启动子进程,而您忘记在主模块中使用正确的习惯用法:

if __name__ == '__main__':
    freeze_support()
    ...
Run Code Online (Sandbox Code Playgroud)

如果程序不会被冻结以生成可执行文件,则可以省略"freeze_support()"行.

我的代码是:

from multiprocessing import Process

#Function to be run
def savedatetime(password,rangestart,rangeend):
    print((password,rangestart,rangeend))

# Inputs to the function
passwords=['p0','p1','p2']
ranges=[(1,10),(10,20),(20,30)]

# Creating the list of processes to append
fileind=0
proc=[]
for rangeind in range(0,len(passwords)):    
    password=passwords[fileind]
    rangestart=ranges[fileind][0]
    rangeend=ranges[fileind][1]
    p = Process(target=savedatetime,args=(password,rangestart,rangeend))            
    proc.append(p)
    fileind=fileind+1
    # running sequentially to check that the function works
    savedatetime(password,rangestart,rangeend)

print(proc)

# Attempting to run simultaneously. This is where the error occurs:
for p in …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing python-3.x python-multiprocessing

2
推荐指数
1
解决办法
2403
查看次数