numpy: broadcast multiplication over one common axis of two 2d arrays

2024/11/14 15:20:28

I'm looking for a way to element-wise multiply two 2d arrays of shape (a, b) and (b, c), respectively. Over the 'b' axis, which the two arrays have in common.

For instance, an example of what I'd like to broadcast (vectorize) is:

import numpy as np    # some dummy data
A = np.empty((2, 3))
B = np.empty((3, 4))# naive implementation
C = np.vstack(np.kron(A[:, i], B[i, :]) for i in [0, 1, 2])# this should give (3, 2, 4)
C.shape

Does anyone know what to do here? Is there a better way?

Answer

With different test cases:

In [56]: A=np.arange(6).reshape((2,3))
In [57]: B=np.arange(12).reshape((3,4))
In [58]: np.vstack([np.kron(A[:,i],B[i,:]) for i in range(3)])
Out[58]: 
array([[ 0,  0,  0,  0,  0,  3,  6,  9],[ 4,  5,  6,  7, 16, 20, 24, 28],[16, 18, 20, 22, 40, 45, 50, 55]])

A first try with `einsum, preserving all 3 axes (no summing)

In [60]: np.einsum('ij,jk->ijk',A,B)
Out[60]: 
array([[[ 0,  0,  0,  0],[ 4,  5,  6,  7],[16, 18, 20, 22]],[[ 0,  3,  6,  9],[16, 20, 24, 28],[40, 45, 50, 55]]])

Same numbers, but in a different shape.

I can reorder axes on output, to make a 2x4x3, which can be reshaped to 8,3 and transposed.

In [64]: np.einsum('ij,jk->ikj',A,B).reshape(8,3).T
Out[64]: 
array([[ 0,  0,  0,  0,  0,  3,  6,  9],[ 4,  5,  6,  7, 16, 20, 24, 28],[16, 18, 20, 22, 40, 45, 50, 55]])

So with another iteration I can get rid of the transpose

In [68]: np.einsum('ij,jk->jik',A,B).reshape(3,8)
Out[68]: 
array([[ 0,  0,  0,  0,  0,  3,  6,  9],[ 4,  5,  6,  7, 16, 20, 24, 28],[16, 18, 20, 22, 40, 45, 50, 55]])

I should have gotten there right away. A is (2,3), B is (3,4), and I want (3,2,4) reshaped to (3,8). i=2, j=3, k=4 => jik.

So another way of describing the problem,

a_ij * b_jk = c_jik

And since I'm not making use of the sum part of the einsum, regular broadcasted multiplication will also work, with one or more transposes.

https://en.xdnf.cn/q/72034.html

Related Q&A

Convert integer to binary in python and compare the bits

How to convert a int n into binary and test each bit of the resulting binary number?I have just got the following after a lot of googling:def check_bit_positions(n, p1, p2):print int(str(n),2)However …

python, confused in decorate and closure

I have some test code:def num(num):def deco(func):def wrap(*args, **kwargs):inputed_num = numreturn func(*args, **kwargs)return wrapreturn deco@num(5) def test(a):return a + inputed_numprint test(1)whe…

Python Regex - checking for a capital letter with a lowercase after

I am trying to check for a capital letter that has a lowercase letter coming directly after it. The trick is that there is going to be a bunch of garbage capital letters and number coming directly befo…

Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy

I have a XML document that contains a hierarchical, tree-like structure, see the example below.The document contains several <Message> tags (I only copied one of them for convenience).Each <Me…

Reference counting using PyDict_SetItemString

Im wondering how memory management/reference counting works when a new value is set into an existing field within a PyDict (within a C extension).For instance, assume a dictionary is created and popula…

How to use statsmodels.tsa.seasonal.seasonal_decompose with a pandas dataframe

from statsmodels.tsa.seasonal import seasonal_decomposedef seasonal_decomp(df, model="additive"):seasonal_df = Noneseasonal_df = seasonal_decompose(df, model=additive)return seasonal_dfseason…

UnidentifiedImageError: cannot identify image file

Hello I am training a model with TensorFlow and Keras, and the dataset was downloaded from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765 This is a zip folder that I split in the …

Pydub raw audio data

Im using Pydub in Python 3.4 to try to detect the pitch of some audio files.I have a working pitch detection algorithm (McLeod Pitch Method), which is robust for real-time applications (I even made an …

Create Duplicate Rows and Change Values in Specific Columns

How to create x amount of duplicates based on a row in the dataframe and change a single or multi variables from specific columns. The rows are then added to the end of the same dataframe.A B C D E F 0…

writing and saving CSV file from scraping data using python and Beautifulsoup4

I am trying to scrape data from the PGA.com website to get a table of all of the golf courses in the United States. In my CSV table I want to include the Name of the golf course ,Address ,Ownership ,We…