PyTorch学习2:创建Tensor的多种方法

import torch
import numpy as np

# Import form numpy:使用numpy进行创建
a = np.array([2, 3.3])
print(a)  # [2.  3.3]
b = torch.from_numpy(a)  # numpy转化为tensor类型
print(b)  # tensor([2.0000, 3.3000], dtype=torch.float64)

# Import form List:使用list创建
a = torch.tensor([2, 3.2])
print(a)  # tensor([2.0000, 3.2000])
b = torch.FloatTensor([2, 3.2])
print(b)  # tensor([2.0000, 3.2000])
c = torch.FloatTensor(2, 3)
print(c)

# uninitialized:根据shape创建Tensor
a = torch.empty(2, 3)
print(a)
b = torch.Tensor(2, 3)
print(b)
c = torch.IntTensor(2, 3)
print(c)
d = torch.FloatTensor(2, 3)
print(d)

# set default type:修改tensor的默认类型
a = torch.tensor([1.2, 3]).type()
print(a)  # torch.FloatTensor
torch.set_default_tensor_type(torch.DoubleTensor)
b = torch.tensor([1.2, 3]).type()
print(b)  # torch.DoubleTensor

# rand/rand_like, randit
a = torch.rand(3, 3)  # 采样自0~1均匀分布
print(a)
b = torch.rand(3, 3)
c = torch.rand_like(b)
print(b)
print(c)
a = torch.randint(1, 10, [3, 3])  # 在区间[1, 10)上随机采样,生成shape=2,2的LongTensor
print(a)

# randn:正态分布
a = torch.randn(3, 3)  # 采样自(0, 1)正态分布
print(a)

# full:使用相同元素构建
a = torch.full([2, 3], 7)  # shape=2,3, 所使用的相同的元素为7
print(a)

# # arange/range
b = torch.arange(0, 10)
print(b)  # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
c = torch.arange(0, 10, 2)
print(c)  # tensor([0, 2, 4, 6, 8])
d = torch.range(0, 10)
print(d)

# linspace/logspace:注意第三个参数为步长
a = torch.linspace(0, 10, steps=4)  # 注意:10也可以取到
print(a)  # tensor([ 0.0000,  3.3333,  6.6667, 10.0000])
b = torch.linspace(0, 10, steps=10)
print(b)  # tensor([ 0.0000,  1.1111,  2.2222,  3.3333,  4.4444,  5.5556,  6.6667,  7.7778,8.8889, 10.0000])
c = torch.linspace(0, 10, steps=11)
print(c)  # # tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

# Ones/zeros/eye
a = torch.ones(3, 3)  # 全1
print(a)
b = torch.zeros(3, 3)  # 全0
print(b)
c = torch.eye(3, 3)  # 对角阵
print(c)
d = torch.eye(5)  # shape=5,5的对角阵
print(d)

# randperm: random.shuffle
# 两个Tensor的shape[0]是相同的,都是2
a = torch.rand(2, 3)
b = torch.rand(2, 2)
idx = torch.randperm(2)  # 制造一个[0,2)的索引序列
print(idx)  # 是变化的
print(a[idx])
print(a)
print(b[idx])
print(b)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碳烤小肥羊。。。

你的鼓励是我创造最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值