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

sparse.py

  1. super(Embedding, self).__init__()

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

  1. self.weight = Parameter(torch.Tensor(num_embeddings, embedding_dim))
  1. 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 one might
  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=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__()
  1. Parameter类中,data不是self.data来的,所以是父类的。只有在_init_()中self.data的才能追加进去,若在其他函数中,跳转到父类中,则是父类的data
    2425行函数,是实现一个子类对父类包装的功能。
  2.  
  3. __init__ __new____call__区分:
  1. class O(object):
  2. def __init__(self, *args, **kwargs):
  3. print "init"
  4. super(O, self).__init__(*args, **kwargs)
  5.  
  6. def __new__(cls, *args, **kwargs):
  7. print "new", cls
  8. return super(O, cls).__new__(cls, *args, **kwargs)
  9.  
  10. def __call__(self, *args, **kwargs):
  11. print "call"
  12.  
  13. oo = O()
  14. print "________"
  15. oo()

结果如下:

  1. 1 new
  2. 2 init
  3. 3 ________
  4. 4 call

conv.py

  1. class Conv2d(_ConvNd):
  2. r"""Applies a 2D convolution over an input signal composed of several input
  3. planes.
  4. """
  5.  
  6. def __init__(self, in_channels, out_channels, kernel_size, stride=1,
  7. padding=0, dilation=1, groups=1, bias=True):
  8. kernel_size = _pair(kernel_size)
  9. stride = _pair(stride)
  10. padding = _pair(padding)
  11. dilation = _pair(dilation)
  12. super(Conv2d, self).__init__(
  13. in_channels, out_channels, kernel_size, stride, padding, dilation,
  14. False, _pair(0), groups, bias)
  15.  
  16. def forward(self, input):
  17. return F.conv2d(input, self.weight, self.bias, self.stride,
  18. self.padding, self.dilation, self.groups)

_pair()跳转到utils.py

  1. def _ntuple(n):
  2. def parse(x):
  3. if isinstance(x, collections.Iterable):
  4. return x
  5. return tuple(repeat(x, n))
  6. return parse
  7.  
  8. _single = _ntuple(1)
  9. _pair = _ntuple(2)
  10. _triple = _ntuple(3)
  11. _quadruple = _ntuple(4)

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

  1. def two_dim(y):
  2. def one_dim(x):
  3. return x*x + y
  4. return one_dim
  5.  
  6. one_dim_plus_one = two_dim(1)
  7.  
  8. print(one_dim_plus_one) # 对象地址 <function two_dim.<locals>.one_dim at 0x0000012F6DBFCB70>
  9. print(one_dim_plus_one(2)) #
  10. print(one_dim_plus_one(3)) #
  11.  
  12. # f = x*x+y
  13. # g1 = f(x,1)
  14. f = lambda x,y:x*x+y
  15. g1 = lambda x:f(x,1) # x*x+1
  16.  
  17. print(g1) # f(x,1)的地址?
  18. print(g1(3)) #

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

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

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

命令行help查看isinstance函数

  1. isinstance(obj, class_or_tuple, /)

内置函数表如下:

_xxx_()是标准库函数

各种函数注意区分。

  1. a = Notebook()
  2. isinstance(a, Notebook) # True
  3.  
  4. class Test(Notebook):pass
  5. issubclass(Test, Notebook) # True

4.  F.conv2d

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

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

functional.py

  1. # Convolutions
  2. ConvNd = torch._C._functions.ConvNd

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

Conv2d是对conv2d包装。

  1. # AttributeError: 'Child' object has no attribute 'data'
  2. class Parent:
  3. def __init__(self):
  4. self.data =12
  5.  
  6. class Child(Parent):
  7. def __init__(self):
  8. pass
  9. super().__init__()
  10.  
  11. a = Child()
  12. print(a.data)
  13.  
  14. #
  15. class Parent:
  16. def __init__(self):
  17. self.data =12
  18.  
  19. class Child(Parent):
  20. def __init__(self):
  21.  
  22. super().__init__()
  23.  
  24. a = Child()
  25. print(a.data)
  26.  
  27. #
  28. class Parent:
  29. def __init__(self):
  30. self.data =12
  31.  
  32. class Child(Parent):
  33. def __init__(self):
  34. self.data = 25
  35. super().__init__()
  36.  
  37. a = Child()
  38. print(a.data)
  39.  
  40. #
  41. class Parent:
  42. def __init__(self):
  43. self.data =12
  44.  
  45. class Child(Parent):
  46. def __init__(self):
  47.  
  48. super().__init__()
  49. self.data = 25
  50.  
  51. a = Child()
  52. print(a.data)

二、面向对象编程python3

1. 列表生成式

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

等价于

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

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

  1. f = [x for if for if for for if]
  2. # 等价于
  3. temp_list = []
  4. for st:
  5. if st:
  6. ...
  7. if:
  8. temp_list.append(x)
  9. f = temp_list
  10.  
  11. #
  12. f = []
  13. for st:
  14. if st:
  15. ...
  16. if:
  17. f.append(x)
  18.  
  19. # x*y for x in range(1,10) for y in range(1,10)
  20. a = []
  21. for x in range(1,10):
  22. for y in range(1,10):
  23. a.append(x*y)

2. global

  1. var = 13
  2.  
  3. def test():
  4. global var
  5. var = 12
  6. print(var)
  7.  
  8. # print(var)
  9. var = 25
  10. test()

书上部分未完

  1.  

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. Ubuntu 15.04 安装配置 Qt + SQLite3

    序 最近需要在Ubuntu下使用Qt开发项目,选择简单小巧的SQLite数据库,现将安装配置以及简单操作记录如下,以便日后查阅. 安装Qt CMake和Qt Creator是Linux下开发C++程序 ...

  2. vmware esxi 6.0 开启嵌套虚拟化

    环境描述: 已通过vSphere Client创建一个名字为centos7的虚拟机,现在需要打开该虚拟机的嵌套虚拟化功能. 第一步: 开启ESXi Shell 开启vSphere的ssh远程登录服务或 ...

  3. day05 模块以及内置常用模块用法

    内置常用模块详解: 1 time 2 datetime 3 random   4 os 5 sys 6 shutil 7 shelve 8 xml 9 configparser 10 hashlib ...

  4. 程序员必需知道的Mac OS使用技巧

    macos sierra正式版发布了,于是我把我沉寂了一年没有用过了的macbook拿出来玩玩,顺便把一些常用技巧mark. 1.apple store下载软件无响应(经常出现的问题) 解决方法:更改 ...

  5. Linux中 find 常见用法示例

    Linux中find常见用法示例 #find path -option [ -print ] [ -exec -ok command ] {} \; #-print 将查找到的文件输出到标准输出 #- ...

  6. day03_10 注释及简单的用户输入输出

    单行注释# print ("我爱北京天安门") print ("我爱北京天安门") #print ("我爱北京天安门") #print (& ...

  7. [python测试框架学习篇] 分享一个和adb相关的测试框架

    https://testerhome.com/topics/7106   (user: zteandallwinner     password: same to qq ) 264768502 · # ...

  8. Concept with HTTP API && RPC

    RPC=Remote Produce Call 是一种技术的概念名词. HTTP是一种协议,RPC可以通过HTTP来实现,也可以通过Socket自己实现一套协议来实现.所以楼主可以换一个问法,为何RP ...

  9. java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()解决办法

    代码改变世界 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.pre ...

  10. 【Luogu】P2219修筑绿化带(单调队列)

    题目链接 这题各种边界判断恶心死人 就是单调队列在每行求出最小的.能装进A*B方块里的花坛 然后再在刚刚求出的那个东西里面跑一遍竖着的单调队列 然后……边界调了一小时 做完这题我深刻地感觉到我又强了 ...