numpy 1D数组是否遵循行/列规则? [英] Do numpy 1D arrays follow row/column rules?
问题描述
我刚刚开始使用numpy,我对如何使用数组感到困惑.我已经在numpy数组上看到了几个Stack Overflow答案,但是它们都涉及如何获得所需的结果(我知道如何做到这一点,我只是不知道为什么我需要这样做).我已经看到的共识是,数组比矩阵更好,因为它们是更基本的类,并且限制较少.我知道您可以转置一个数组,这对我来说意味着行和列之间是有区别的,但是乘法规则都会产生错误的输出(与我的预期相比).
I have just started using numpy and I am getting confused about how to use arrays. I have seen several Stack Overflow answers on numpy arrays but they all deal with how to get the desired result (I know how to do this, I just don't know why I need to do it this way). The consensus that I've seen is that arrays are better than matrices because they are a more basic class and less restrictive. I understand you can transpose an array which to me means there is a distinction between a row and a column, but the multiplication rules all produce the wrong outputs (compared to what I am expecting).
这是我与输出一起编写的测试代码:
Here is the test code I have written along with the outputs:
a = numpy.array([1,2,3,4])
print(a)
>>> [1 2 3 4]
print(a.T) # Transpose
>>> [1 2 3 4] # No apparent affect
b = numpy.array( [ [1], [2], [3], [4] ] )
print(b)
>>> [[1]
[2]
[3]
[4]] # Column (Expected)
print(b.T)
>>> [[1 2 3 4]] # Row (Expected, transpose seems to work here)
print((b.T).T)
>>> [[1]
[2]
[3]
[4]] # Column (All of these are as expected,
# unlike for declaring the array as a row vector)
# The following are element wise multiplications of a
print(a*a)
>>> [ 1 4 9 16]
print(a * a.T) # Row*Column
>>> [ 1 4 9 16] # Inner product scalar result expected
print(a.T * a) # Column*Row
>>> [ 1 4 9 16] # Outer product matrix result expected
print(b*b)
>>> [[1]
[4]
[9]
[16]] # Expected result, element wise multiplication in a column
print(b * b.T) # Column * Row (Outer product)
>>> [[ 1 2 3 4]
[ 2 4 6 8]
[ 3 6 9 12]
[ 4 8 12 16]] # Expected matrix result
print(b.T * (b.T)) # Column * Column (Doesn't make much sense so I expected elementwise multiplication
>>> [[ 1 4 9 16]]
print(b.T * (b.T).T) # Row * Column, inner product expected
>>> [[ 1 2 3 4]
[ 2 4 6 8]
[ 3 6 9 12]
[ 4 8 12 16]] # Outer product result
我知道我可以使用numpy.inner()
和numpy.outer()
来实现效果(这不是问题),我只想知道是否需要跟踪向量是行还是列.
I know that I can use numpy.inner()
and numpy.outer()
to achieve the affect (that is not a problem), I just want to know if I need to keep track of whether my vectors are rows or columns.
我也知道我可以创建一个一维矩阵来表示我的向量,并且乘法可以按预期进行.我正在尝试找出存储数据的最佳方法,以便在查看代码时可以清楚地知道将要发生的事情-现在,数学看上去只是令人困惑和错误.
I also know that I can create a 1D matrix to represent my vectors and the multiplication works as expected. I'm trying to work out the best way to store my data so that when I look at my code it is clear what is going to happen - right now the maths just looks confusing and wrong.
对于我的应用程序,我只需要使用1D和2D张量.
I only need to use 1D and 2D tensors for my application.
推荐答案
我将尝试注释您的代码
a = numpy.array([1,2,3,4])
print(a)
>>> [1 2 3 4]
print(a.T) # Transpose
>>> [1 2 3 4] # No apparent affect
a.shape
将显示(4,)
. a.T.shape
相同.它保持相同数量的尺寸,并且执行了唯一有意义的转置-没有变化.将其设置为(4,1)
会添加一个尺寸,并破坏了A.T.T
往返行程.
a.shape
will show (4,)
. a.T.shape
is the same. It kept the same number of dimensions, and performed the only meaningful transpose - no change. Making it (4,1)
would have added a dimension, and destroyed the A.T.T
roundtrip.
b = numpy.array( [ [1], [2], [3], [4] ] )
print(b)
>>> [[1]
[2]
[3]
[4]] # Column (Expected)
print(b.T)
>>> [[1 2 3 4]] # Row (Expected, transpose seems to work here)
b.shape
是(4,1)
,b.T.shape
是(1,4)
.请注意[]的额外集合.如果将a
创建为a = numpy.array([[1,2,3,4]])
,其形状也将是(1,4)
.
b.shape
is (4,1)
, b.T.shape
is (1,4)
. Note the extra set of []. If you'd created a
as a = numpy.array([[1,2,3,4]])
its shape too would have been (1,4)
.
制作b
的简单方法是b=np.array([[1,2,3,4]]).T
(或b=np.array([1,2,3,4])[:,None]
或b=np.array([1,2,3,4]).reshape(-1,1)
)
The easy way to make b
would be b=np.array([[1,2,3,4]]).T
(or b=np.array([1,2,3,4])[:,None]
or b=np.array([1,2,3,4]).reshape(-1,1)
)
将此与MATLAB进行比较
Compare this to MATLAB
octave:3> a=[1,2,3,4]
a =
1 2 3 4
octave:4> size(a)
ans =
1 4
octave:5> size(a.')
ans =
4 1
即使没有多余的[],它也将矩阵初始化为2d.
Even without the extra [] it has initialed the matrix as 2d.
numpy
具有一个模仿MATLAB的matrix
类-早在MATLAB仅允许2d的时候.
numpy
has a matrix
class that imitates MATLAB - back in the time when MATLAB allowed only 2d.
In [75]: m=np.matrix('1 2 3 4')
在[76]:m Out [76]:矩阵([[1、2、3、4]])
In [76]: m Out[76]: matrix([[1, 2, 3, 4]])
In [77]: m.shape
Out[77]: (1, 4)
In [78]: m=np.matrix('1 2; 3 4')
In [79]: m
Out[79]:
matrix([[1, 2],
[3, 4]])
我不建议您使用np.matrix
,除非它确实为您的代码添加了一些有用的东西.
I don't recommend using np.matrix
unless it really adds something useful to your code.
请注意MATLAB关于vectors
的论述,但实际上它们只是它们的matrix
,仅具有一个非一维维度.
Note the MATLAB talks of vectors
, but they are really just their matrix
with only one non-unitary dimension.
# The following are element wise multiplications of a
print(a*a)
>>> [ 1 4 9 16]
print(a * a.T) # Row*Column
>>> [ 1 4 9 16] # Inner product scalar result expected
此行为源自a.T == A
.如您所述,*
产生逐元素乘法.这等效于MATLAB .*
. np.dot(a,a)
给出2个数组的点或矩阵乘积.
This behavior follows from a.T == A
. As you noted, *
produces element by element multiplication. This is equivalent to the MATLAB .*
. np.dot(a,a)
gives the dot or matrix product of 2 arrays.
print(a.T * a) # Column*Row
>>> [ 1 4 9 16] # Outer product matrix result expected
不,它仍在进行元素乘法.
No, it is still doing elementwise multiplication.
我将使用broadcasting
,a[:,None]*a[None,:]
来获取外部产品. Octave在模仿numpy时添加了此内容;我不知道MATLAB是否还拥有它.
I'd use broadcasting
, a[:,None]*a[None,:]
to get the outer product. Octave added this in imitation of numpy; I don't know if MATLAB has it yet.
在下面的*
中始终是逐元素相乘.广播产生矩阵/外部产品结果.
In the following *
is always element by element multiplication. It's broadcasting that produces matrix/outer product results.
print(b*b)
>>> [[1]
[4]
[9]
[16]] # Expected result, element wise multiplication in a column
A (4,1) * (4,1)=>(4,1)
.周围形状相同.
A (4,1) * (4,1)=>(4,1)
. Same shapes all around.
print(b * b.T) # Column * Row (Outer product)
>>> [[ 1 2 3 4]
[ 2 4 6 8]
[ 3 6 9 12]
[ 4 8 12 16]] # Expected matrix result
此处(4,1)*(1,4)=>(4,4)
产品.复制了2个尺寸1
的尺寸,因此实际上成为了(4,4)*(4,4)
.您将如何在MATLAB中复制.*
?
Here (4,1)*(1,4)=>(4,4)
product. The 2 size 1
dimensions have been replicated so it becomes, effectively a (4,4)*(4,4)
. How would you do replicate this in MATLAB - with .*
?
print(b.T * (b.T)) # Column * Column (Doesn't make much sense so I expected elementwise multiplication
>>> [[ 1 4 9 16]]
*
是元素性的,与预期无关.在MATLAB中使用b' .* b'
.
*
is elementwise regardless of expectations. Think b' .* b'
in MATLAB.
print(b.T * (b.T).T) # Row * Column, inner product expected
>>> [[ 1 2 3 4]
[ 2 4 6 8]
[ 3 6 9 12]
[ 4 8 12 16]] # Outer product result
再次*
是元素级的; inner
除乘法外还需要求和.在这里,广播再次适用(1,4)*(4,1)=>(4,4)
.
Again *
is elementwise; inner
requires a summation in addition to multiplication. Here broadcasting again applies (1,4)*(4,1)=>(4,4)
.
np.dot(b,b)
或np.trace(b.T*b)
或np.sum(b*b)
给出30
.
在MATLAB中工作时,我经常检查size
,并创建可以捕捉尺寸不匹配的测试矩阵(例如2x3而不是2x2矩阵).我继续在numpy中做到这一点.
When I worked in MATLAB I frequently checked the size
, and created test matrices that would catch dimension mismatches (e.g. a 2x3 instead of a 2x2 matrix). I continue to do that in numpy.
关键是:
-
numpy
数组可能是1d(甚至是0d)
numpy
arrays may be 1d (or even 0d)
(4,)数组与(4,1)
或(1,4)`并不完全相同.
A (4,) array is not exactly the same as a (4,1)
or (1,4)`.
*
是元素级-始终.
广播通常会解释outer
类似行为
broadcasting usually accounts for outer
like behavior
这篇关于numpy 1D数组是否遵循行/列规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!