简体   繁体   English

点积为(x)和(x,y)的形状

[英]Dot product with shapes (x) and (x, y)

I am really new to numpy, so I am having some troubles understanding the dot product. 我真的对numpy陌生,因此在理解点积时遇到了一些麻烦。

I have this simple piece of code: 我有这段简单的代码:

import numpy as np

A = np.ones((5))
B = np.ones((5,10))

A.dot(B)
# array([ 5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.,  5.])

A.dot(B).shape
# (10,)

I cannot understand what is happening in this code. 我不明白这段代码中发生了什么。 I am a little confused, because it seems that a shape of (10,) is not a column vector, because the transpose is the same. 我有点困惑,因为(10,)的形状似乎不是列向量,因为转置是相同的。

Is A being broadcasted? A正在广播吗? I thought that A should be broadcasted to the shape of (5,5) , so it could be multiplied with B and thus returning an array of shape (5,10) . 我认为应该将A广播为(5,5)的形状,因此可以将其乘以B并返回一个形状为(5,10)的数组。 What am I getting wrong? 我怎么了?

Numpy makes a difference between 1d arrays (something of shape (N,) ) and an 2d array (matrix) with one column (shape (N, 1) ) or one row (shape (1, N) aka column- or row-vectors. Numpy在1d数组(形状为(N,)东西)和2d数组(矩阵)具有一列(形状(N, 1) )或一行(形状(1, N)又称为列或行(1, N)之间产生差异。向量。

>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B.dot(a)
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

Or unsing python 3.5 with numpy 1.10: 或用numpy 1.10取消安装python 3.5:

>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B @ a
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

If you have a 1d array, you can use np.newaxis to make it a row or column vector: 如果具有一np.newaxis数组,则可以使用np.newaxis使其成为行或列向量:

>>> a = np.ones(5)
>>> B = np.ones((5, 5))
>>> B @ a[:, np.newaxis]
array([[ 5.],
       [ 5.],
       [ 5.],
       [ 5.],
       [ 5.]])

Both new row and column: 新的行和列:

>>> x = np.arange(5)
>>> B = x[:, np.newaxis] @ x[np.newaxis, :]
>>> B
array([[ 0,  0,  0,  0,  0],
       [ 0,  1,  2,  3,  4],
       [ 0,  2,  4,  6,  8],
       [ 0,  3,  6,  9, 12],
       [ 0,  4,  8, 12, 16]])

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

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