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

相关文章

Android分包MultiDex策略详解

1.分包背景 这里首先介绍下MultiDex的产生背景。 当Android系统安装一个应用的时候,有一步是对Dex进行优化,这个过程有一个专门的工具来处理,叫DexOpt。DexOpt的...

关于Numpy中的行向量和列向量详解

行向量 方式1 import numpy as np b=np.array([1,2,3]).reshape((1,-1)) print(b,b.shape) 结果: (arr...

在Django中创建第一个静态视图

正如我们的第一个目标,创建一个网页,用来输出这个著名的示例信息: Hello world. 如果你曾经发布过Hello world页面,但是没有使用网页框架,只是简单的在h...

对python中的try、except、finally 执行顺序详解

如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to r...

解决python Markdown模块乱码的问题

解决python Markdown模块乱码的问题

有个需求需要把markdown转成html模块,查询了一下刚好有这个模块 安装 pip install amrkdown 安装完成直接转换并保存为html时,发现出现中文乱码的情况 用...