"""
A Simple PyTorch Tutorial_1
"""# import package 导入包import torch
import numpy as np
# creat an empty 5x3 tensor 创建一个5x3的空张量
x = torch.empty(5,3)print(x)# creat a random tensor
x = torch.rand(5,3)print(x)# creat a zero tensor ,the type is long
x = torch.zeros(5,3, dtype=torch.long)# creat tensors from array
x = torch.tensor([5.5,3])# creat a 5x3 tensor, the type is double
x = torch.ones(5,3, dtype=torch.double)# creat a new tensor of the same dimension from an existing tensor and redefine the type as float
x = torch.randn_like(x, dtype=torch.float)# print a tensor's dimensionprint(x.size())# add two tensors
y = torch.rand(5,3)print(x + y)# take the first column of the tensorprint(x[:,1])# resize a 4x4 tensor into a one-dimensional tensor
x = torch.randn(4,4)
y = x.view(16)print(x.size(), y.size())# get the numbers from the tensor# only one element tensors can be converted to Python scalars
x = torch.randn(1)print(x)print(x.item())# change the tensor to numpy
a = torch.ones(5)print(a)
b = a.numpy()print(b)# change numpy to tensor
a = np.ones(5)
b = torch.from_numpy(a)print(a)print(b)# do whatever you want on tensor
y = x +2print(y)print(y.grad_fn)# do something on y
z = y * y *3
out = z.mean()print(z)print(out)# Back propagate out
out.backward()# print gradiant d(out)/dxprint(x.grad)# out=0.25*Σ3(x+2)^2# creat a tensor caculation (y=x*2^n)
x = torch.randn(3, requires_grad=True)
y = x *2while y.data.norm()<1000:
y = y *2print(y)# caculate the gradient of v = [0.1, 1.0, 0.0001]
v = torch.tensor([0.1,1.0,0.0001], dtype=torch.float)
y.backward(v)print(x.grad)