pytorch中创建tensor的几种方法

本文详细介绍了在PyTorch中创建张量的各种方法,包括从NumPy数组、列表创建张量,按指定维度初始化张量,进行随机初始化,使用相同元素构建张量等。此外还介绍了如何通过指定均值和标准差来生成正态分布的张量,以及一些特殊张量如对角阵、全零张量和全一张量的创建。

1.从numpy创建

https://pytorch.org/docs/stable/generated/torch.from_numpy.html

 

2.从list创建

 

3.指定维度的初始化

# 生成2行3列的数据
a = torch.empty(2, 3)
b = torch.FloatTensor(2, 3)
c = torch.IntTensor(2, 3)

 

4.随机初始化

# 采样自0~1均匀分布
a = torch.rand(3, 3)

# 形如*_like接受一个Tensor,将这个Tensor的shape读取出来之后在送入*所表示的函数
# 下面的rand_like(a)即将a的shape=3,3读出来传给torch.rand()函数
b = torch.rand_like(a)  # 相当于执行了torch.rand(3,3)

# 在区间[1,10)上随机采样,生成shape=2,2的LongTensor
c = torch.randint(1, 10, [2, 2])

# 采样自N(0,1)
d = torch.randn(3, 3)

随机变量正态分布:https://pytorch.org/docs/stable/generated/torch.randn.html

 

5.使用相同元素构建

# shape=2,3,所使用的相同的元素为7
b = torch.full([2, 3], 7)

6.指定参数的正态分布

# 指定均值和标准差
a = torch.normal(mean=torch.full([10], 0), std=torch.arange(1, 0, -0.1))

7.linespace

https://pytorch.org/docs/stable/generated/torch.linspace.html

 

8.logspace

https://pytorch.org/docs/stable/generated/torch.logspace.html

 

9.全0

a = torch.zeros([3, 4])

10.全

b = torch.ones([3, 4])

11.对角阵

https://pytorch.org/docs/stable/generated/torch.eye.html

 

12.randperm

>>> torch.randperm(4)
tensor([2, 1, 0, 3])

https://pytorch.org/docs/stable/generated/torch.randperm.html

 

参考:

https://blog.youkuaiyun.com/SHU15121856/article/details/87731878

https://www.jianshu.com/p/39985149c17a

https://zhuanlan.zhihu.com/p/68627509

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值