pytorch基础
程序员文章站
2022-06-26 11:31:07
...
一、Tensor (张量)
import torch
from torch.autograd import Variable
import numpy as np
#tensor 张量
a = torch.Tensor([[2,3],[4,8],[7,9]])
print('a is:{}'.format(a))
print('a size is:{}'.format(a.size()))
a is:tensor([[2., 3.],
[4., 8.],
[7., 9.]])
a size is:torch.Size([3, 2])
#指定想要的类型
b = torch.LongTensor([[2,3],[4,8],[7,9]])
print('b is:{}'.format(b))
b is:tensor([[2, 3],
[4, 8],
[7, 9]])
#全空的tensor
c = torch.zeros((3,2))
print('zero tensor:{}'.format(c))
zero tensor:tensor([[0., 0.],
[0., 0.],
[0., 0.]])
#正态分布作为随机初始值的tensor
d = torch.randn((3,2))
print('normal random is:{}'.format(d))
normal random is:tensor([[-1.1648, 1.0327],
[ 0.9533, 0.3417],
[ 0.4022, -0.7862]])
#用索引取值
a[0,1]=100
print('changed a is:{}'.format(a))
changed a is:tensor([[ 2., 100.],
[ 4., 8.],
[ 7., 9.]])
#和numpy之间转换
np_b = b.numpy()
print('convert to numpy is \n {}'.format(np_b))
e = np.array([[2,3],[4,5]])
torch_e = torch.from_numpy(e)
print('from numpy to torch.Tensor is {}'.format(torch_e))
convert to numpy is
[[2 3]
[4 8]
[7 9]]
from numpy to torch.Tensor is tensor([[2, 3],
[4, 5]])
二、Variable (变量)
#variable变量
#标量求导
x = Variable(torch.Tensor([1]),requires_grad=True)
w = Variable(torch.Tensor([2]),requires_grad=True)
b = Variable(torch.Tensor([3]),requires_grad=True)
y = w*x+b
#这一步即自动求导
y.backward()
print(x.grad)
print(w.grad)
print(b.grad)
tensor([2.])
tensor([1.])
tensor([1.])
#矩阵求导
x = torch.randn(3)
x = Variable(x,requires_grad = True)
y = x*2
print(y)
y.backward(torch.FloatTensor([1,0.1,0.01]))
print(x.grad)
tensor([ 3.3212, -3.4426, -0.1929], grad_fn=<MulBackward0>)
tensor([2.0000, 0.2000, 0.0200])
上一篇: Pytorch基础
下一篇: Pytorch 基础