脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python中的几种矩阵乘法(小结)

Python中的几种矩阵乘法(小结)

2021-08-06 00:36hezhiyao Python

这篇文章主要介绍了Python中的几种矩阵乘法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一.  np.dot()

1.同线性代数中矩阵乘法的定义。np.dot(A, B)表示:

  • 对二维矩阵,计算真正意义上的矩阵乘积。
  • 对于一维矩阵,计算两者的内积。

2.代码

 【code】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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中,实现对应元素相乘(element-wise product),有2种方式,

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

2.代码

【code】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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]]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/hezhiyao/p/8177832.html

延伸 · 阅读

精彩推荐