目录
3、torch.Tensor与torch.tensor的几点区别
一、Tensor概述
1、对tensor的操作很多,从接口的角度来划分,可以分为两类:
(1)torch.function,如torch.sum、torch.add等,
(2)tensor.function,如tensor.view、tensor.add等。
2、如果从修改方式的角度,可以分为以下两类:
(1)不修改自身数据,如x.add(y),x的数据不变,返回一个新的tensor。
(2)修改自身数据,如x.add_(y)(运行符带下划线后缀),运算结果存在x中,x被修改。
import torch
x=torch.tensor([1,2])
y=torch.tensor([3,4])
z=x.add(y)
print(z)
print(x)
x.add_(y)
print(x)
运行结果
tensor([4, 6])
tensor([1, 2])
tensor([4, 6])
二、创建Tensor
1、表1 常见的新建tensor方法
补充:
torch.full([2,4],2) #根据形状[2,4],填充指定数值2
2、创建张量的方法
Tensor(序列) #其中序列可以是列表、元组、array(数组)
3、torch.Tensor与torch.tensor的几点区别
①torch.Tensor是torch.empty和torch.tensor之间的一种混合,但是,当传入数据时,torch.Tensor使用全局默认dtype(FloatTensor),torch.tensor从数据中推断数据类型。
②torch.tensor(1)返回一个固定值1,而torch.Tensor(1)返回一个大小为1的张量,它是随机初始化的值。