基于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设计】。

相关文章

Flask中endpoint的理解(小结)

在flask框架中,我们经常会遇到endpoint这个东西,最开始也没法理解这个到底是做什么的。最近正好在研究Flask的源码,也就顺带了解了一下这个endpoint 首先,我们看一个...

Python中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

如何运行Python程序的方法

如何运行Python程序的方法

安装完python之后,我们可以做两件事情, 1.将安装目录中的Doc目录下的python331.chm使用手册复制到桌面上,方便学习和查阅 2.将Python安装路径我的是C:\Pyt...

一个基于flask的web应用诞生 使用模板引擎和表单插件(2)

一个基于flask的web应用诞生 使用模板引擎和表单插件(2)

经过了第一章的内容,已经可以做出一些简单的页面,首先用这种方式做一个登录页面,首先要创建一个login的路由方法: @app.route("/login",methods=["GET...

python实现回旋矩阵方式(旋转矩阵)

我们知道Python中是没有数组 这种数据结构的,所以要想实现回旋矩阵,需要先导入一个numpy包, 它是一个由多维数组对象和用于处理数组的例程集合组成的python扩充程序库,可以用来...