如何将向量的每个元素提升到另一个向量的每个元素的幂?

How to raise every element of a vector to the power of every element of another vector?

我想通过从 0 到 5 的升幂来提高向量:

import numpy as np

a = np.array([1, 2, 3]) # list of 11 components
b = np.array([0, 1, 2, 3, 4]) # power
c = np.power(a,b)

期望的结果是:

c = [[1**0, 1**1, 1**2, 1**3, 1**4], [2**0, 2**1, ...], ...]

我不断收到此错误:

ValueError: operands could not be broadcast together with shapes (3,) (5,)

这是一个解决方案:

num_of_powers = 5
num_of_components = 11

a = []
for i in range(1,num_of_components + 1):
    a.append(np.repeat(i,num_of_powers))
b = list(range(num_of_powers))
c = np.power(a,b)

输出 c 看起来像:

array([[    1,     1,     1,     1,     1],
       [    1,     2,     4,     8,    16],
       [    1,     3,     9,    27,    81],
       [    1,     4,    16,    64,   256],
       [    1,     5,    25,   125,   625],
       [    1,     6,    36,   216,  1296],
       [    1,     7,    49,   343,  2401],
       [    1,     8,    64,   512,  4096],
       [    1,     9,    81,   729,  6561],
       [    1,    10,   100,  1000, 10000],
       [    1,    11,   121,  1331, 14641]], dtype=int32)

您的解决方案显示广播错误,因为根据 documentation:

If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

c = [[x**y for y in b] for x in a]
c = np.asarray(list(map(lambda x: np.power(a,x), b))).transpose()

您需要先创建一个矩阵,其中的行是每个数字的重复。这可以通过 np.tile:

来完成
mat = np.tile(a, (len(b), 1)).transpose()

然后按元素计算它的 b 次方:

np.power(mat, b)

总计:

import numpy as np

nums = np.array([1, 2, 3]) # list of 11 components
powers = np.array([0, 1, 2, 3, 4]) # power

print(np.power(np.tile(nums, (len(powers), 1)).transpose(), powers))

这将给出:

[[ 1  1  1  1  1]   # == [1**0, 1**1, 1**2, 1**3, 1**4]
 [ 1  2  4  8 16]   # == [2**0, 2**1, 2**2, 2**3, 2**4]
 [ 1  3  9 27 81]]  # == [3**0, 3**1, 3**2, 3**3, 3**4]

一个解决方案是向数组添加一个新维度a

c = a[:,None]**b

# Using broadcasting : 
# (3,1)**(4,) --> (3,4)
#
#     [[1],
# c =  [2], ** [0,1,2,3,4]
#      [3]]

有关更多信息,请查看 numpy broadcasting documentation