注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
一、基本概念类
1、与numpy有关
1、tensor与numpy转换
PS:转换后的tensor与numpy指向同一地址,所以,对一方的值改变另一方也随之改变
(1)tensor初始化,与numpy的使用方法相同
a = torch.ones(5)
print(a)
输出
tensor([1., 1., 1., 1., 1.])
(2)tensor to numpy
b = a.numpy()
print(b)
输出
[1. 1. 1. 1. 1.]
a.add_(1)
print(a) # tensor([2., 2., 2., 2., 2.])
(3)numpy to tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
c = torch.add
print(a)
print(b)
输出
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
除chartensor外所有tensor都可以转换为numpy
2、ToTensor:
convert a PIL image to tensor (H,W,C) in range [0,255] to a torch.Tensor(C,H,W) in the range [0.0,1.0]
tensor = transforms.ToTensor(image)
注意:当然这个图像可以是Image读取的;也可以使用opencv读取。而后者需要将读取的图像颜色通道需要从BGR转换为RGB格式。不知道为什么,虽然使用的效果相近,但两则的转换结果并不是完全一样的。
3、维度扩充
大多数模型的输入维度都是(B,C,W,H),但我们使用单张图片测试模型效果时,只有(C,W,H)三个通道的数据,此时,则需要扩充数据维度,代码如下:
"""
src-(C,W,H)
des-(B,C,W,H)
"""
des= Variable(torch.unsqueeze(src, dim=0).float(), requires_grad=False)
|