NJU1healer的个人博客分享 http://blog.sciencenet.cn/u/NJU1healer

博文

Python 中的几种矩阵乘法 np.dot, np.multiply, *

已有 4755 次阅读 2020-10-23 21:40 |个人分类:Python|系统分类:科研笔记

Python中的几种矩阵乘法

1. 同线性代数中矩阵乘法的定义: np.dot()

       np.dot(A, B):对于二维矩阵,计算真正意义上的矩阵乘积,同线性代数中矩阵乘法的定义。对于一维矩阵,计算两者的内积。见如下Python代码:

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))

结果如下:

two_multi_res: [[22 28]

 [49 64]]

one_result_res: 32

2. 对应元素相乘 element-wise product: np.multiply(), 或 *

       在Python中,实现对应元素相乘,有2种方式,一个是np.multiply(),另外一个是*。见如下Python代码:

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))

结果如下:

element wise product: [[ 7 16 27]

 [16 35  6]]

element wise product: [[ 7 16 27]

 [16 35  6]]

【参考】

https://blog.csdn.net/u012609509/article/details/70230204/

点滴分享,福泽你我!Add oil!



https://blog.sciencenet.cn/blog-3428464-1255542.html

上一篇:BatchNorm, LayerNorm, InstanceNorm和GroupNorm总结
下一篇:torch.mean()
收藏 IP: 103.149.249.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-29 17:39

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部