基于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自动化开发学习之三级菜单制作

本文实例为大家分享了Python三级菜单展示的具体代码,供大家参考,具体内容如下 作业需求: (1)运行程序输出第一级菜单 (2)选择一级菜单某项,输出二级菜单,同理输出三级菜单 (3...

python requests更换代理适用于IP频率限制的方法

python requests更换代理适用于IP频率限制的方法

有些网址具有IP限制,比如同一个IP一天只能点赞一次。 解决方法就是更换代理IP。 从哪里获得成千上万的IP呢? 百度“http代理” 可获得一大堆网站。 比如某代理网站,1天...

Python使用pyautogui模块实现自动化鼠标和键盘操作示例

本文实例讲述了Python使用pyautogui模块实现自动化鼠标和键盘操作。分享给大家供大家参考,具体如下: 一、pyautogui模块简要说明 ## 使用 pyautogui 模块...

浅谈Pandas 排序之后索引的问题

如下所示: In [1]: import pandas as pd ...: df=pd.DataFrame({"a":[1,2,3,4,5],"b":[5,4,3,2,1]})...

python多进程控制学习小结

python多进程控制学习小结

前言: python多进程,经常在使用,却没有怎么系统的学习过,官网上面讲得比较细,结合自己的学习,整理记录下官网:https://docs.python.org/3/library/m...