将 numpy 1d 数组和 3d 数组的每个元素相乘的有效方法



我想将 1dArray 的每个元素和 3dArray 的每个矩阵相乘for而不循环。

arr1d2=np.array([1,2])
arr3d222=np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
# Correct Solution is below
for i1 in range(len(arr1d2)):
print(arr1d2[i1]*arr3d222[i1])

我试图找到更有效的方法来做到这一点。我想这个for循环是我代码的瓶颈。

尝试:

print(arr1d2[:]*arr3d222[:])

感谢您的任何帮助。

答案的时间比较

import time
import numpy as np
dim=250
arr1d=np.arange(dim)
arr3d,val_arr3=np.zeros([dim,dim,dim]),1
result=np.zeros(np.shape(arr3d))
for i1 in range(len(arr3d)):
for i2 in range(len(arr3d[0])):
for i3 in range(len(arr3d[0,0])):
arr3d[i1,i2,i3]=val_arr3
val_arr3=val_arr3+1
start_time1 = time.time()
# Correct Solution
for i1 in range(dim):
result[i1]=arr1d[i1]*arr3d[i1]  
print("Method 1 : For Loopn%s seconds." % (time.time() - start_time1))
result=np.zeros(np.shape(arr3d))
start_time2 = time.time()
result=arr1d.reshape(len(arr3d),1,1) * arr3d
print("Method 2 : arr1d.reshape(len(arr3d),1,1) * arr3d n%s seconds." % (time.time() - start_time2))
result=np.zeros(np.shape(arr3d))
start_time3 = time.time()
result=arr1d[:, np.newaxis, np.newaxis] * arr3d
print("Method 3 : arr1d[:, np.newaxis, np.newaxis] * arr3d n%s seconds." % (time.time() - start_time3))

结果是

Method 1 : For Loop
0.06770634651184082 seconds.
Method 2 : arr1d.reshape(len(arr3d),1,1) * arr3d 
0.05272269248962402 seconds.
Method 3 : arr1d[:, np.newaxis, np.newaxis] * arr3d 
0.048714399337768555 seconds.

您可以使用np.newaxis使维度数匹配:

arr1d2[:, np.newaxis, np.newaxis] * arr3d222

只需将第一个数组设置为正确的形状:

arr1d2.reshape(len(arr3d222),1,1) * arr3d222

相关内容

  • 没有找到相关文章