PyTorch框架+Python 3面向对象编程学习笔记

标签:一个   bfc   mod   函数式编程   标准   包装   benchmark   文件   pad   

一、CNN情感分类中的面向对象部分

sparse.py

1  super(Embedding, self).__init__()

表示需要父类初始化,即要运行父类的_init_(),如果没有这个,则要自定义初始化

1 self.weight = Parameter(torch.Tensor(num_embeddings, embedding_dim))
Parameter跳转
 1 class Parameter(Variable):
 2     """A kind of Variable that is to be considered a module parameter.
 3 
 4     Parameters are :class:`~torch.autograd.Variable` subclasses, that have a
 5     very special property when used with :class:`Module` s - when they‘re
 6     assigned as Module attributes they are automatically added to the list of
 7     its parameters, and will appear e.g. in :meth:`~Module.parameters` iterator.
 8     Assigning a Variable doesn‘t have such effect. This is because> 9     want to cache some temporary state, like last hidden state of the RNN, in
10     the model. If there was no such class as :class:`Parameter`, these
11     temporaries would get registered too.
12 
13     Another difference is that parameters can‘t be volatile and that they
14     require gradient by default.
15 
16     Arguments:
17         data (Tensor): parameter tensor.
18         requires_grad (bool, optional): if the parameter requires gradient. See
19             :ref:`excluding-subgraphs` for more details.
20     """
21     def __new__(cls, data=http://www.mamicode.com/None, requires_grad=True):
22         return super(Parameter, cls).__new__(cls, data, requires_grad=requires_grad)
23 
24     def __repr__(self):
25         return Parameter containing: + self.data.__repr__()
Parameter类中,data不是self.data来的,所以是父类的。只有在_init_()中self.data的才能追加进去,若在其他函数中,跳转到父类中,则是父类的data
24,25行函数,是实现一个子类对父类包装的功能。

__init__ 、__new__、__call__区分:
 1 class O(object):
 2     def __init__

PyTorch框架+Python 3面向对象编程学习笔记

扫一扫手机访问