栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

PyTorch:中.add()和.add

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PyTorch:中.add()和.add

结论:

add 加法 / mul 乘法 / exp 以e为底的指数。

以 “下划线 _” 结尾的 ,均为in-place。
可以简单理解为:修改了对应变量中的数值。
Torch里面所有带 “下划线 _” 的操作,都是in-place的。

.add()和.add_()

.add()和.add_()都能把两个张量加起来,但.add_是in-place操作,如:x.add_(y),x+y的结果会存储到原来的x中。

import torch

x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
z = x.add(y)
print('x.add(y) is: {}'.format(z))
print('after x.add(y), x is: {}'.format(x))
z = x.add_(y)
print('x.add_(y) is: {}'.format(z))
print('after x.add_(y), x is: {}'.format(x))

输出为:

x.add(y) is: tensor([5, 7, 9])
after x.add(y), x is: tensor([1, 2, 3])

x.add_(y) is: tensor([5, 7, 9])
after x.add_(y), x is: tensor([5, 7, 9])
.mul()和.mul_()

x.mul(y)或x.mul_(y)实现把x和y点对点相乘,其中x.mul_(y)是in-place操作,会把相乘的结果存储到x中。值得注意的是,x必须是tensor, y可以是tensor,也可以是数。

import torch

x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
z = x.mul(y)
print('x.mul(y) is: {}'.format(z))
print('after x.mul(y), x is: {}'.format(x))
z = x.mul_(y)
print('x.mul_(y) is: {}'.format(z))
print('after x.mul_(y), x is: {}'.format(x))

输出为:

x.mul(y) is: tensor([ 4, 10, 18])
after x.mul(y), x is: tensor([1, 2, 3])

x.mul_(y) is: tensor([ 4, 10, 18])
after x.mul_(y), x is: tensor([ 4, 10, 18])
.exp()和.exp_()

.exp()和.exp_()都能实现以e为底的指数,区别是.exp_()是in-place操作。

import torch

x = torch.FloatTensor([1, 2, 3])
z = x.exp()
print('x.exp() is: {}'.format(z))
print('after x.exp(), x is: {}'.format(x))
z = x.exp_()
print('x.exp_() is: {}'.format(z))
print('after x.exp_(), x is: {}'.format(x))

输出为:

x.exp() is: tensor([ 2.7183,  7.3891, 20.0855])
after x.exp(), x is: tensor([1., 2., 3.])

x.exp_() is: tensor([ 2.7183,  7.3891, 20.0855])
after x.exp_(), x is: tensor([ 2.7183,  7.3891, 20.0855])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/619263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号