Tensor创建、随机生成、索引与切片、维度变换

本文详细介绍PyTorch中Tensor的创建、随机生成、索引与切片、维度变换等核心操作,帮助读者掌握Tensor的基本使用技巧。

一、Tensor创建

1.import from numpy

  1. torch.from_numpy():从numpy中导入
a = np.array([2,3.3])
# 导入
print(torch.from_numpy(a))
# out : tensor([2.0000, 3.3000], dtype=torch.float64)

2.import from list

  1. torch.tensor([]):接收现有的数据
  2. torch.FloatTensor(shape):一般是接收shape,尽量避免直接接收list
#接收现有的数据 Tensor接收数据的维度
a = torch.tensor([2.,3.2]) 
print(a)
# out : tensor([2.0000, 3.2000])
a = torch.FloatTensor([2.,3.2]) # 一般情况存放shape
print(a)
# out : tensor([2.0000, 3.2000])
a = torch.FloatTensor(2,2,3)
print(a)
# out : tensor([[[7.5555e+31, 1.2705e+31, 3.2611e-12],
#         [7.5555e+31, 1.2705e+31, 1.7225e+22]],
#        [[1.2102e+25, 1.6217e-19, 4.7429e+30],
#         [1.6530e+19, 1.8254e+31, 7.9463e+08]]])
a = torch.tensor([[2.,3.2],[1.,22.3]])
print(a)
# out : tensor([[ 2.0000,  3.2000],
#        [ 1.0000, 22.3000]])

3.初始化tensor

  1. torch.empty(shape):初始化tensor,未初始化的tensor会出现极端数据
  2. torch.FloatTensor(d1,d2,d3):生成Float的Tensor
a = torch.empty(1)
# Out : tensor([0.])

# 未初始化的tensor一定要跟写入数据的后续步骤,比如作为临时容器
torch.FloatTensor(1,2,3)

# 未初始化的tensor出现的问题
b = torch.empty(2,3)
b = torch.Tensor(2,3)

4.设置tensor生成的默认类型

  1. torch.tensor().type():查看tensor生成的数据类型
  2. torch.set_default_tensor_type():改变默认生成的数据类型
# 直接使用tensor的话使用的是自己设定的默认的数据类型
print(torch.tensor([1.2,3]).type())
# out : torch.FloatTensor
#修改默认tensor的数据类型
torch.set_default_tensor_type(torch.DoubleTensor)
print(torch.tensor([1,3.]).type())
# out : torch.DoubleTensor

二、随机生成

1.rand函数

  1. torch.rand(shape):从[0,1]的均匀采样生成
  2. torch.rand_like():接受的是tensor,函数是先求tensor.shape,在传入到rand_like()中
  3. torch.randint(min,max,shape):生成的范围是[min,max)的
  4. torch.randn(shape):正态分布生成
  5. torch.normal(mean=torch.full([10],0),std=torch.arange(1,0,-0.1)):自定义生成10个,均值为0,std为
  6. torch.full():全部赋值为一个元素
  7. torch.randperm():生成[0,x)的下标
# rand函数从[0,1]的均匀采样
a = torch.rand(3,3)
print(a)
# out : tensor([[0.8618, 0.0304, 0.8964],
#        [0.0703, 0.4121, 0.1302],
#        [0.7296, 0.1493, 0.7068]])

# rand_like接受的是tensor
b = torch.rand_like(a)
print(b)
# out : tensor([[0.9976, 0.5621, 0.6491],
#        	   [0.4178, 0.7164, 0.1702],
#              [0.2571, 0.0322, 0.6676]])

# randint(min,max,shap) 范围是[min,max)
c = torch.randint(3,10,[3,3])
print(c)
# out : tensor([[8, 7, 7],
#              [5, 8, 4],
#              [5, 5, 8]])

# 正态分布randn
torch.randn(1,3)
# out : tensor([[-0.8832,  0.2013, -0.5065]])

# N(u,std)
torch.normal(mean=torch.full([10],0),std=torch.arange(1,0,-0.1))
# out : tensor([ 1.2065,  0.5789, -0.1925,  0.2631,  0.5852, -0.6697, -0.6499,  1.0295,
#         0.0067, -0.1699])

# 全部赋值为一个元素
torch
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值