基于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基于pygame实现响应游戏中事件的方法(附源码)

python基于pygame实现响应游戏中事件的方法(附源码)

本文实例讲述了python基于pygame实现响应游戏中事件的方法。分享给大家供大家参考,具体如下: 先看一下我做的demo效果: 当玩家按下键盘上的:上,下,左,右键的时候,后台会打...

Python模块、包(Package)概念与用法分析

Python模块、包(Package)概念与用法分析

本文实例讲述了Python模块、包(Package)概念与用法。分享给大家供大家参考,具体如下: Python中”模块”的概念 在开发中,我们会有很多函数,我们可以把这些函数都放到一个文...

python调用外部程序的实操步骤

python调用外部程序的实操步骤

在python的使用中,有时也不得不调用一下外部程序,那么如何调用外部程序: 首先,我们要启动python软件,使用的是python2.7的版本,具体如图: 在外部调用中主要要用到一...

python-opencv颜色提取分割方法

python-opencv颜色提取分割方法

1.用于简单的对象检测、跟踪 2.简单前背景分割 #encoding:utf-8 #黄色检测 import numpy as np import argparse import cv...

matplotlib.pyplot画图 图片的二进制流的获取方法

有些时候,我们需要画图后的二进制数据流,matplotlib没有提供相关的api,通过源码查看与百度,得到下面此方法 import matplotlib.pyplot as plt...