view()
类似reshape
如果是torch.view(参数a,-1),则表示在参数b未知,参数a已知的情况下自动补齐列向量长度,在这个例子中a=2,tt3总共由6个元素,则b=6/2=3。
>>> import torch
>>> tt1=torch.tensor([-0.3623, -0.6115, 0.7283, 0.4699, 2.3261, 0.1599])
>>> result=tt1.view(3,2)
>>> result
tensor([[-0.3623, -0.6115],
[ 0.7283, 0.4699],
[ 2.3261, 0.1599]])
squeeze() unsqueeze()
b = torch.arange(0,6) #默认步长为1
b.view(2,3)
b.unsqueeze(1) #维度变成(2,1,3)
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # ([100]) -> ([100,1])
只有维度为1的时候才能去掉
# c的维度是(1,2,3)
c.squeeze(-3) <==> c.squeeze(0) 去掉第一维
c.squeeze(-2) 没有变化
torch.linspace() torch.arange()
线性间距向量,生成等差数列
arange()类似于内置函数range(),通过指定开始值、终值和步长创建表示等差数列的一维数组,注意得到的结果数组不包含终值。
linspace()通过指定开始值、终值和元素个数创建表示等差数列的一维数组,可以通过endpoint参数指定是否包含终值,默认值为True,即包含终值。
a = torch.arange(0, 10, 2) # 间隔为2, 不包含终值
b = torch.linspace(0, 10, 2) # 包含2个数, 默认包含终值(endpoint)
print(a)
print(a.size())
print(b)
print(b.size())
tensor([0, 2, 4, 6, 8])
torch.Size([5])
tensor([ 0., 10.])
torch.Size([2])
torch.save()
可以保存模型或只保存模型参数
# 2 ways to save the net
torch.save(net1, 'net.pkl') # save entire net
net2 = torch.load('net.pkl')
torch.save(net1.state_dict(), 'net_params.pkl') # save only the parameters
net3.load_state_dict(torch.load('net_params.pkl')) # 需要先构建net3的框架
enumerate()
该函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
a = [[1, 2], [3, 4], [5, 6]]
for num, p in enumerate(a):
print(str(num), end=' ')
print(p)
0 [1, 2]
1 [3, 4]
2 [5, 6]
season = ['spring', 'summmer', 'fall', 'winter']
print(list(enumerate(season)))
[(0, 'spring'), (1, 'summmer'), (2, 'fall'), (3, 'winter')]
zip()
该函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(*zipped)) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
# 用迭代器访问
temp = zip(num, season)
d = zip(*temp)
it = iter(d)
for i in it:
print(i)
(1, 2, 3, 4)
('spring', 'summmer', 'fall', 'winter')
# 如果直接打印d,会显示d为<zip object at 0x00000156AA0F6048>
向列表末尾插入元素
num = [i for i in range(10)]
a = [7, 7, 7]
num[10:10] = a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 7, 7]
torch.stack()
transforms.ToTensor()
(1) transforms.ToTensor() 将numpy的ndarray或PIL.Image读的图片转换成形状为(C,H, W)的Tensor格式,且/255归一化到[0,1.0]之间
(2)通道的具体顺序与cv2读的还是PIL.Image读的图片有关系
cv2:(B,G,R)
PIL.Image:(R, G, B)
import torch
import cv2
from PIL import Image
from torchvision import transforms
image = cv2.imread('myimage.jpg') # numpy数组格式(H,W,C=3),通道顺序(B,G,R)
image2 = Image.open('myimage.jpg') # PIL的JpegImageFile格式(size=(W,H))
print(image.shape) # (H,W,3)
print(image2.size) # (W,H)
tran = transforms.ToTensor() # 将numpy数组或PIL.Image读的图片转换成(C,H, W)的Tensor格式且/255归一化到[0,1.0]之间
img_tensor = tran(image)
img2_tensor = tran(image2)
print(img_tensor.size()) # (C,H, W), 通道顺序(B,G,R)
print(img2_tensor.size()) # (C,H, W), 通道顺序(R,G,B)
输出结果 :
实际转换流程如下: