gpt4 book ai didi

python - 是否可以在没有 for 循环的情况下将矩阵 A 中的所有每一列乘以矩阵 B 的每一列?

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:57 26 4
gpt4 key购买 nike

我有三个矩阵 W HV。我想获取 keep,它存储 V 的所有列和 W 的每一列之间的逐元素乘法,并逐行求和。

(V有6行,W也有6行。W的每一列(有6个元素)乘以6个元素V列逐列计算。然后按行对结果求和)

W = np.random.randint(4,6, size=(6, 4))
H = np.random.randint(1,3, size=(4, 5))
V = np.dot(W,H) + 1
keep = np.array([]).reshape(0,6)

print W
>>[[4 4 5 5]
[4 4 4 4]
[4 5 5 4]
[4 5 5 5]
[5 4 4 5]
[5 4 4 5]]
print V
>>[[28 33 32 37 24]
[25 29 29 33 21]
[28 33 33 37 24]
[30 35 34 39 25]
[28 32 32 37 23]
[28 32 32 37 23]]

# I want the result from only two from four rows of W
group = 2
for k in xrange(group):
# multiply all of each column of V by k-th column of W and sum in row
keep = np.vstack([keep, sum(V[:,:].T*W[:,k])])

print keep, keep.shape
>>[[ 616. 548. 620. 652. 760. 760.]
[ 616. 548. 775. 815. 608. 608.]] (2L, 6L)

我想知道这可以在没有 for 循环的情况下完成吗?像 sum(V[:,:].T*W[:,0:1] 虽然,我认为这是不可能的,因为 W 的每一列都有逐步乘以矩阵 V,我相信有人有更好的主意(或确认不能)。

我尽量避免 for 循环,因为这是长算法的一部分,我希望当 group 达到数百时它可以非常快。

最佳答案

似乎非常适合 np.einsum ,因为我们需要保持两个输入之间的第一个轴对齐并将其保留在输出中 -

np.einsum('ij,ik->ki',V,W)

sample 运行-

In [2]: W = np.random.randint(4,6, size=(6, 4))
...: H = np.random.randint(1,3, size=(4, 5))
...: V = np.dot(W,H) + 1
...: keep = np.array([]).reshape(0,6)
...:

In [5]: group = W.shape[1]
...: for k in xrange(group):
...: # multiply all of each column of V by k-th column of W and sum in row
...: keep = np.vstack([keep, sum(V[:,:].T*W[:,k])])
...:

In [6]: np.allclose(keep, np.einsum('ij,ik->ki',V,W))
Out[6]: True

关于python - 是否可以在没有 for 循环的情况下将矩阵 A 中的所有每一列乘以矩阵 B 的每一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com