基于python及pytorch中乘法的使用详解

yipeiwu_com5年前Python基础

numpy中的乘法

A = np.array([[1, 2, 3], [2, 3, 4]])
B = np.array([[1, 0, 1], [2, 1, -1]])
C = np.array([[1, 0], [0, 1], [-1, 0]])
 
A * B : # 对应位置相乘
np.array([[ 1, 0, 3], [ 4, 3, -4]]) 
 
A.dot(B) :  # 矩阵乘法 
ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)
 
A.dot(C) : # 矩阵乘法  | < -- > np.dot(A, C)
np.array([[-2, 2],[-2, 3]])

总结 : 在numpy中,*表示为两个数组对应位置相乘; dot表示两个数组进行矩阵乘法

pytorch中的乘法

A = torch.tensor([[1, 2, 3], [2, 3, 4]])
B = torch.tensor([[1, 0, 1], [2, 1, -1]])
C = torch.tensor([[1, 0], [0, 1], [-1, 0]])
 
# 矩阵乘法
torch.mm(mat1, mat2, out=None) <--> torch.matmul(mat1, mat2, out=None)
eg : 
  torch.mm(A, B)   : RuntimeError: size mismatch, m1: [2 x 3], m2: [2 x 3]
  torch.mm(A, C)   : tensor([[-2, 2], [-2, 3]])
  torch.matmul(A, C) : tensor([[-2, 2], [-2, 3]])
 
# 点乘
torch.mul(mat1, mat2, out=None)
 
eg :
  torch.mul(A, B) : tensor([[ 1, 0, 3], [ 4, 3, -4]])
  torch.mul(A, C) : RuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 1

总结 : 在pytorch中,mul表示为两个数组对应位置相乘; mm和matmul表示两个数组进行矩阵乘法

以上这篇基于python及pytorch中乘法的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 装饰器使用详解

装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.   经常用于有切面需求的场景,比如:插入日志、性能测试、...

浅谈关于Python3中venv虚拟环境

浅谈关于Python3中venv虚拟环境

Python3.3以上的版本通过venv模块原生支持虚拟环境,可以代替Python之前的virtualenv。 该venv模块提供了创建轻量级“虚拟环境”,提供与系统Python的隔离支...

使用Python编写一个简单的tic-tac-toe游戏的教程

 这个教程,我们将展示如何用python创建一个井字游戏。 其中我们将使用函数、数组、if条件语句、while循环语句和错误捕获等。 首先我们需要创建两个函数,第一个函数用来显...

python 通过xml获取测试节点和属性的实例

写在前面:通过xml获取测试数据,主要是为了使数据参数化。测试脚本和测试数据分离,使得脚本清晰容易维护,方便排查问题。 XML:可扩展的标记语言,是一种用于标记电子文件使其具有结构行的...

用python + openpyxl处理excel2007文档思路以及心得

寻觅工具 确定任务之后第一步就是找个趁手的库来干活。 Python Excel上列出了xlrd、xlwt、xlutils这几个包,但是 它们都比较老,xlwt甚至不支持07版以后的exc...