program tip

Python : 행 벡터와 열 벡터 구분

radiobox 2020. 12. 12. 10:24
반응형

Python : 행 벡터와 열 벡터 구분


파이썬에서 행 벡터와 열 벡터를 구별하는 좋은 방법이 있습니까? 지금까지 나는 numpy와 scipy를 사용하고 있는데 지금까지 내가 보는 것은 만약 내가 하나에 벡터를 준다면,

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

그들은 날씨가 행 벡터 나 열 벡터를 의미한다고 말할 수 없습니다. 게다가:

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

"실제 세계"에서는 사실이 아닙니다. 언급 된 모듈의 벡터에있는 대부분의 함수는 차별화가 필요하지 않다는 것을 알고 있습니다. 예를 들어 outer(a,b)또는 a.dot(b)내 편의를 위해 차별화하고 싶습니다.


배열에 다른 차원을 추가하여 구별을 명시 적으로 만들 수 있습니다.

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

이제 열 벡터가되도록 강제합니다.

>>> 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]])

또 다른 옵션은 구별을 원할 때 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]])

[]벡터를 작성할 때 double을 사용하십시오 .

그런 다음 행 벡터를 원하는 경우 :

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

또는 열 벡터를 원하는 경우 :

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

생성중인 벡터는 행도 열도 아닙니다 . 실제로 1 차원 만 있습니다. 다음을 통해 확인할 수 있습니다.

  • 차원 수를 검사 myvector.ndim하는1
  • 의하면 myvector.shape, 이는 (3,)(하나 개의 요소 튜플). 행 벡터는이어야 (1, 3)하고 열의 경우(3, 1)

이를 처리하는 두 가지 방법

  • 생성 실제 행 또는 열 벡터
  • reshape 당신의 현재

행 또는 열을 명시 적으로 만들 수 있습니다.

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

또는 단축키로

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

또는 (1, n)행 또는 (n, 1)열에 대해 모양을 변경할 수 있습니다.

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

여기서는 -1자동으로의 값을 찾습니다 n.


numpy.array의 ndmin 옵션을 사용할 수 있다고 생각합니다. 2로 유지하면 a (4,1)이되고 transpose는 (1,4)가됩니다.

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

이 경우에 대해 자세히 알고 싶다면 matrix대신 a를 사용하는 것이 좋습니다 .

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

제공합니다 :

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

ndarray두 번째 차원을 명시 적으로 추가하는 것도 사용할 수 있습니다 .

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

과:

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

1x3 배열 또는 3x1 배열을 원하는 경우 :

import numpy as np
row_arr = np.array([1,2,3]).reshape((1,3))
col_arr = np.array([1,2,3]).reshape((3,1)))

작업 확인 :

row_arr.shape  #returns (1,3)
col_arr.shape  #returns (3,1)

여기에 많은 답변이 도움이되지만 너무 복잡하다는 것을 알았습니다. 실제로 나는 돌아올 shapereshape와 코드를 읽을 수 : 매우 간단하고 명백한.


Python의 Numpy가 컨텍스트에서 사용하지 않는 한 구별하지 않는 것처럼 보입니다.

"원한다면 표준 벡터 또는 행 / 열 벡터를 가질 수 있습니다."

":) rank-1 배열을 행 또는 열 벡터로 취급 할 수 있습니다. dot (A, v)는 v를 열 벡터로 취급하고 dot (v, A)는 v를 행 벡터로 취급합니다. 많은 조옮김을 입력합니다. "

또한 코드에 따라 : "랭크 1 배열에서 전치하면 아무 작업도 수행되지 않습니다."출처 : http://wiki.scipy.org/NumPy_for_Matlab_Users


다음과 같이 배열의 요소를 행 또는 열에 저장할 수 있습니다.

>>> 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]])

우수한 Pandas 라이브러리는 이러한 종류의 작업을보다 직관적 인 IMO로 만드는 기능을 numpy에 추가합니다. 예를 들면 :

import numpy as np
import pandas as pd

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

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

DataFrame을 정의하고 스프레드 시트와 같은 피벗 테이블을 만들 수도 있습니다 .


When I tried to compute w^T * x using 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.

As far as 1D array is 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.

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

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 :

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

Note that we used w, wt instead 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?

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

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.


P.S. : potential gotchas in numpy


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]])

참고URL : https://stackoverflow.com/questions/17428621/python-differentiating-between-row-and-column-vectors

반응형