pytorch-张量数据结构

1-1 张量数据结构

  pytorch的基本数据结构是张量Tensor,Tensor也即是一个多维数组。pytorch中的语法和数据结构与numpy大多相似,张量对应于numpy中的array。tensor的type是一个元组。
  在这一小节中,介绍pytorch中张量的数据类型、张量的维度、张量的尺寸等基本概念。

一.pytorch中张量的数据类型

pytorch中张量的数据类型和numpy.array基本一致,但是pytorch的张量不支持str类型的数据。主要的类型包括:
浮点型:
torch.float16,
torch.float32(torch.float),
torcy.float64(torch.double),
整型:
torch.int8,
torch.int16,
torch.int32(torch.long),
torch.int64(torch.int),
8位无符号整型:
torch.uint8,
布尔型:
torch.bool
一般在神经网络中使用的数据类型都是float32.

1.pytorch会根据你的输入张量自动推断数据类型

import numpy as np
import torch

#pytorch会自动根据你的输入去判断是什么类型的数据
a = torch.tensor(1)
print(a, a.dtype)  #在pytorch中使用.dtype来查看张量的数据类型
b = torch.tensor(2.0)
print(b, b.dtype)
c = torch.tensor(True)
print(c, c.dtype)
tensor(1) torch.int64
tensor(2.) torch.float32
tensor(True) torch.bool

2.pytorch指定张量数据类型

import torch

#指定数据类型
a = torch.tensor(1, dtype = torch.int32)
print(a, a.dtype)
b = torch.tensor(2.0, dtype = torch.float64)
print(b, b.dtype)
tensor(1, dtype=torch.int32) torch.int32
tensor(2., dtype=torch.float64) torch.float64 #自动推断会推断成float32类型

3.pytorch不同数据类型之间的转换

# 不同类型进行转换

a = torch.tensor(1)
print(a,a.dtype)
b = a.float()
print(b,b.dtype) #使用a.float将a int型转换成浮点型
c = a.type(torch.float)
print(c,c.dtype) #使用c.type函数将a int型转换成浮点类型
d = a.type_as(b)
print(d,d.dtype) #使用a.type_as(b)将a int型转换成Tensor(b)相同类型
tensor(1) torch.int64
tensor(1.) torch.float32
tensor(1.) torch.float32
tensor(1.) torch.float32

二、pytorch张量的维度

在pytorch,不同类型的数据可以用不同维度(dimension)的张量来表示。

标量为0维张量,向量为1维张量,矩阵为2维张量。

彩色图像有rgb三个通道,可以表示为3维张量;灰度图像只有一个通道,就是一维张量。

视频还有时间维,可以表示为4维张量。

可以简单地总结为:一个list或一个tensor中有几层中括号,就是多少维的张量。

scalar = torch.tensor(True) #tensor中没有[]中括号,为标量
print(scalar)
print(scalar.dim())  # 标量,0维张量
tensor(True)
0
vector = torch.tensor([1.0,2.0,3.0,4.0]) #向量,1维张量
print(vector)
print(vector.dim())
tensor([1., 2., 3., 4.])
1
matrix = torch.tensor([[1.0,2.0],[3.0,4.0]]) #矩阵, 2维张量
print(matrix)
print(matrix.dim())
tensor([[1., 2.],
               
        [3., 4.]])
2
tensor3 = torch.tensor([[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]])  # 3维张量
print(tensor3)
print(tensor3.dim())
tensor([[[1., 2.],
         [3., 4.]],

        [[5., 6.],
         [7., 8.]]])
3
tensor4 = torch.tensor([[[[1.0,1.0],[2.0,2.0]],[[3.0,3.0],[4.0,4.0]]],
                        [[[5.0,5.0],[6.0,6.0]],[[7.0,7.0],[8.0,8.0]]]])  # 4维张量
print(tensor4)
print(tensor4.dim())
tensor([[[[1., 1.],
          [2., 2.]],

         [[3., 3.],
          [4., 4.]]],


        [[[5., 5.],
          [6., 6.]],

         [[7., 7.],
          [8., 8.]]]])
4

三.pytorch张量的尺寸

在pytorch中,可以通过a.shape或者a.size()查看张量在每一维度的长度。

可以通过a.view来改变张量的尺寸,还可以通过a.reshape方法来改变张量尺寸。

1.查看张量每一维的长度

1.1 标量
scalar = torch.tensor(True) #
print(scalar.size())
print(scalar.shape)
torch.Size([])
torch.Size([])
1.2 一维张量
vector = torch.tensor([1.0,2.0,3.0,4.0])
print(vector.size())
print(vector.shape)
torch.Size([4])
torch.Size([4])
1.3 矩阵(二维张量)
matrix = torch.tensor([[1.0,2.0],[3.0,4.0]])
print(matrix.size())
torch.Size([2, 2])

2.改变张量的尺寸

2.1使用view方法来改变张量的尺寸
# 使用view可以改变张量尺寸

vector = torch.arange(0,12)
print(vector)
print(vector.shape)

matrix34 = vector.view(3,4)
print(matrix34)
print(matrix34.shape)

matrix43 = vector.view(4,-1) #-1表示该位置长度由程序自动推断
print(matrix43)
print(matrix43.shape)
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
torch.Size([12])
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
torch.Size([3, 4])
tensor([[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]])
torch.Size([4, 3])
2.2使用reshape方法来改变张量的尺寸(reshape更常用)
# 有些操作会让张量存储结构扭曲,直接使用view会失败,可以用reshape方法

matrix26 = torch.arange(0,12).view(2,6)
print(matrix26)
print(matrix26.shape)

# 转置操作让张量存储结构扭曲
matrix62 = matrix26.t()
print(matrix62.is_contiguous())


# 直接使用view方法会失败,可以使用reshape方法
#matrix34 = matrix62.view(3,4) #error!
matrix34 = matrix62.reshape(3,4) #等价于matrix34 = matrix62.contiguous().view(3,4)
print(matrix34)
tensor([[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11]])
torch.Size([2, 6])
False
tensor([[ 0,  6,  1,  7],
        [ 2,  8,  3,  9],
        [ 4, 10,  5, 11]])

四、张量与numpy.array

可以用numpy方法从Tensor得到numpy数组,也可以用torch.from_numpy从numpy数组得到Tensor。

这两种方法关联的Tensor和numpy数组是共享数据内存的。如果改变其中一个,另外一个的值也会发生改变。

如果有需要,可以用张量的clone方法拷贝张量,中断这种关联。

此外,还可以使用item方法从标量张量得到对应的Python数值;使用tolist方法从张量得到对应的Python数值列表

1.torch.from_numpy函数从numpy数组得到Tensor

import numpy as np
import torch 

#torch.from_numpy函数从numpy数组得到Tensor

arr = np.zeros(3)
tensor = torch.from_numpy(arr)
print("before add 1:")
print(arr)
print(tensor)

print("\nafter add 1:")
np.add(arr,1, out = arr) #给 arr增加1,tensor也随之改变
print(arr)
print(tensor)
before add 1:
[0. 0. 0.]
tensor([0., 0., 0.], dtype=torch.float64)

after add 1:
[1. 1. 1.]
tensor([1., 1., 1.], dtype=torch.float64)

2.numpy方法从Tensor得到numpy数组

# numpy方法从Tensor得到numpy数组

tensor = torch.zeros(3)
arr = tensor.numpy()
print("before add 1:")
print(tensor)
print(arr)

print("\nafter add 1:")

#使用带下划线的方法表示计算结果会返回给调用 张量
tensor.add_(1) #给 tensor增加1,arr也随之改变 
#或: torch.add(tensor,1,out = tensor)
print(tensor)
print(arr)
before add 1:
tensor([0., 0., 0.])
[0. 0. 0.]

after add 1:
tensor([1., 1., 1.])
[1. 1. 1.]

3.用clone() 方法拷贝张量,中断这种关联

# 可以用clone() 方法拷贝张量,中断这种关联

tensor = torch.zeros(3)

#使用clone方法拷贝张量, 拷贝后的张量和原始张量内存独立
arr = tensor.clone().numpy() # 也可以使用tensor.data.numpy()
print("before add 1:")
print(tensor)
print(arr)

print("\nafter add 1:")

#使用 带下划线的方法表示计算结果会返回给调用 张量
tensor.add_(1) #给 tensor增加1,arr不再随之改变
print(tensor)
print(arr)
before add 1:
tensor([0., 0., 0.])
[0. 0. 0.]

after add 1:
tensor([1., 1., 1.])
[0. 0. 0.]

4.item方法和tolist方法可以将张量转换成Python数值和数值列表

# item方法和tolist方法可以将张量转换成Python数值和数值列表
scalar = torch.tensor(1.0)
s = scalar.item()
print(s)
print(type(s))

tensor = torch.rand(2,2)
t = tensor.tolist()
print(t)
print(type(t))
1.0
<class 'float'>
[[0.8211846351623535, 0.20020723342895508], [0.011571824550628662, 0.2906131148338318]]
<class 'list'>

更多技术欢迎加入交流:320297153

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值