文章目錄
- 一、乘法
- 二、轉置
- array.transpose()
- array.T
- reshape()
- 求逆
一、乘法
- numpy.dot(x,y)就是正常的向量或者矩陣乘法
-
x*y:
分情況討論- 如果x和y是維度相同的行(列)向量或者矩陣,結果是對應位置的數相乘:
import
numpy
as
np
a
=
np
.
array
(
[
1
,
2
,
3
]
)
b
=
np
.
array
(
[
4
,
2
,
6
]
)
print
(
a
*
b
)
# 結果 array([ 4, 4, 18])
c
=
np
.
array
(
[
[
1
]
,
[
2
]
,
[
3
]
]
)
d
=
np
.
array
(
[
[
4
]
,
[
2
]
,
[
6
]
]
)
print
(
c
*
d
)
# array([[ 4],
# [ 4],
# [18]])
>>
>
e
array
(
[
[
4
,
8
,
12
]
,
[
2
,
4
,
6
]
,
[
6
,
12
,
18
]
]
)
>>
>
f
array
(
[
[
2
,
3
,
4
]
,
[
2
,
4
,
6
]
,
[
6
,
3
,
7
]
]
)
>>
>
e
*
f
array
(
[
[
8
,
24
,
48
]
,
[
4
,
16
,
36
]
,
[
36
,
36
,
126
]
]
)
- 如果x和y,一個是行向量,另一個是列向量,那么,將行或列進行復制,形成相同形狀的矩陣后,在對應位置的元素相乘:
>>
>
a
array
(
[
1
,
2
,
3
]
)
>>
>
d
array
(
[
[
4
]
,
[
2
]
,
[
6
]
]
)
>>
>
a
*
d
array
(
[
[
4
,
8
,
12
]
,
[
2
,
4
,
6
]
,
[
6
,
12
,
18
]
]
)
- 如果x和y是維度不相同的矩陣則無法進行這種運算
>>
>
h
array
(
[
[
2
,
3
]
,
[
3
,
5
]
,
[
4
,
6
]
]
)
>>
>
g
array
(
[
[
2
,
3
,
5
]
,
[
3
,
5
,
6
]
]
)
>>
>
g
*
h
Traceback
(
most recent call last
)
:
File
"
"
,
line
1
,
in
<
module
>
g
*
h
ValueError
:
operands could
not
be broadcast together
with
shapes
(
2
,
3
)
(
3
,
2
)
>>
>
h
*
g
Traceback
(
most recent call last
)
:
File
"
"
,
line
1
,
in
<
module
>
h
*
g
ValueError
:
operands could
not
be broadcast together
with
shapes
(
3
,
2
)
(
2
,
3
)
- 如果x和y一個是矩陣一個是向量,則將向量進行復制,形成與矩陣相同的大小,然后對應位置元素相乘。
>>
>
h
array
(
[
[
2
,
3
]
,
[
3
,
5
]
,
[
4
,
6
]
]
)
>>
>
i
array
(
[
[
3
]
,
[
6
]
,
[
8
]
]
)
>>
>
h
*
i
array
(
[
[
6
,
9
]
,
[
18
,
30
]
,
[
32
,
48
]
]
)
>>
>
i
*
h
array
(
[
[
6
,
9
]
,
[
18
,
30
]
,
[
32
,
48
]
]
)
>>
>
h
array
(
[
[
2
,
3
]
,
[
3
,
5
]
,
[
4
,
6
]
]
)
>>
>
g
=
np
.
array
(
[
3
,
4
]
)
>>
>
h
*
g
array
(
[
[
6
,
12
]
,
[
9
,
20
]
,
[
12
,
24
]
]
)
>>
>
g
*
h
array
(
[
[
6
,
12
]
,
[
9
,
20
]
,
[
12
,
24
]
]
)
二、轉置
array.transpose()
array.T
首先需要說明的是,如果你的array是行向量。那么前兩個轉置方法是沒有用的。如果是列向量或者矩陣,要轉置成為行向量,那么前兩個是有用的。示例如下:
>>> b
array([4, 2, 6])
>>> b.T
array([4, 2, 6])
>>> b.transpose()
array([4, 2, 6])
>>> c
array([[1],
[2],
[3]])
>>> c.T
array([[1, 2, 3]])
>>> c.transpose()
array([[1, 2, 3]])
>>> h
array([[2, 3],
[3, 5],
[4, 6]])
>>> h.T
array([[2, 3, 4],
[3, 5, 6]])
>>> h.transpose()
array([[2, 3, 4],
[3, 5, 6]])
- 不管是矩陣還是向量下面這個方法一定是有用的,但一般只用這個處理行向量的轉置:
reshape()
其原型如下:
numpy
.
reshape
(
a
,
newshape
,
order
=
'C'
)
[
source
]
?
# a:待reshape的數組
# newshape: 新數組的樣式,(x,y), 表示x行,y列,如果y為-1,那么它會根據原數組中數據的數量,以及行x的數量,自動計算y的值。
使用示例:
import
numpy
as
np
a
=
np
.
array
(
[
1
,
2
,
3
]
)
;
b
=
np
.
reshape
(
a
,
(
3
,
-
1
)
)
;
print
(
b
)
#結果:[[1]
# [2]
# [3]]
求逆
Q
=
np
.
array
(
[
[
-
0.6
,
-
0.8
]
,
[
-
0.8
,
0.6
]
]
)
np
.
linalg
.
inv
(
Q
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
