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

sparse.py

  super(Embedding, self).__init__()

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

 self.weight = Parameter(torch.Tensor(num_embeddings, embedding_dim))
Parameter跳转
 class Parameter(Variable):
"""A kind of Variable that is to be considered a module parameter. Parameters are :class:`~torch.autograd.Variable` subclasses, that have a
very special property when used with :class:`Module` s - when they're
assigned as Module attributes they are automatically added to the list of
its parameters, and will appear e.g. in :meth:`~Module.parameters` iterator.
Assigning a Variable doesn't have such effect. This is because one might
want to cache some temporary state, like last hidden state of the RNN, in
the model. If there was no such class as :class:`Parameter`, these
temporaries would get registered too. Another difference is that parameters can't be volatile and that they
require gradient by default. Arguments:
data (Tensor): parameter tensor.
requires_grad (bool, optional): if the parameter requires gradient. See
:ref:`excluding-subgraphs` for more details.
"""
def __new__(cls, data=None, requires_grad=True):
return super(Parameter, cls).__new__(cls, data, requires_grad=requires_grad) def __repr__(self):
return 'Parameter containing:' + self.data.__repr__()
Parameter类中,data不是self.data来的,所以是父类的。只有在_init_()中self.data的才能追加进去,若在其他函数中,跳转到父类中,则是父类的data
24,25行函数,是实现一个子类对父类包装的功能。 __init__ 、__new__、__call__区分:
 class O(object):
def __init__(self, *args, **kwargs):
print "init"
super(O, self).__init__(*args, **kwargs) def __new__(cls, *args, **kwargs):
print "new", cls
return super(O, cls).__new__(cls, *args, **kwargs) def __call__(self, *args, **kwargs):
print "call" oo = O()
print "________"
oo()

结果如下:

1 new
2 init
3 ________
4 call

conv.py

 class Conv2d(_ConvNd):
r"""Applies a 2D convolution over an input signal composed of several input
planes.
""" def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True):
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(Conv2d, self).__init__(
in_channels, out_channels, kernel_size, stride, padding, dilation,
False, _pair(0), groups, bias) def forward(self, input):
return F.conv2d(input, self.weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)

_pair()跳转到utils.py

 def _ntuple(n):
def parse(x):
if isinstance(x, collections.Iterable):
return x
return tuple(repeat(x, n))
return parse _single = _ntuple(1)
_pair = _ntuple(2)
_triple = _ntuple(3)
_quadruple = _ntuple(4)

这是一个函数式编程的写法,涉及函数嵌套。举例如下:

 def two_dim(y):
def one_dim(x):
return x*x + y
return one_dim one_dim_plus_one = two_dim(1) print(one_dim_plus_one) # 对象地址 <function two_dim.<locals>.one_dim at 0x0000012F6DBFCB70>
print(one_dim_plus_one(2)) #
print(one_dim_plus_one(3)) # # f = x*x+y
# g1 = f(x,1)
f = lambda x,y:x*x+y
g1 = lambda x:f(x,1) # x*x+1 print(g1) # f(x,1)的地址?
print(g1(3)) #

1. repeat(x, n)跳转之后只有_init_()  pass,这是pytorch框架中,是ide生成的临时文件,由C语言实现的标准库内置函数或是外部接口。

2. tuple([iterable])
什么是可迭代对象?列表、字符串。。。
 if isinstance(x, collections.Iterable):
return x
return tuple(repeat(x, n))
 x = 'hello'
print(_quadruple(x)) # 'hello'是可迭代对象,输出'hello' x = 2 # 2不是可迭代对象,输出(2,2,2,2)
print(_quadruple(x))

3. isinstance()函数是内置函数(内置函数不用导入就可以使用!那len()呢?)

命令行help查看isinstance函数

 isinstance(obj, class_or_tuple, /)

内置函数表如下:

_xxx_()是标准库函数

各种函数注意区分。

 a = Notebook()
isinstance(a, Notebook) # True class Test(Notebook):pass
issubclass(Test, Notebook) # True

4.  F.conv2d

 def forward(self, input):
return F.conv2d(input, self.weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)

conv2d跳转到functional.py(from .. import functional as F)中conv2d

functional.py

 # Convolutions
ConvNd = torch._C._functions.ConvNd

def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1,
groups=1):
"""Applies a 2D convolution over an input image composed of several input
planes. See(参考) :class:`~torch.nn.Conv2d` for details and output shape.
"""
f = ConvNd(_pair(stride), _pair(padding), _pair(dilation), False,
_pair(0), groups, torch.backends.cudnn.benchmark, torch.backends.cudnn.enabled)
return f(input, weight, bias)

Conv2d是对conv2d包装。

 # AttributeError: 'Child' object has no attribute 'data'
class Parent:
def __init__(self):
self.data =12 class Child(Parent):
def __init__(self):
pass
super().__init__() a = Child()
print(a.data) #
class Parent:
def __init__(self):
self.data =12 class Child(Parent):
def __init__(self): super().__init__() a = Child()
print(a.data) #
class Parent:
def __init__(self):
self.data =12 class Child(Parent):
def __init__(self):
self.data = 25
super().__init__() a = Child()
print(a.data) #
class Parent:
def __init__(self):
self.data =12 class Child(Parent):
def __init__(self): super().__init__()
self.data = 25 a = Child()
print(a.data)

二、面向对象编程python3

1. 列表生成式

 def search(self, filter):
return [note for note in self.notes if note.match(filter)]

等价于

 def search(self, filter):
temp = []
for note in self.notes:
if note.match(filter):
temp.append(note)
    return temp

列表推导式目标是生成临时列表,举例如下:

 f = [x for if for if for for if]
# 等价于
temp_list = []
for st:
if st:
...
if:
temp_list.append(x)
f = temp_list #
f = []
for st:
if st:
...
if:
f.append(x) # x*y for x in range(1,10) for y in range(1,10)
a = []
for x in range(1,10):
for y in range(1,10):
a.append(x*y)

2. global

 var = 13

 def test():
global var
var = 12
print(var) # print(var)
var = 25
test()

书上部分未完

												

PyTorch框架+Python 3面向对象编程学习笔记的更多相关文章

  1. Python之面向对象编程学习

    不知不觉,学到了python的面向对象编程思想.今天我们来讨论下面向对象编程的思想. 顾名思义,面向对象,就是面向于对象,这里所说的对象不是你现实生活中你的女朋友,你的老婆,你的爱人,在编程的世界里面 ...

  2. JavaScript面向对象编程学习笔记

    1  Javascript 面向对象编程 所谓"构造函数",其实就是一个普通函数,但是内部使用了this变量.对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例 ...

  3. php面向对象编程--学习笔记

    1.声明一个类 在php中使用class关键字创建一个新类,类包括属性与方法.语法格式如下: <?php class类名{ 属性: 方法: } ?> 2.创建一个实例对象 创建对象的过程称 ...

  4. python面向对象编程学习

    python面向对象编程 基本概念理解 面向对象编程--Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作 ...

  5. 并发编程学习笔记(15)----Executor框架的使用

    Executor执行已提交的 Runnable 任务的对象.此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节.调度等)分离开来的方法.通常使用 Executor 而不是显式地创建 ...

  6. 并发编程学习笔记(12)----Fork/Join框架

    1. Fork/Join 的概念 Fork指的是将系统进程分成多个执行分支(线程),Join即是等待,当fork()方法创建了多个线程之后,需要等待这些分支执行完毕之后,才能得到最终的结果,因此joi ...

  7. Python:面向对象编程3 定制类(有更新)

    Python:面向对象编程3  定制类(有更新) ⚠️本文主要内容为对Data model相关知识点的提取学习记录.(内容来自文档和部分网页教程案例) ⚠️:这个连接指向<流畅的python&g ...

  8. 并发编程学习笔记(6)----公平锁和ReentrantReadWriteLock使用及原理

    (一)公平锁 1.什么是公平锁? 公平锁指的是在某个线程释放锁之后,等待的线程获取锁的策略是以请求获取锁的时间为标准的,即使先请求获取锁的线程先拿到锁. 2.在java中的实现? 在java的并发包中 ...

  9. 并发编程学习笔记(5)----AbstractQueuedSynchronizer(AQS)原理及使用

    (一)什么是AQS? 阅读java文档可以知道,AbstractQueuedSynchronizer是实现依赖于先进先出 (FIFO) 等待队列的阻塞锁和相关同步器(信号量.事件,等等)提供一个框架, ...

随机推荐

  1. jquery中arrt()和prop()的区别

    在jQuery中,attr()函数和prop()函数都用于设置或获取指定的属性,它们的参数和用法也几乎完全相同. 但不得不说的是,这两个函数的用处却并不相同.下面我们来详细介绍这两个函数之间的区别. ...

  2. HDU 5025 Saving Tang Monk(状态转移, 广搜)

    #include<bits/stdc++.h> using namespace std; ; ; char G[maxN][maxN], snake[maxN][maxN]; ]; int ...

  3. Mysql中的联合索引、前缀索引、覆盖索引

    索引 索引是一种特殊的文件,它们包含着对数据表里所有记录的引用指针.更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度. 联合索引 又名复合索引,由两个或多个列的索引.它规定了mys ...

  4. P2598 [ZJOI2009]狼和羊的故事(最小割)

    P2598 [ZJOI2009]狼和羊的故事 题目描述 “狼爱上羊啊爱的疯狂,谁让他们真爱了一场:狼爱上羊啊并不荒唐,他们说有爱就有方向......” Orez听到这首歌,心想:狼和羊如此和谐,为什么 ...

  5. Python虚拟机之if控制流(一)

    Python虚拟机中的if控制流 在所有的编程语言中,if控制流是最简单也是最常用的控制流语句.下面,我们来分析一下在Python虚拟机中对if控制流的实现 # cat demo.py a = 1 i ...

  6. html-body相关标签

    一 字体标签   字体标签包含:h1~h6.<font>.<u>.<b>.<strong><em>.<sup>.<sub& ...

  7. Oracle 表空间的日常维护与管理

    目录 Oracle 表空间的日常维护与管理 1.创建数据表空间 2.创建临时表空间 3.创建 UNDO 表空间 4.表空间的扩展与修改大小 5.表空间重命名 6.表空间的删除 7.更改表空间的读写模式 ...

  8. 理解Linux虚拟文件系统VFS

    当前,除了linux标准的文件系统Ext2/Ext3/Ext4外,还有很多种文件系统,比如reiserfs, xfs, Windows的vfat NTFS,网络文件系统nfs 以及flash 文件系统 ...

  9. 2018天梯赛第一次训练题解和ac代码

    随着评讲的进行代码和题解会逐步放上来 2018天梯赛第一次训练 1001 : 进制转换 Time Limit(Common/Java):1000MS/10000MS     Memory Limit: ...

  10. tcpdump 进行抓包

    tcpdump 进行抓包是怎么回事? tcp抓包是怎么搞的?