Python:区分行向量和列向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17428621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:10:38  来源:igfitidea点击:

Python: Differentiating between row and column vectors

pythonarraysnumpyvectorscipy

提问by MarcinKonowalczyk

Is there a good way of differentiating between row and column vectors in python? So far I'm using numpy and scipy and what I see so far is that If I was to give one a vector, say

有没有区分python中行向量和列向量的好方法?到目前为止,我正在使用 numpy 和 scipy,到目前为止我看到的是如果我要给一个向量,说

from numpy import *
Vector = array([1,2,3])

they wouldn't be able to say weather I mean a row or a column vector. Moreover:

他们不能说天气我的意思是一行或一个列向量。而且:

array([1,2,3]) == array([1,2,3]).transpose()
True

Which in "real world" is simply untrue. I realize that most of the functions on vectors from the mentioned modules don't need the differentiation. For example outer(a,b)or a.dot(b)but I'd like to differentiate for my own convenience.

这在“现实世界”中是不真实的。我意识到来自上述模块的大多数向量函数不需要区分。例如outer(a,b)a.dot(b)但我想为了我自己的方便而区分。

采纳答案by bogatron

You can make the distinction explicit by adding another dimension to the array.

您可以通过向数组添加另一个维度来明确区分。

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14

Now force it to be a column vector:

现在强制它是一个列向量:

>>> a.shape = (3,1)
>>> a
array([[1],
       [2],
       [3]])
>>> a.transpose()
array([[1, 2, 3]])
>>> a.dot(a.transpose())
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Another option is to use np.newaxis when you want to make the distinction:

另一种选择是使用 np.newaxis 进行区分:

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[:, np.newaxis]
array([[1],
       [2],
       [3]])
>>> a[np.newaxis, :]
array([[1, 2, 3]])

回答by so13eit

It looks like Python's Numpy doesn't distinguish it unless you use it in context:

除非您在上下文中使用它,否则看起来 Python 的 Numpy 不会区分它:

"You can have standard vectors or row/column vectors if you like. "

“如果您愿意,您可以使用标准向量或行/列向量。”

" :) You can treat rank-1 arrays as either row or column vectors. dot(A,v) treats v as a column vector, while dot(v,A) treats v as a row vector. This can save you having to type a lot of transposes. "

" :) 您可以将 rank-1 数组视为行向量或列向量。dot(A,v) 将 v 视为列向量,而 dot(v,A) 将 v 视为行向量。这可以节省您的时间键入很多转置。”

Also, specific to your code: "Transpose on a rank-1 array does nothing. " Source: http://wiki.scipy.org/NumPy_for_Matlab_Users

此外,特定于您的代码:“在 rank-1 数组上转置什么都不做。”来源:http: //wiki.scipy.org/NumPy_for_Matlab_Users

回答by Saullo G. P. Castro

If you want a distiction for this case I would recommend to use a matrixinstead, where:

如果您想要针对这种情况进行区分,我建议您改用 a matrix,其中:

matrix([1,2,3]) == matrix([1,2,3]).transpose()

gives:

给出:

matrix([[ True, False, False],
        [False,  True, False],
        [False, False,  True]], dtype=bool)

You can also use a ndarrayexplicitly adding a second dimension:

您还可以使用ndarray显式添加第二个维度:

array([1,2,3])[None,:]
#array([[1, 2, 3]])

and:

和:

array([1,2,3])[:,None]
#array([[1],
#       [2],
#       [3]])

回答by cms_mgr

The excellent Pandaslibrary adds features to numpy that make these kinds of operations more intuitive IMO. For example:

优秀的Pandas库为 numpy 添加了功能,使这些类型的操作在 IMO 中更加直观。例如:

import numpy as np
import pandas as pd

# column
df = pd.DataFrame([1,2,3])

# row
df2 = pd.DataFrame([[1,2,3]])

You can even define a DataFrame and make a spreadsheet-like pivot table.

您甚至可以定义一个 DataFrame 并制作一个类似电子表格的数据透视表

回答by abhra

I think you can use ndmin option of numpy.array. Keeping it to 2 says that it will be a (4,1) and transpose will be (1,4).

我认为您可以使用 numpy.array 的 ndmin 选项。保持为 2 表示它将是 (4,1) 并且转置将是 (1,4)。

>>> a = np.array([12, 3, 4, 5], ndmin=2)
>>> print a.shape
>>> (1,4)
>>> print a.T.shape
>>> (4,1)

回答by kmario23

When I tried to compute w^T * xusing numpy, it was super confusing for me as well. In fact, I couldn't implement it myself. So, this is one of the few gotchas in NumPy that we need to acquaint ourselves with.

当我尝试w^T * x使用 numpy进行计算时,它也让我非常困惑。事实上,我自己无法实现它。所以,这是我们需要熟悉的 NumPy 中为数不多的问题之一。

As far as 1D arrayis concerned, there is no distinction between a row vector and column vector. They are exactly the same.

一维数组而言,行向量和列向量之间没有区别。它们完全一样。

Look at the following examples, where we get the same result in all cases, which is not true in (the theoretical sense of) linear algebra:

看看下面的例子,我们在所有情况下都得到相同的结果,这在(理论上的)线性代数中是不正确的:

In [37]: w
Out[37]: array([0, 1, 2, 3, 4])

In [38]: x
Out[38]: array([1, 2, 3, 4, 5])

In [39]: np.dot(w, x)
Out[39]: 40

In [40]: np.dot(w.transpose(), x)
Out[40]: 40

In [41]: np.dot(w.transpose(), x.transpose())
Out[41]: 40

In [42]: np.dot(w, x.transpose())
Out[42]: 40


With that information, now let's try to compute the squared length of the vector |w|^2.

有了这些信息,现在让我们尝试计算向量的平方长度|w|^2

For this, we need to transform wto 2D array.

为此,我们需要转换w为二维数组。

In [51]: wt = w[:, np.newaxis]

In [52]: wt
Out[52]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

Now, let's compute the squared length (or squared magnitude) of the vector w:

现在,让我们计算向量的平方长度(或平方大小)w

In [53]: np.dot(w, wt)
Out[53]: array([30])

Note that we used w, wtinstead of wt, w(like in theoretical linear algebra) because of shape mismatch with the use of np.dot(wt, w). So, we have the squared length of the vector as [30]. Maybe this is one of the ways to distinguish (numpy's interpretation of) row and column vector?

请注意,由于形状与 np.dot(wt, w) 的使用不匹配,我们使用w,wt而不是wt, w(就像在理论线性代数中一样)。因此,我们将向量的平方长度设为[30]。也许这是区分(numpy 的解释)行和列向量的方法之一?

And finally, did I mention that I figured out the way to implement w^T * x? Yes, I did :

最后,我有没有提到我找到了实现的方法w^T * x?是的,我做到了:

In [58]: wt
Out[58]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

In [59]: x
Out[59]: array([1, 2, 3, 4, 5])

In [60]: np.dot(x, wt)
Out[60]: array([40])

So, in NumPy, the order of the operands is reversed, as evidenced above, contrary to what we studied in theoretical linear algebra.

因此,在 NumPy 中,操作数的顺序是颠倒的,如上所述,这与我们在理论线性代数中研究的相反。



P.S.: potential gotchas in numpy

PSnumpy 中的潜在问题

回答by Evgeni Sergeev

Here's another intuitive way. Suppose we have:

这是另一种直观的方式。假设我们有:

>>> a = np.array([1, 3, 4])
>>> a
array([1, 3, 4])

First we make a 2D array with that as the only row:

首先,我们制作一个二维数组,将其作为唯一的行:

>>> a = np.array([a])
>>> a
array([[1, 3, 4]])

Then we can transpose it:

然后我们可以转置它:

>>> a.T
array([[1],
       [3],
       [4]])

回答by davidA

Use double []when writing your vectors.

[]编写向量时使用 double 。

Then, if you want a row vector:

然后,如果你想要一个行向量:

row_vector = array([[1, 2, 3]])    # shape (1, 3)

Or if you want a column vector:

或者如果你想要一个列向量:

col_vector = array([[1, 2, 3]]).T  # shape (3, 1)

回答by blue_note

The vector you are creating is neither row nor column. It actually has 1 dimension only. You can verify that by

您正在创建的向量既不是 row 也不是 column。它实际上只有一维。您可以通过以下方式验证

  • checking the number of dimensions myvector.ndimwhich is 1
  • checking the myvector.shape, which is (3,)(a tuple with one element only). For a row vector is should be (1, 3), and for a column (3, 1)
  • 检查维度的数目myvector.ndim,其1
  • 检查myvector.shape, 这是(3,)(只有一个元素的元组)。对于行向量应该是(1, 3),对于列(3, 1)

Two ways to handle this

处理这个的两种方法

  • create an actualrow or column vector
  • reshapeyour current one
  • 创建实际的行或列向量
  • reshape你现在的

You can explicitly create a row or column

您可以显式创建行或列

row = np.array([    # one row with 3 elements
   [1, 2, 3]
]
column = np.array([  # 3 rows, with 1 element each
    [1],
    [2],
    [3]
])

or, with a shortcut

或者,使用快捷方式

row = np.r_['r', [1,2,3]]     # shape: (1, 3)
column = np.r_['c', [1,2,3]]  # shape: (3,1)

Alternatively, you can reshape it to (1, n)for row, or (n, 1)for column

或者,您可以将其重塑(1, n)为行或(n, 1)

row = my_vector.reshape(1, -1)
column = my_vector.reshape(-1, 1)

where the -1automatically finds the value of n.

其中-1自动找到 的值n

回答by Ryan Yarahmadian

You can store the array's elements in a row or column as follows:

您可以按如下方式将数组元素存储在一行或一列中:

>>> a = np.array([1, 2, 3])[:, None] # stores in rows
>>> a
array([[1],
       [2],
       [3]])

>>> b = np.array([1, 2, 3])[None, :] # stores in columns
>>> b
array([[1, 2, 3]])