0

違いは何ですか:

import numpy as np
A = np.zeros((3,))

import numpy as np
B = np.zeros((1,3))

ご回答有難うございます!

4

3 に答える 3

2

これらが実際の違いを示していることを願っています。

>>> A = np.zeros((3,))
>>> B = np.zeros((1,3))
>>> A #no column, just 1D
array([ 0.,  0.,  0.])
>>> B #has one column
array([[ 0.,  0.,  0.]])
>>> A.shape
(3,)
>>> B.shape
(1, 3)
>>> A[1]
0.0
>>> B[1] #can't do this, it will take the 2nd column, but there is only one column.

Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    B[1]
IndexError: index 1 is out of bounds for axis 0 with size 1
>>> B[0] #But you can take the 1st column
array([ 0.,  0.,  0.])
>>> B[:,1] #take the 2nd cell, for each column
array([ 0.])
>>> B[0,1] #how to get the same result as A[1]? take the 2nd cell of the 1st col.
0.0
于 2013-10-22T16:08:59.880 に答える
1

A は 3 つの要素を持つ 1 次元配列です。

B は、1 行 3 列の 2 次元配列です。

C = np.zeros((3,1))3 行 1 列の 2 次元配列を作成する which を使用することもできます。

A、B、および C は同じ要素を持ちます。違いは、後の呼び出しでどのように解釈されるかです。たとえば、一部の numpy 呼び出しは特定の次元で動作するか、特定の次元で動作するように指示できます。たとえば合計:

>> np.sum(A, 0)
   3.0
>> np.sum(B, 0)
   array([ 1., 1., 1.])

また、 のような行列/テンソル操作やdot、 や のような操作でも異なる動作をhstackvstackます。

使用するのがベクトルだけの場合、フォーム A は通常、必要な処理を行います。余分な 'singleton' 次元 (つまり、サイズ 1 の次元) は、追跡しなければならない余計なものです。ただし、2 次元配列を操作する必要がある場合は、行ベクトルと列ベクトルを区別する必要がある可能性があります。その場合、フォーム B と C が役立ちます。

于 2013-10-22T16:54:30.237 に答える