PyTorch中tensor的相关操作

list、numpy、tensor两两之间的相关转换

list 转 numpy

ndarray = np.array(list)

# 具体例子如下
import numpy as np
a_list  = [1, 2, 3]
a_np  = np.array(a_list)

numpy 转 list

list = ndarray.tolist()

#具体例子如下所示
import numpy as np
a_list  = [1, 2, 3]
a_np  = np.array(a_list)
a_to_list = a_np.tolist()

用numpy创建tensor

tensor = torch.from_numpy(np.zeros(r, c))

row = 2
column = 3
a_tensor = torch.from_numpy(np.zeros((row,column)))

## 将创建好的tensor分配到指定的设备中
os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1'
device = 'cuda' if torch.cuda.is_available() else 'cpu'
a_tensor_device = a_tensora_tensor.to(device)
# 此处是将a_tensor分配到cuda 0 和1

list 转 torch.Tensor

tensor=torch.Tensor(list)

a_tensor =torch.Tensor(a_list)

torch.Tensor 转 list

Tensor不可直接转换为list , 需要先转换为numpy,然后在转换为list
list = tensor.numpy().tolist()

a_list = a_tensor.numpy().tolist()

torch.Tensor 转换为numpy

ndarray = tensor.numpy()
gpu上的tensor不能直接转为numpy
ndarray = tensor.cpu().numpy()

# 普通的tensor转换为numpy
a_np = a_tensor.numpy()

# GPU上的tensor转换为numpy
a_np_gpu = a_tensor.cpu().numpy()

tensor(PyTorch)的一些基本操作

tensor 设置数据类型

import torch
a = [1, 2, 3, 5]
b = [1.2, 3.3, 5.6]
da = torch.tensor(a) # 此时da的数据是tensor.int64的类型,此时是默认的数据类型
db =torch.tensor(b) # 此时db的数据是tensor.float32的类型,此时是默认的数据类型

daa = torch.tensor(a, dtype = torch.long) # 此时da的数据是tensor.int64的类型,这是指定的数据类型
# 在指定数据类型时要注意:
#      1. 若是原本数据是整数,则指定为整数型和浮点型都没问题
#      2. 若是原本数据是小数,则指定为浮点型数据时没有问题,但是在指定为整数型会出现问题,直接将数字的小数部分直接丢掉,而只保留整数部分

在这里插入图片描述

tensor 创建注意的几个Tips

  • torch.randtorch.randn是两个不同的分布函数的随机数创建。
    • torch.rand:返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
    • torch.randn:返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数
# 具体例子如下所示:
import torch
a = torch.rand(1,2)
a
# output: tensor([[0.7504, 0.5853]])
b = torch.randn(1,2)
b
#output: tensor([[-0.3798,  0.0115]])
  • torch.normal创建
    torch.normal创建的是符合离散正态分布随机数,可以指定均值和方差。
# 具体例子如下所示
torch.normal(2, 3, size=(1, 4))
# 2:表示mean
# 3:表示std
# size=(1, 4):表示输出tensor的维度大小
  • torch.full创建
    torch.full创建任意指定维度而且指定值的tensor。
# 具体例子如下所示:
import torch
x=torch.full((2,3),1.2,dtype=torch.float)
x
# output: tensor([[1.2000, 1.2000, 1.2000],
                            [1.2000, 1.2000, 1.2000]])
# (2,3):表示指定生成tensor的维度,这里只是二维,当然可以更高维
# 1.2:表示指定的值
# dtype=torch.float:表示生成的数据的类型

单个元素tensor取值

单个元素tensor取值可以使用Tensor.item()

import torch
x = torch.randn(1)
y = x.item()
print('x: {}'.format(x))
print('y: {}'.format(y))
# output
# x: tensor([-1.4665])
# y: -1.4664647579193115

不同维度tensor最大值(最小值)的选择

torch.max, torch.min不仅会返回最大值、最小值,而且在指定的维度会返回其对应的位置,但是不指定维度直接使用只会返回最大值、最小值。torch.max和torch.min用法一样,只是一个是求最大值,一个是求最小值。

# 具体以torch.max为例
import torch
a = torch.randn(2,10)
a
# output:
# tensor([[ 1.3100e+00, -3.4182e-01, -5.7281e-02, -4.9519e-04,  6.6183e-01,
#         -5.5695e-01, -9.3556e-01,  3.4168e-01,  8.3933e-01, -9.3372e-01],
#         [-6.6425e-01,  3.1085e-01,  1.9820e+00, -3.6192e-01,  2.3477e-01,
 #          5.9145e-02,  7.1136e-01,  6.0131e-01,  1.9997e+00,  2.6330e+00]])
torch.max(a)
# output:
# tensor(2.6330)
a = torch.randn(2,3,4,3) # 2*3*4*3: N*C*H*W
a
torch.max(a, 0) # 在N这个维度上进行比较大小去最大值,并且返回其位置(是N中的哪一个)
# output:
# torch.return_types.max(
# values=tensor([[[-0.0233,  0.6172,  1.1725],
#          [-0.0720, -0.7014,  0.2533],
#          [ 0.5254,  1.6286, -0.6081],
#          [ 0.7030, -0.7195, -0.3218]],

#         [[-0.2194, -0.5759,  1.6942],
#          [-0.1742, -0.2742,  1.3223],
#          [ 2.0272,  0.9716,  2.2349],
#          [-0.6161,  0.6193,  1.1204]],

#         [[ 0.3826, -0.4263,  0.4860],
#          [ 0.1900, -0.2935,  0.2704],
#          [ 0.4831,  0.6423,  1.3739],
#          [-0.1392, -0.3983,  0.8989]]]),
# indices=tensor([[[0, 0, 0],
#          [0, 0, 1],
#          [1, 0, 0],
#          [1, 0, 0]],

#         [[1, 1, 0],
#          [1, 0, 1],
#          [0, 1, 0],
#          [1, 1, 1]],

#         [[1, 0, 1],
#          [0, 1, 0],
#          [1, 1, 1],
#          [1, 0, 1]]]))
torch.max(a, 1) # 在C这个维度上进行比较大小去最大值,并且返回其位置(是C中的哪一个,每个N中分别比较)
# output:
# torch.return_types.max(
# values=tensor([[[-0.0233,  0.6172,  1.6942],
#          [ 0.1900, -0.2742,  0.2704],
#          [ 2.0272,  1.6286,  2.2349],
#          [-1.3326, -0.3983,  0.4357]],

#         [[ 0.3826, -0.2523,  0.4860],
#          [-0.1742, -0.2935,  1.3223],
#          [ 0.5254,  0.9716,  1.3739],
#          [ 0.7030,  0.6193,  1.1204]]]),
# indices=tensor([[[0, 0, 1],
#          [2, 1, 2],
#          [1, 0, 1],
#          [2, 2, 1]],

#         [[2, 0, 2],
#          [1, 2, 1],
#          [0, 1, 2],
#          [0, 1, 1]]]))
torch.max(a, 2) # 在H这个维度上进行比较大小去最大值,并且返回其位置(是H中的哪一个,每个N中分别比较)
# output:
# torch.return_types.max(
# values=tensor([[[-0.0233,  1.6286,  1.1725],
#          [ 2.0272, -0.2742,  2.2349],
#          [ 0.1900, -0.3983,  0.2704]],

#         [[ 0.7030, -0.2523,  0.2625],
#          [-0.1742,  0.9716,  1.3223],
#          [ 0.4831,  0.6423,  1.3739]]]),
# indices=tensor([[[0, 2, 0],
#          [2, 1, 2],
#          [1, 3, 1]],

#         [[3, 0, 0],
#          [1, 2, 1],
#          [2, 2, 2]]]))
torch.max(a, 3) # 在W这个维度上进行比较大小去最大值,并且返回其位置(是W中的哪一个,每个N中分别比较)
# output:
# torch.return_types.max(
# values=tensor([[[ 1.1725, -0.0720,  1.6286, -0.3218],
#          [ 1.6942, -0.2742,  2.2349,  0.4357],
#          [-0.4263,  0.2704,  0.1508, -0.3983]],

#         [[ 0.2625,  0.2533,  0.5254,  0.7030],
#          [ 0.3899,  1.3223,  1.0412,  1.1204],
#          [ 0.4860, -0.2935,  1.3739,  0.8989]]]),
# indices=tensor([[[2, 0, 1, 2],
#          [2, 1, 2, 2],
#          [1, 2, 0, 1]],

#         [[2, 2, 0, 0],
#          [2, 2, 2, 2],
#          [2, 1, 2, 2]]]))

tensor 的拆分、拼接、加减乘除、乘方、开方、指数、对数、裁剪等操作

此处我就不写了,有份资料写的很详细:Pytorch张量高阶操作
注意:
直接使用torch.add(1)函数,张量的值会加1,但张量本身不会发生改变。而使用torch.add_(1)是直接在张量上进行加1操作,会改变张量的值。

tensor的切片和索引

tensor的切片和索引与numpy相同,可以参考:NumPy 切片和索引

几个和训练模型相关的pytorch的资料

以下的几份资料可以用作pytorch撰写神经网络模型的入门材料:

  1. PyTorch简明教程
  2. PyTorch深度学习:60分钟入门(Translation)
  3. torch的常用模块学习
    最后也是最好的资料:官方的教程

参考资料

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Tensor views在PyTorch是一种非常有用的操作,它可以让我们对一个Tensor进行不同的视图操作,而不会改变它的数据本身。这个操作可以极大地减少内存的占用,同时也能够提高代码的效率。 在PyTorch,我们可以使用以下方法创建Tensor views: 1. `view()`:这个方法可以改变Tensor的形状,但是新的Tensor必须和原来的Tensor包含相同的元素数目。如果你想要改变Tensor的形状,但是又不想改变Tensor的数据,那么view()方法就是你需要的。 2. `reshape()`:这个方法和view()方法很像,但是它可以改变Tensor的形状,即使新的Tensor和原来的Tensor包含不同数量的元素。如果你想要改变Tensor的形状,同时还想改变Tensor的数据,那么reshape()方法就是你需要的。 3. `narrow()`:这个方法可以让你从一个Tensor选择一个子集,这个子集是一个连续的Tensor。你可以使用这个方法来实现切片操作。 4. `expand()`:这个方法可以让你将一个Tensor扩展成一个更大的Tensor,但是数据并不会被复制。 5. `transpose()`:这个方法可以让你将Tensor的维度交换。 下面是一些具体的操作示例: ```python import torch # 创建一个大小为(2, 3)的Tensor x = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 使用view()方法创建一个视图 y = x.view(6) print(y) # 使用reshape()方法创建一个视图 z = x.reshape(3, 2) print(z) # 使用narrow()方法创建一个视图 w = x.narrow(1, 1, 2) print(w) # 使用expand()方法创建一个视图 u = x.expand(2, 3, 2) print(u) # 使用transpose()方法创建一个视图 v = x.transpose(0, 1) print(v) ``` 输出结果如下: ``` tensor([1, 2, 3, 4, 5, 6]) tensor([[1, 2], [3, 4], [5, 6]]) tensor([[2, 3], [5, 6]]) tensor([[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]]) tensor([[1, 4], [2, 5], [3, 6]]) ``` 可以看到,我们使用不同的方法创建了不同的Tensor views,并且这些views对原来的Tensor没有任何影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值