python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python numpy.dot()矩阵相乘

python中numpy.dot()计算矩阵相乘

作者:想变厉害的大白菜

本文主要介绍了python中numpy.dot()计算矩阵相乘,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、如何用 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()矩阵相乘内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文