向量和数组的 np array 点积

Np array dot product of vector and array

我在理解 numpy 点函数背后的工作时遇到问题,broadcasting.Below 是我试图理解的片段

a=np.array([[1,2],[3,5]])

如果我们检查 a 的形状 a.shape 它将是 (2,2)

b=np.array([3,6])b.shape is (2,)

问题1:b是列向量还是行向量?在提供输入时,似乎 b 是行向量,但形状将其显示为具有 2 rows.What 的列向量是我理解的错误吗?

现在如果做 a.dot(b) 它导致 array([15,39])

问题 2:根据矩阵乘法,如果 am*n 那么 b 必须是 n*k 并且因为 a 是 2*2 那么 b 必须是 2*1。这是否验证 b 是一个列向量,否则如果它是一个行向量,则矩阵乘法是不可能的,但是考虑到 b,点积的输出确实根据矩阵乘法给出了值作为列向量并广播它

现在 b.dot(a) 也是可能的,结果是 array([21,36])和 这让我大吃一惊 mind.How 他们是在检查矩阵乘法向量的兼容性吗?他们是如何计算的? 在至少一种情况下,他们必须为未显示的 multiplication.But 抛出不兼容维度的错误,并且他们正在计算这两种情况下的结果。

起初,a=np.array([[1,2],[3,5])为了工作a=np.array([[1,2],[3,5]])改为a=np.array([[1,2],[3,5]])

numpy 数组是值的网格,所有类型都相同,并由非负整数元组索引。维数是数组的秩;数组的形状是一个整数元组,给出了数组沿每个维度的大小。

回答你的问题b的形状是2,也就是行数。

a = np.array([1, 2, 3])
a.shape
(3,) #here 3 is row size its one dimensional array. 

点运算符:

numpy.dot

示例:

np.dot(2, 4)
8

二维数组的另一个例子:

>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
       [2, 2]])
  • 用于计算向量内积、向量与矩阵相乘以及矩阵相乘的 dot 函数。

  • Dot 既可以作为 numpy 模块中的函数使用,也可以作为数组对象的实例方法使用

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

他们是怎么计算的?

b.dot(a) is also possible and results in array([21,36])and this blew my mind.How are they checking the compatibility of the vector for matrix multiplication and how do they calculate?

这是基本的 matrix product

     a
    array([[1, 2],  #2D array 
           [3, 5]])
    >>> b
    array([3, 6]) #1D array 

(7*3 6*6) = ([21, 36])

numpy 的编程方式意味着一维数组 shape=(n,) 被视为 既不是 列向量也不是行向量,但可以 act 喜欢基于点积中的位置的任何一个。为了更好地解释这一点,请考虑将非对称数组的情况与对称数组的情况进行比较:

>>>a=numpy.arange(3)
>>>a.shape=(1,3)
>>>a
array([0,1,2])

>>>b=numpy.arange(9)
>>>b.shape=(3,3)
>>>b
array([0,1,2]
      [3,4,5]
      [6,7,8])

然后定义一个(3,)向量:

>>>c=numpy.arange(3)
>>>c
array([0,1,2])
>>>c.shape
(3,)

在普通线性代数中,如果 c 是一个列向量,我们希望 a.c 生成一个常数,1x3 矩阵点和 3x1 列向量,而 c.a 生成一个 3x3 矩阵,3x1列乘以 1x3 行。在 python 中这样做你会发现 a.dot(c) 会产生一个 (1,) 数组(我们期望的常量),但是 c.dot(a) 会引发错误:

>>>d=a.dot(c)
d.shape=(1,)
>>>e=c.dot(a)
ValueError: shapes (3,) and (1,3) not aligned: 3 (dim 0) != 1 (dim 0)

出问题的是 numpy 只检查了 c 的 维度与 a 的第一个维度,没有检查 last c 对 a 的维数。根据 numpy 一维数组只有 1 个维度 并且所有检查都是针对该维度完成的。因此,我们发现一维数组并不严格充当列或行向量。例如。 b.dot(c) 对照 c 的一维检查 b 的第二维(c acts 像列向量)并且 c.dot(b) 检查 c 的一维对照 c 的第一维b(c 充当 像一个行向量)。因此,它们都有效:

>>>f=b.dot(c)
>>>f
array([ 5, 14, 23])

>>>g=c.dot(b)
>>>g
array([15, 18, 21]) 

为避免这种情况,您必须为您的数组提供第二维,使其成为行或列向量。在此示例中,您可以明确地说 c.shape=(3,1) 用于列向量或 c.shape=(1,3) 用于行向量。

>>>c.shape=(3,1)
>>>c.dot(a)
array([0,0,0]
      [0,1,2]
      [0,2,4])
>>>h=c.dot(b)
ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)


>>>c.shape=(1,3) 
>>>i=c.dot(b)
>>>i
array([[15, 18, 21]])

要点是: 根据 numpy,行向量和列向量有两个维度