python数组对应元素相乘(multiply)、两个矩阵相乘(dot)、星号(*)乘法-Python中数组、矩阵乘法

59 篇文章 4 订阅
46 篇文章 3 订阅


想必大家做机器学习都被矩阵乘法,矩阵对应元素相乘等问题困扰过。本文将一一为大家讲解。

1.np.dot

np.dot()函数主要有两个功能,向量点积和矩阵乘法,这里我就简单列举了三种最常用到的情况

  1. np.dot(a, b), 其中a为一维的向量,b为一维的向量,当然这里a和b都是np.ndarray类型的, 此时因为是一维的所以是向量点积。
import numpy as np
 
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
print(np.dot(a, b))
 
output:
130
[Finished in 0.2s]
  1. np.dot(a, b), 其中a为二维矩阵,b为一维向量,这时b会被当做一维矩阵进行计算
import numpy as np
 
a = np.random.randint(0,10, size = (5,5))
b = np.array([1,2,3,4,5])
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print(np.dot(a, b))
 
 
output:
the shape of a is (5, 5)
the shape of b is (5,)
[42 85 50 81 76]
[Finished in 0.2s]

这里需要注意的是一维矩阵和一维向量的区别,一维向量的shape是(5, ), 而一维矩阵的shape是(5, 1), 若两个参数a和b都是一维向量则是计算的点积,但是当其中有一个是矩阵时(包括一维矩阵),dot便进行矩阵乘法运算,同时若有个参数为向量,会自动转换为一维矩阵进行计算。

  1. np.dot(a ,b), 其中a和b都是二维矩阵,此时dot就是进行的矩阵乘法运算
import numpy as np
 
a = np.random.randint(0, 10, size = (5, 5))
b = np.random.randint(0, 10, size = (5, 3))
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print(np.dot(a, b))
 
 
output:
the shape of a is (5, 5)
the shape of b is (5, 3)
[[ 66  80  98]
 [ 53  60  60]
 [ 65  84  85]
 [ 25 113 101]
 [ 42  78  77]]
[Finished in 0.2s]

2.np.multiply()

由于multiply是ufunc函数,ufunc函数会对这两个数组的对应元素进行计算,因此它要求这两个数组有相同的大小(shape相同),相同则是计算内积。如果shape不同的话,会将小规格的矩阵延展成与另一矩阵一样大小,再求两者内积。
两种情况:
1、当两个规格大小一样时,得到结果则是两个的内积

In :       	a = np.arange(1,5).reshape(2,2)# a.shape = (2,2)	#a.shape = (2,2)
In :       	b = np.array([1,2,3,4]).reshape(2,2)          		#b.shape = (2,2)
Out: 		[[1 2]												#其中a =b
 			 [3 4]]

In : 		np.multiply(a, b) 
Out: 		[[ 1  4]
 			 [ 9 16]]               							#结果是a与b的内积                      	

2、当两个矩阵大小不一样,则先将小的扩大到与另一矩阵大小一样,再求内积

In :       	a = np.array ([[1,2,3],[4,5,6]])         # a.shape = (2, 3)
Out: 		[[1 2 3]
			 [4 5 6]]

In :       	b = np.array([1,2,3])         			 # b.shape = (1,3)
In : 		np.multiply(a, b) 						 #先将b扩展成 array ([[1, 2, 3],
        		    								 #					 [1, 2, 3]])  

Out: 		array ([[1, 4, 9],
        		    [4,10,18]])            			#最后a与b*的内积(b*是延展后的b)                     	

3.星号(*)

作用

对数组执行对应位置相乘
对矩阵执行矩阵乘法运算

A = np.arange(1,5).reshape(2,2)
B = np.arange(0,4).reshape(2,2)
print(A*B)

array([[ 0, 2],
[ 6, 12]])

(np.mat(A))*(np.mat(B))

matrix([[ 4, 7],
[ 8, 15]])

  • 22
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值