Pytorch入门
张量
新建张量
- 1.生成一个空张量torch.empty
import torch
x = torch.empty(5,3)
print(x)
- 2.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor返回一个张量,该张量由间隔上均匀分布的随机数填充:math:
[0,1)
import torch
x = torch.rand(2, 3)
print(x)
- 3.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor返回一个张量,该张量由均值为“0”、方差为“1”的正态分布中的随机数填充(也称为标准正态分布)
import torch
x = torch.randn(2, 3)
print(x)
- 4.normal(mean, std, *, generator=None, out=None) -> Tensor给定平均值和标准差;返回对应
**
正太分布**
数值
import torch
x = torch.normal(2, 3, size=(1, 4))
print(x)
- linspace(…)
linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor在start和end之间等距的返回数据
import torch
x = torch.linspace(3, 10, steps=5)
print(x)
tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000])
- **torch.zeros(2, 3)**生成一个全零的张量
import torch
x = torch.zeros(2, 3)
print(x)
tensor([[0., 0., 0.],
[0., 0., 0.]])
- **torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])**已知矩阵转换为张量
x = torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
print(x)
tensor([[0.1000, 1.2000],
[2.2000, 3.1000],
[4.9000, 5.2000]])
- 生成一个同样维度的矩阵
import torch
import numpy as np
x = torch.ones(5,5, dtype=torch.double)
print(x)
x = torch.randn_like(x,dtype=torch.float)
print(x)
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.2423, 1.7955, -0.5171, 1.1406, -0.5407],
[-1.1997, 0.1341, -1.2628, -1.4078, -0.3429],
[ 1.1838, 0.4697, 0.2860, -0.0708, 0.2232],
[-0.0636, -0.1558, -0.3082, -0.2701, -0.5039],
[ 0.9021, -1.5196, -0.8247, -1.4582, 0.8148]])
- 获取张量的形状print(x.size())
print(x.size())
torch.Size([5, 5])
张量运算
- 加法
y = torch.rand(5,5)
# 加法1
print(x + y)
#加法2
print(torch.add(x,y))
# 加法 3
y.add_(x)
print(y)
tensor([[-0.5748, 0.5915, -0.1207, 0.9979, -0.0416],
[ 1.1396, 0.4685, 0.9498, 1.1800, -2.0215],
[ 0.3359, -1.4478, -1.2943, 0.4292, 0.1471],
[-0.3918, 0.5140, -1.2918, 0.4770, -0.1626],
[ 0.4617, 2.1801, 0.1918, 0.0635, 2.1010]])
tensor([[-0.5748, 0.5915, -0.1207, 0.9979, -0.0416],
[ 1.1396, 0.4685, 0.9498, 1.1800, -2.0215],
[ 0.3359, -1.4478, -1.2943, 0.4292, 0.1471],
[-0.3918, 0.5140, -1.2918, 0.4770, -0.1626],
[ 0.4617, 2.1801, 0.1918, 0.0635, 2.1010]])
tensor([[-0.5748, 0.5915, -0.1207, 0.9979, -0.0416],
[ 1.1396, 0.4685, 0.9498, 1.1800, -2.0215],
[ 0.3359, -1.4478, -1.2943, 0.4292, 0.1471],
[-0.3918, 0.5140, -1.2918, 0.4770, -0.1626],
[ 0.4617, 2.1801, 0.1918, 0.0635, 2.1010]])
- 指定输出到某一个参数
result = torch.empty(5,3)
torch.add(x,y,out = result)
print(result)
print(x)
print(x[:, 1])
tensor([[-0.9804, 0.1685, 0.8569, 2.0596, 0.2225],
[ 1.0814, 1.4838, 0.5020, 1.5157, 0.8952],
[-0.3903, 1.9247, 0.8741, 1.9728, 0.2694],
[ 1.1786, -0.7924, -0.8760, 0.3188, 1.7267],
[ 1.6438, 1.4482, 0.7289, 0.9638, 0.8927]])
tensor([[ 0.2748, -0.0774, -1.2880, -0.0365, 0.8686],
[ 0.1119, 0.8125, 1.2119, 0.5379, -0.2646],
[-0.1414, 0.8118, -1.0719, -0.5585, 0.0922],
[ 0.1249, 0.5992, -0.7017, 0.0810, -0.2659],
[-0.6018, -0.3716, 2.8113, 0.7393, -0.6450]])
tensor([-0.0774, 0.8125, 0.8118, 0.5992, -0.3716])
- 改变张量的维度
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 4) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([4, 4])
张量的转换
在用CPU的时候numpy和pytorch共用物理内存
- 张量和numpy之间的转换
a = torch.ones(5)
print(a)
"""
tensor([1., 1., 1., 1., 1.])
"""
b = a.numpy()
print(b)
"""
[1. 1. 1. 1. 1.]
"""
a.add_(1)
print(a)
print(b)
"""
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
"""
- numpy转pytorch
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
"""
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
"""
- GPU下数据转换
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
"""
tensor([-0.4743], device='cuda:0')
tensor([-0.4743], dtype=torch.float64)
"""
Transfrom的初步使用
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
#图片转换为PIL格式
writer = SummaryWriter("logs")
img = Image.open("image/648.jpg")
print(img)
#用tensorboard显示 totensor
trans_totensor = transforms.ToTensor()
img_temsor = trans_totensor(img)
writer.add_image("Totensor", img_temsor)
#Normalize
#output[channel] = (input[channel] - mean[channel]) / std[channel]
print(img_temsor[0][0][1])#0层0行0列
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
img_norm = trans_norm(img_temsor)
print(img_norm[0][0][1])
writer.add_image("Normalize", img_norm)
#resize
print(img.size)
#img PIL->resize->img_resize PIL
trans_resize = transforms.Resize((512, 512))
#img resize PIL-> totensor->img_resize tensor
img_resize = trans_resize(img)
#由于返回数据是PIL图像,需要转换为tensor才能进行tensorboard显示
img_resize = trans_totensor(img_resize)
writer.add_image("Resize", img_resize, 0)
#Compose-resize-2
trans_resize_2 = transforms.Resize(512)
#PTL->PIL->tensor
trans_compose = transforms.Compose([trans_resize_2, trans_totensor])
img_resize_2 = trans_compose(img)
writer.add_image("Resize", img_resize_2, 1)
#RandomCrop
trans_random = transforms.RandomCrop((255, 100))#随机裁剪
trans_cmpose_2 = transforms.Compose([trans_random, trans_totensor])
for i in range(10):
img_crop = trans_cmpose_2(img)
writer.add_image("RandomCrop", img_crop, i)
writer.close()