python中numpy.dot()计算矩阵相乘,
python中numpy.dot()计算矩阵相乘,
目录
- 一、如何用 python 计算矩阵乘法?
- 二、实例
- 向量相乘,得到内积
- 矩阵相乘,得到矩阵的积
- 参考链接
一、如何用 python 计算矩阵乘法?
使用 Numpy 包里的 dot() 函数。
该函数主要功能有两个:向量点积 和 矩阵乘法 。
格式:x.dot(y) 等价于 np.dot(x,y)
x 是m × n 矩阵 ,y 是 n×m 矩阵,则 x.dot(y) 得到 m×m 矩阵。
二、实例
向量相乘,得到内积
import numpy as np x=np.array([0,1,2,3,4]) #等价于 x=np.arange(0,5) y=x[::-1] print(x) print(y) print(np.dot(x,y))
输出结果:
[0 1 2 3 4]
[4 3 2 1 0]
10
矩阵相乘,得到矩阵的积
(1)实例 1
import numpy as np x=np.arange(0,5) # 0,10,是随机数的方位,size=(5,1),也就是5维矩阵,且每一维元素数为1个 y=np.random.randint(0,10,size=(5,1)) print(x) print(y) # 查看矩阵或者数组的维数 print("x.shape:"+str(x.shape)) print("y.shape"+str(y.shape)) print(np.dot(x,y))
输出结果:
[0 1 2 3 4]
[[1]
[7]
[1]
[3]
[8]]
x.shape:(5,)
y.shape(5, 1)
[50]
(2)实例 2
import numpy as np x=np.arange(0,6).reshape(2,3) y=np.random.randint(0,10,size=(3,2)) print(x) print(y) print("x.shape:"+str(x.shape)) print("y.shape"+str(y.shape)) print(np.dot(x,y))
输出结果:
[[0 1 2]
[3 4 5]]
[[1 8]
[6 1]
[3 9]]
x.shape:(2, 3)
y.shape(3, 2)
[[12 19]
[42 73]]
参考链接
Numpy——np.dot()函数用法
到此这篇关于python中numpy.dot()计算矩阵相乘的文章就介绍到这了,更多相关python numpy.dot()矩阵相乘内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!
您可能感兴趣的文章:- python中使用numpy包的向量矩阵相乘np.dot和np.matmul实现
- 纯python进行矩阵的相乘运算的方法示例
- python的几种矩阵相乘的公式详解
- Python实现的矩阵转置与矩阵相乘运算示例
- Python实现矩阵相乘的三种方法小结
评论关闭