python连乘函数_python中np.multiply()、np.dot()和星号(*)三种乘法运算的区别(转)...

为了区分三种乘法运算的规则,具体分析如下:

import numpy as np

1. np.multiply()函数

函数作用

数组和矩阵对应位置相乘,输出与相乘数组/矩阵的大小一致

1.1数组场景

【code】

A = np.arange(1,5).reshape(2,2)

A

【result】

array([[1, 2],

[3, 4]])

【code】

B = np.arange(0,4).reshape(2,2)

B

【result】

array([[0, 1],

[2, 3]])

【code】

np.multiply(A,B) #数组对应元素位置相乘

【result】

array([[ 0, 2],

[ 6, 12]])

1.2 矩阵场景

【code】

np.multiply(np.mat(A),np.mat(B)) #矩阵对应元素位置相乘,利用np.mat()将数组转换为矩阵

【result】

matrix([[ 0, 2],

[ 6, 12]])

【code】

np.sum(np.multiply(np.mat(A),np.mat(B))) #输出为标量

【result】

20

2. np.dot()函数

函数作用

对于秩为1的数组,执行对应位置相乘,然后再相加;

对于秩不为1的二维数组,执行矩阵乘法运算;超过二维的可以参考numpy库介绍。

2.1 数组场景

2.1.1 数组秩不为1的场景

【code】

A = np.arange(1,5).reshape(2,2)

A

【result】

array([[1, 2],

[3, 4]])

【code】

B = np.arange(0,4).reshape(2,2)

B

【result】

array([[0, 1],

[2, 3]])

【code】

np.dot(A,B) #对数组执行矩阵相乘运算

【result】

array([[ 4, 7],

[ 8, 15]])

2.1.2 数组秩为1的场景

【code】

C = np.arange(1,4)

C

【result】

array([1, 2, 3])

【code】

D = np.arange(0,3)

D

【result】

array([0, 1, 2])

【code】

np.dot(C,D) #对应位置相乘,再求和

【result】

8

2.2 矩阵场景

【code】

np.dot(np.mat(A),np.mat(B)) #执行矩阵乘法运算

【result】

matrix([[ 4, 7],

[ 8, 15]])

3. 星号(*)乘法运算

作用

对数组执行对应位置相乘

对矩阵执行矩阵乘法运算

3.1 数组场景

【code】

A = np.arange(1,5).reshape(2,2)

A

【result】

array([[1, 2],

[3, 4]])

【code】

B = np.arange(0,4).reshape(2,2)

B

【result】

array([[0, 1],

[2, 3]])

【code】

A*B #对应位置点乘

【result】

array([[ 0, 2],

[ 6, 12]])

3.2矩阵场景

【code】

(np.mat(A))*(np.mat(B)) #执行矩阵运算

【result】

matrix([[ 4, 7],

[ 8, 15]])

------------------------------------------------

转载自:https://blog.csdn.net/zenghaitao0128/article/details/78715140

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值