zoukankan      html  css  js  c++  java
  • 【pytorch】学习笔记(二)- Variable

    【pytorch】学习笔记(二)- Variable

    学习链接自莫烦python

    什么是Variable

    Variable就好像一个篮子,里面装着鸡蛋(Torch 的 Tensor),里面的鸡蛋数不断变化(对应值不断变化)。

    如果用一个 Variable 进行计算, 那返回的也是一个同类型的 Variable

    创建Variable

    import torch
    from torch.autograd import Variable
    
    #创建张量
    tensor=torch.FloatTensor([[1,2],[3,4]])
    # 把张量放到Vaiable中
    variable=Variable(tensor,requires_grad=True)
    
    print(tensor)
    
    print(variable)
    

    Variable计算

    t_out=torch.mean(tensor*tensor)
    v_out=torch.mean(variable*variable)
    print(t_out)
    print(v_out)
    

    结果:

    tensor(7.5000)
    tensor(7.5000, grad_fn=<MeanBackward0>)
    

    tensor与variable的区别

    1.Variable 计算时, 它在背景幕布后面一步步默默地搭建着一个庞大的系统, 叫做计算图, computational graph.
    2.这个图是用来干嘛的? 原来是将所有的计算步骤 (节点) 都连接起来, 最后进行误差反向传递的时候, 一次性将所有 variable 里面的修改幅度 (梯度) 都计算出来, 而 tensor 就没有这个能力啦
    3.v_out = torch.mean(variable*variable) 就是在计算图中添加的一个计算步骤, 计算误差反向传递的时候有他一份功劳

    # 模拟 v_out 的误差反向传递
    v_out.backward()
    # 初始 Variable 的梯度
    print(variable.grad)
    

    获取Variable中的数据

    import torch
    from torch.autograd import Variable
    
    #创建张量
    tensor=torch.FloatTensor([[1,2],[3,4]])
    # 把张量放到Vaiable中
    variable=Variable(tensor,requires_grad=True)
    
    print(variable.data)
    
    print(variable.data.numpy())
    
  • 相关阅读:
    CentOS 7 安装MySQL 5.7
    Introduction to BGP (4)
    Introduction to BGP (3)
    Introduction to BGP (2)
    Introduction to BGP (1)
    Cisco NAT Fundation
    Linux安装Nginx
    GRE协议学习与练习
    Oracle Study Note : Users and Basic Security
    Oracle Study Note : Tablespace and Data Files
  • 原文地址:https://www.cnblogs.com/mengxiaoleng/p/11775956.html
Copyright © 2011-2022 走看看