2013-04-01 16 views
5

Używam numpy.matrix. Jeśli dodaję matrycę 3x3 za pomocą wektora 1x3 lub 3x1. Dostaję z powrotem matrycę 3x3. Czy nie powinno to być "niezdefiniowane"? A jeśli nie, jakie jest wytłumaczenie tego?Macierz Numpy plus wektor kolumnowy

Przykład

a = np.matrix('1 1 1; 1 1 1; 1 1 1') 
b = np.matrix('1 1 1') 
a + b #or a + np.transpose(b) 

wyjściowa:

matrix([[2, 2, 2], 
     [2, 2, 2], 
     [2, 2, 2]]) 

Odpowiedz

7

ten nazywany jest "nadawanie". Z manual:

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.

+0

Thanks to wszystko wyjaśnia. Jeszcze nie zrozumiałem tej koncepcji, mimo że komunikat o błędzie już na mnie wskazywał: "ValueError: operandy nie mogły być transmitowane razem z kształtami ..." – andershqst

5

Jeśli chcesz dodać wektor do macierzy, można to zrobić wybierając gdzie powinien iść:

In [155]: ma = np.matrix(
    ...:  [[ 1., 1., 1.], 
    ...:  [ 1., 1., 1.], 
    ...:  [ 1., 1., 1.]]) 

In [156]: mb = np.matrix([[1,2,3]]) 

In [157]: ma[1] += mb # second row 

In [158]: ma 
Out[158]: 
matrix([[ 1., 1., 1.], 
     [ 2., 3., 4.], 
     [ 1., 1., 1.]]) 

In [159]: ma[:,1] += mb.T # second column 

In [160]: ma 
Out[160]: 
matrix([[ 1., 2., 1.], 
     [ 2., 5., 4.], 
     [ 1., 4., 1.]]) 

Ale chciałbym was ostrzec, że nie używają numpy.matrix, jak podano. W rzeczywistości używasz numpy.ndarray, ponieważ np.ones zwraca ndarray, a nie matrix.

dodanie jest wciąż ten sam, ale stworzyć kilka matryc, a przekonasz się, że zachowują się one inaczej:

In [161]: ma*mb 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 

ValueError: matrices are not aligned 

In [162]: mb*ma 
Out[162]: matrix([[ 6., 6., 6.]]) 

In [163]: ma*mb.T 
Out[163]: 
matrix([[ 6.], 
     [ 6.], 
     [ 6.]]) 

In [164]: aa = np.ones((3,3)) 

In [165]: ab = np.arange(1,4) 

In [166]: aa*ab 
Out[166]: 
array([[ 1., 2., 3.], 
     [ 1., 2., 3.], 
     [ 1., 2., 3.]]) 

In [167]: ab*aa 
Out[167]: 
array([[ 1., 2., 3.], 
     [ 1., 2., 3.], 
     [ 1., 2., 3.]]) 
+0

Arh tak masz rację co do macierzy. Poprawię moje pytanie. Jednak moje pytanie dotyczy dodatku, w którym transmisja wydaje się działać tak, jak wskazano w zaakceptowanej odpowiedzi. – andershqst

+0

Tak, proszę; Chciałem tylko ostrzec cię przed możliwym nieoczekiwanym zachowaniem. – askewchan

+0

Tak, dziękuję. – andershqst

Powiązane problemy