溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中的幾種矩陣乘法(小結(jié))

發(fā)布時間:2020-10-11 14:58:20 來源:腳本之家 閱讀:197 作者:hezhiyao 欄目:開發(fā)技術

一.  np.dot()

1.同線性代數(shù)中矩陣乘法的定義。np.dot(A, B)表示:

  • 對二維矩陣,計算真正意義上的矩陣乘積。
  • 對于一維矩陣,計算兩者的內(nèi)積。

2.代碼

 【code】

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
# 2-D array: 3 x 2
two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])

two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
print('two_multi_res: %s' %(two_multi_res))

# 1-D array
one_dim_vec_one = np.array([1, 2, 3])
one_dim_vec_two = np.array([4, 5, 6])
one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
print('one_result_res: %s' %(one_result_res))

 【result】

two_multi_res: [[22 28]
                [49 64]]
one_result_res: 32

二. np.multiply()或 *

1.在Python中,實現(xiàn)對應元素相乘(element-wise product),有2種方式,

  • 一個是np.multiply()
  • 另外一個是 *

2.代碼

【code】

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])

# 對應元素相乘 element-wise product
element_wise = two_dim_matrix_one * another_two_dim_matrix_one
print('element wise product: %s' %(element_wise))

# 對應元素相乘 element-wise product
element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
print('element wise product: %s' % (element_wise_2))

【result】

element wise product: [[ 7 16 27]
                       [16 35  6]]
element wise product: [[ 7 16 27]
                       [16 35  6]]

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI