脾气暴躁-多种外部产品 [英] Numpy - Multiple Outer Products

查看:99
本文介绍了脾气暴躁-多种外部产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以计算多个外部乘积并将结果堆叠在一个操作中.

I was wondering if there's a way to compute multiple outer products and stack the results in a single operation.

假设我有一个Nx1向量,并将外部乘积与1xM向量相乘,结果将是一个NxM矩阵.

Say I have an Nx1 vector and take the outer product with a 1xM vector, the result will be an NxM matrix.

如果我有一个NxR矩阵A和一个RxM矩阵B,该怎么办?是否可以构造一个NxMxR矩阵,其中输出矩阵的每一层都是A的对应列和B的行的外积?

What if I had an NxR matrix A, and an RxM matrix B. Is it possible to construct an NxMxR matrix where each layer of the output matrix is the outer product of the corresponding column of A and row of B?

我知道在R上的单个for循环中执行此操作确实很容易,但是我想知道是否有使用numpy内置函数的更快方法(就像通常在使用numpy时一样).

I know it's really easy to do this in a single for loop over R, but I wanted to know if there's a faster way using numpy builtins (as there usually is when numpy is concerned).

我无法找出一组适用于einsum的索引(而且我什至不确定einsum是否是正确的方法,因为这里不涉及求和)

I haven't been able to figure out a set of indices that work with einsum (and I'm not even sure if einsum is the right approach, since there is no summation involved here)

推荐答案

是的,当然可以使用

Yes, of course, using broadcasting or Einsum (the fact that there is no summation does not matter)

N, M, R = 8, 9, 16

A = numpy.random.rand(N)
B = numpy.random.rand(M)

C = A[:, None] * B[None, :]
D = numpy.einsum('a,b->ab', A, B)
numpy.allclose(C, D)
# True
C.shape
# (8, 9)

A = numpy.random.rand(N, R)
B = numpy.random.rand(M, R)

C = A[:, None, :] * B[None, :, :]
D = numpy.einsum('ar,br->abr', A, B)
numpy.allclose(C, D)
# True
C.shape
# (8, 9, 16)

这篇关于脾气暴躁-多种外部产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆