简体   繁体   English

将 numpy ndarray 与一维数组相乘

[英]Multiplying numpy ndarray with 1d array

So I can see many questions on this forum asking how to multiply numpy ndarrays with a 1d ndarray over a given axis.所以我可以在这个论坛上看到很多问题,询问如何在给定轴上将 numpy ndarray 与 1d ndarray 相乘。 Most of the answers suggest making use of np.newaxis to meet broadcasting requirements.大多数答案都建议使用 np.newaxis 来满足广播要求。 Here I have a more specific issue where Id like to multiply over axis 2 eg:在这里,我有一个更具体的问题,我想在轴 2 上相乘,例如:

>>> import numpy as np
>>> x = np.arange(27).reshape((3,3,3))
>>> y = np.arange(3)
>>> z = x*y[:,np.newaxis,np.newaxis]
>>> x
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
>>> y
array([0, 1, 2])
>>> z
array([[[ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[36, 38, 40],
        [42, 44, 46],
        [48, 50, 52]]])

This is the kind of multiplication I want.这就是我想要的那种乘法。 However, in my case I've got dimensions along axis 0 and 1 that do not match dimensions along axis 2 eg, when I try and implement the above for my arrays I get this:但是,在我的情况下,我沿轴 0 和 1 的尺寸与沿轴 2 的尺寸不匹配,例如,当我尝试为我的 arrays 实现上述内容时,我得到了这个:

>>> x = np.arange(144).reshape(8,6,3)
>>> z = x*y[:,np.newaxis,np.newaxis]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (8,6,3) (3,1,1) 

I understand why I get this broadcasting error, my issue is that if I adjust my broadcasting eg do a valid multiplication:我明白为什么我会收到这个广播错误,我的问题是,如果我调整我的广播,例如做一个有效的乘法:

>>> z = x*y[np.newaxis,np.newaxis,:]

I am now not multiplying across the correct axis.我现在没有在正确的轴上相乘。

Any ideas how to address this issue?任何想法如何解决这个问题?

Hi i have manage to get it in the format a long with the axis similar to how you did with your first example but not sure if this is correct?嗨,我已经设法得到它的格式很长,轴类似于你在第一个例子中所做的,但不确定这是否正确?

import numpy as np

test = np.arange(144).reshape(8,6,3)
test2 = np.arange(3)

np.array([test[i] * test2[i] for i in range(len(test.shape))])
>>>array([[[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[ 18,  19,  20],
        [ 21,  22,  23],
        [ 24,  25,  26],
        [ 27,  28,  29],
        [ 30,  31,  32],
        [ 33,  34,  35]],

       [[ 72,  74,  76],
        [ 78,  80,  82],
        [ 84,  86,  88],
        [ 90,  92,  94],
        [ 96,  98, 100],
        [102, 104, 106]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM