专栏名称: 数据派THU
本订阅号是“THU数据派”的姊妹账号,致力于传播大数据价值、培养数据思维。
目录
相关文章推荐
数局  ·  MarketUP&百格活动:2025年B2B ... ·  15 小时前  
数局  ·  解数咨询:2024年保健品行业复盘 ·  15 小时前  
大数据文摘  ·  Andrej Karpathy ... ·  4 天前  
51好读  ›  专栏  ›  数据派THU

手把手教你由TensorFlow上手PyTorch(附代码)

数据派THU  · 公众号  · 大数据  · 2017-10-01 19:00

正文

请到「今天看啥」查看全文



你可以比较一下 while 循环语句的下两种定义——第一个是 TensorFlow 中,第二个是 PyTorch 中:


  1. import tensorflow as tf

  2. first_counter = tf.constant(0)

  3. second_counter = tf.constant(10)

  4. some_value = tf.Variable(15)

  5. # condition should handle all args:

  6. def cond(first_counter, second_counter, *args):

  7.    return first_counter < second_counter

  8. def body(first_counter, second_counter, some_value):

  9.    first_counter = tf.add(first_counter, 2)

  10.    second_counter = tf.add(second_counter, 1)

  11.    return first_counter, second_counter, some_value

  12. c1, c2, val = tf.while_loop(

  13.    cond, body, [first_counter, second_counter, some_value])

  14. with tf.Session() as sess:

  15.    sess.run(tf.global_variables_initializer())

  16.    counter_1_res, counter_2_res = sess.run([c1, c2])


  1. import torch

  2. first_counter = torch.Tensor([0])

  3. second_counter = torch.Tensor([10])

  4. some_value = torch.Tensor(15)

  5. while (first_counter < second_counter)[0]:

  6.    first_counter += 2

  7.    second_counter += 1



看起来第二种方法比第一个简单多了,你觉得呢?

模型定义


现在我们看到,想在 PyTorch 中创建 if/else/while 复杂语句非常容易。不过让我们先回到常见模型中,PyTorch 提供了非常类似于 Keras 的、即开即用的层构造函数:


神经网络包(nn)定义了一系列的模块,它可以粗略地等价于神经网络的层。模块接收输入变量并计算输出变量,但也可以保存内部状态,例如包含可学习参数的变量。nn 包还定义了一组在训练神经网络时常用的损失函数。


  1. from collections import OrderedDict

  2. import torch.nn as nn

  3. # Example of using Sequential

  4. model = nn.Sequential(

  5.    nn.Conv2d(1, 20, 5),

  6.    nn.ReLU(),

  7.    nn.Conv2d(20, 64, 5),

  8.    nn.ReLU()

  9. )

  10. # Example of using Sequential with OrderedDict

  11. model = nn.Sequential(OrderedDict([

  12.    ('conv1', nn.Conv2d(1, 20, 5)),

  13.    ('relu1', nn.ReLU()),

  14.    ('conv2', nn.Conv2d(20, 64, 5)),

  15.    ('relu2', nn.ReLU())

  16. ]))

  17. output = model(some_input)



如果你想要构建复杂的模型,我们可以将 nn.Module 类子类化。当然,这两种方式也可以互相结合。


  1. from torch import nn

  2. class Model(nn.Module):

  3.    def __init__(self):

  4.        super().__init__()

  5.        self.feature_extractor = nn.Sequential(

  6.            nn.Conv2d(3, 12, kernel_size=3, padding=1, stride=1),

  7.            nn.Conv2d(12, 24, kernel_size=3, padding=1, stride=1),

  8.        )

  9.        self.second_extractor = nn.Conv2d(

  10.            24, 36, kernel_size=3, padding=1, stride=1)

  11.    def forward(self, x):

  12.        x = self.feature_extractor(x)

  13.        x = self.second_extractor(x)

  14.        # note that we may call same layer twice or mode

  15.        x = self.second_extractor(x)

  16.        return x



在__init__方法中,我们需要定义之后需要使用的所有层。在正向方法中,我们需要提出如何使用已经定义的层的步骤。而在反向传播上,和往常一样,计算是自动进行的。

自定义层


如果我们想要定义一些非标准反向传播模型要怎么办?这里有一个例子——XNOR 网络:



在这里我们不会深入细节,如果你对它感兴趣,可以参考一下原始论文: https://arxiv.org/abs/1603.05279


与我们问题相关的是反向传播需要权重必须介于-1 到 1 之间。在 PyTorch 中,这可以很容易实现:


  1. import torch

  2. class MyFunction(torch.autograd.Function):

  3.    @staticmethod

  4.    







请到「今天看啥」查看全文