pytorch基础

一、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])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值