Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

Python 3D-1D Array multiplication

Alright, so i want to multiply a 3D array and 1D array together and then do summation like in the example below

A = [Array([[[100, 100, 100],
            [100, 100, 100]],

            [[100, 100, 100],
            [100, 100, 100]]]), 

    Array([[[200, 200, 200],
            [200, 200, 200]],

            [[200, 200, 200],
            [200, 200, 200]]])]

Weight = [0.25,0.75]


# A[0]*Weight[0]+A[1]*Weight[1]

C = [[[100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75],
      [100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75]],
    
     [[100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75],
      [100*0.25 + 200*0.75, 100*0.25 + 200*0.75, 100*0.25 + 200*0.75]]]
    
  = [[[175, 175, 175],
      [175, 175, 175]],
    
     [[175, 175, 175],
      [175, 175, 175]]]

The question is how do i do it in python? I tried to use np.multiply, np.dot, np.matmul but none of them seems to work as i intended. Maybe i didn't do it correctly. By the way, i also want it to be able to multiply even larger array, for example A Array with multiple Array() inside, not just 2 like in the example. And of course the length of Weight Array will follow the length of A Array. Also if possible i also wanna avoid using for-loop and use only numpy functions instead.

question from:https://stackoverflow.com/questions/65841249/python-3d-1d-array-multiplication

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply broadcast the values and sum them up.

import numpy as np

A = np.array([np.array([[[100, 100, 100],
            [100, 100, 100]],

            [[100, 100, 100],
            [100, 100, 100]]]), 

    np.array([[[200, 200, 200],
            [200, 200, 200]],

            [[200, 200, 200],
            [200, 200, 200]]])])


Weight = np.array([0.25,0.75])

P = (A * Weight[:, None, None, None]).sum(0)

Or you can also use einsum. Replace the last line with -

P = np.einsum("ijkl,i->jkl", A, Weight)

Gives the same result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...