将二维数组中的每一列与另一个二维数组中的每一列相乘 [英] Multiply each column from 2D array with each column from another 2D array

查看:31
本文介绍了将二维数组中的每一列与另一个二维数组中的每一列相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Numpy 数组 x,形状为 (m, i)y,形状为 (m, j) (所以行数是一样的).我想将 x 的每一列与 y 的每一列元素相乘,以便结果的形状为 (m, i*j).

I have two Numpy arrays x with shape (m, i) and y with shape (m, j) (so the number of rows is the same). I would like to multiply each column of x with each column of y element-wise so that the result is of shape (m, i*j).

示例:

import numpy as np

np.random.seed(1)
x = np.random.randint(0, 2, (10, 3))
y = np.random.randint(0, 2, (10, 2))

这将创建以下两个数组 x:

This creates the following two arrays x:

array([[1, 1, 0],
       [0, 1, 1],
       [1, 1, 1],
       [0, 0, 1],
       [0, 1, 1],
       [0, 0, 1],
       [0, 0, 0],
       [1, 0, 0],
       [1, 0, 0],
       [0, 1, 0]])

y:

array([[0, 0],
       [1, 1],
       [1, 1],
       [1, 0],
       [0, 0],
       [1, 1],
       [1, 1],
       [1, 1],
       [0, 1],
       [1, 0]])

现在结果应该是:

array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0]])

目前,我已经通过 xy 列上的两个嵌套循环实现了这个操作:

Currently, I've implemented this operation with two nested loops over the columns of x and y:

def _mult(x, y):
    r = []
    for xc in x.T:
        for yc in y.T:
            r.append(xc * yc)
    return np.array(r).T

但是,我很确定一定有我似乎想不出的更优雅的解决方案.

However, I'm pretty sure that there must be a more elegant solution that I can't seem to come up with.

推荐答案

使用 NumPy 广播 -

(y[:,None]*x[...,None]).reshape(x.shape[0],-1)

说明

作为输入,我们有 -

y : 10 x 2
x : 10 x 3

使用 y[:,None],我们在现有的两个暗度之间引入了一个新轴,从而创建了它的 3D 阵列版本.这将保持第一个轴作为 3D 版本中的第一个轴,并将第二个轴作为第三个轴推出.

With y[:,None], we are introducing a new axis between the existing two dims, thus creating a 3D array version of it. This keeps the first axis as the first one in 3D version and pushes out the second axis as the third one.

使用 x[...,None],我们引入一个新轴作为最后一个轴,方法是将两个现有的暗淡作为前两个暗淡,从而产生 3D 数组版本.

With x[...,None], we are introducing a new axis as the last one by pushing up the two existing dims as the first two dims to result in a 3D array version.

总而言之,随着新轴的引入,我们有 -

To summarize, with the introduction of new axes, we have -

y : 10 x 1 x 2
x : 10 x 3 x 1

使用 y[:,None]*x[...,None]y 都会有broadcastingcode>x,生成形状为 (10,3,2) 的输出数组.要获得形状 (10,6) 的最终输出数组,我们只需要将最后两个轴与该重塑合并.

With y[:,None]*x[...,None], there would be broadcasting for both y and x, resulting in an output array with a shape of (10,3,2). To get to the final output array of shape (10,6), we just need to merge the last two axes with that reshape.

这篇关于将二维数组中的每一列与另一个二维数组中的每一列相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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