think_deeply

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  • model.named_children() 和 model.named_modules(); model.named_parameters()和model.parameters()的意思:
    • model.named_children()与model.named_modules():
      • 目的:返回网络model下的模块,并返回名称和模块本身
      • 区别:.named_children()返回所有子模块,并返回名称和模块本身;.named_modules()返回所有模块(包括子模块下的所有模块),并返回名称和模块本身。
      • 相同点:两者都是返回模块迭代器,只是前者将子模块作为最小单元返回,后者将每层作为最小单元返回。
      • 例子:代码可参阅:https://blog.csdn.net/watermelon1123/article/details/98036360
    • model.named_parameters()和model.parameters():
      • 目的:返回模型中可以被训练的参数
      • 区别:.named_parameters()返回的参数附带网络层的名称,如某conv层的weight和bias;而.parameters()返回的是model中所有学习的参数
      • 例子:https://blog.csdn.net/u013548568/article/details/84311099
      • import torchvision
        model = torchvision.models.resnet18(True)
        head = 2  # 只显示前2个参数
        print('model.named_parameters():')
        for i,(name, param) in enumerate(model.named_parameters()):
            if i<head:
                print(name, param.size())
        print('=============================')
        print('model.parameters():')
        for j, param in enumerate(model.parameters()):
            if j<head:
                print(param.size())
        
        输出:
        model.named_parameters():
        conv1.weight torch.Size([64, 3, 7, 7])
        bn1.weight torch.Size([64])
        =============================
        model.parameters():
        torch.Size([64, 3, 7, 7])
        torch.Size([64])

         

  • hook: pytorch 可以利用register_forward_hook和register_backward_hook方法将网络的特定模块提取出来,并能够返回相应模块的输入和输出。这两个方法分别用于输出特定模块的features/gradients,为可视化中间层特征提供了帮助。参见:半小时学会Pytorch Hookhttps://zhuanlan.zhihu.com/p/75054200

 

  • Python PIL库的convert作用:转换图像格式
    • RGB的图像,无论格式是jpg,png,bmp,使用Image open()打开都是RGB模式,可以使用save()转换成jpg,png,bmp的任意格式存储。
    • Gray的图像,无论格式是jpg,png,bmp,使用Image open()打开都是L模式,可以使用save()转换成jpg,png,bmp的任意格式存储。
    • 使用Convert可以将图像模式转换成不同的9种模式,包括:“1,L,P,RGB,RGBA,CMYK,YCbCr,I,F”,其中convert(‘L’)就表示转换成灰度图,计算公式为:L = R * 299/1000 + G * 587/1000+ B * 114/1000,更多内容参考:https://blog.csdn.net/icamera0/article/details/50843172
  • python中参数前面*和**的意思:表示可以传入任意个数的参数到python函数中:https://www.cnblogs.com/arkenstone/p/5695161.html

 

  • np.random.seed()是为numpy的随机数生成器初始化一个seed常量。这样在每次生成随机数时都会是相同的,否则都是不同的
    •   例子:
    • import numpy as np
      np.random.seed(4)
      a = np.random.rand(5);a
      [out]: array([0.96702984, 0.54723225, 0.97268436, 0.71481599, 0.69772882])

      
      np.random.seed(4)
      b = np.random.rand(5);b==a
      [out]: array([ True,  True,  True,  True,  True])

      
      c = np.random.rand(5);c,c==a
      [out]: (array([0.2160895 , 0.97627445, 0.00623026, 0.25298236, 0.43479153]),
       array([False, False, False, False, False]))
  • colab改变当前工作路径:%cd ' 你想要的路径'; !pwd 显示当前工作路径
    •   colab 是Ubuntu的云服务器,其中.mount()是挂载的意思,想要读取哪个路径,就得先挂载到哪个路径上。
      from google.colab import drive
      drive.mount('/content/gdrive/',force_remount=True)
      %cd '/content/gdrive/My Drive/ProxNet/burst-cvpr-2019-master/'
      !pwd
      
      [out]: Mounted at /content/gdrive/ /content/gdrive/My Drive/ProxNet/burst-cvpr-2019-master /content/gdrive/My Drive/ProxNet/burst-cvpr-2019-master
  • python 获取当前程序的工作路径:os.getcwd()
  • glob.glob('要搜索的文件的命名方式') 搜索文件
    • 查找文件只用到三个匹配符:"*", "?", "[]"。"*"匹配0个或多个字符;"?"匹配单个字符;"[]"匹配指定范围内的字符,如:[0-9]匹配数字。
      import glob  
        
      #获取指定目录下的所有图片  
      print glob.glob(r"E:\Picture\*\*.jpg")  
        
      #获取上级目录的所有.py文件  
      print glob.glob(r'../*.py') #相对路径 
  •  pytorch保存与加载模型:
    • 保存模型和参数 & 对于的加载模型与参数:
      • torch.save(model, path)     &    model_dict = torch.load(path)
    • 仅保存参数 & 对应的加载参数:
      • torch.save(model.state_dict(), path)    &    model_dict = model.load_state_dict(torch.load(path))
  •  Pytorch中torch.Tensor的构造与相互转换,以及torch.type()和torch.type_as()的用法
  • Pytorch定义了7中CPU张量类型和8种GPU张量类型,CPU→GPU只需加上cuda,如:torch.FloatTensor(3,4)→torch.cuda.FloatTensor(3,4)torch.FloatTensor(2,3)构建一个2*3的Float类型(float32)的张量
  • 注意以下方法产生的Tensor都是随机的,可以使用.fill_(value)使得张量被被赋值为value.
    • torch.DoubleTensor(2,3)构建一个2*3的Double类型(float64)的张量
    • torch.ByteTensor(2,3)构建一个2*3的Byte类型(uint8:无符号整型,全正的)的张量,初始化为0
    • torch.CharTensor(2,3)构建一个2*3的Char类型(int8:有符号整型,有正有负)的张量
    • torch.ShortTensor(2,3)构建一个2*3的Short类型(int16:有符号整型)的张量
    • torch.IntTensor(2,3)构建一个2*3的Int类型(int32:有符号整型)的张量
    • torch.LongTensor(2,3)构建一个2*3的Long类型(int64:有符号整型)的张量
    • 转变张量格式:.***()
    • tensor = torch.Tensor(3,5)
    • tensor = tensor.double() 转变成doule类型
    • tensor = tensor.byte() 
    • tensor = tensor.char()
    • tensor = tensor.short()
    • tensor = tensor.long()  
    • 转变张量格式 .type()
      • tensor = torch.Tensor(3,4)  # tensor.dtype = torch.float32
      • new_tensor = tensor.type(torch.DoubleTensor())    # new_tensor.dtype = torch.float64
    • 转变张量格式:type_as(tensor)
      • a = torch.ByteTensor(3,4)  # a.dtype = torch.uint8
      • b = torch.LongTensor(4,5)      # b.dtype = torch.int64
      • b = b.type_as(a)  # b.dtype = torch.uint8
    • numpy数组转换成torch张量的方法:
      import numpy as np
      import torch
      a = np.random.rand(1,2,3,4).astype(dtype='float32');a.dtype,a.shape
      #(dtype('float32'), (1, 2, 3, 4))
      b = torch.FloatTensor(a);b.dtype,b.shape
      #(torch.float32, torch.Size([1, 2, 3, 4]))
      b.numpy()==a
      #array([[[[ True,  True,  True,  True],
               [ True,  True,  True,  True],
               [ True,  True,  True,  True]],
      
              [[ True,  True,  True,  True],
               [ True,  True,  True,  True],
               [ True,  True,  True,  True]]]])
  • python 中np.transpose()和torch.permute()的用法:
    • 相同:均为转换轴的位置
    • 区别:transpose()用在numpy的数组中;而permute()是用在pytorch的张量上。
  • python中size,shape,len的用法:
        • 首先numpy和pytorch都有size和shape方法,只是调用不同:
        • numpy 数组
          • a = np.random.rand(3,4,2)
          • a.size  # 24,返回数组的所有元素个数
          • a.shape  # (3,4,2)以元组形式返回数组的维度
          • len(a)  # 3, dim=0的值
          pytorch 张量:.size() 和 .shape返回值一样,使用哪一个都可以。
    https://github.com/pytorch/pytorch/issues/5544
      • b = torch.rand(3,4,2)
      • b.size()  # torch.Size([3, 4, 2])
      • b.shape  # torch.Size([3, 4, 2]) 
      • len(b)  # 3, dim=0的值
    • pytorch生成张量的方法
      • a = torch.rand(*sizes, out=None) → Tensor  # 均匀随机分布:[0,1).  1个 * 的意思:1)可以解压列表;2) 可以元组方式输入
        • 所以可以这样生成张量:
        • a = torch.rand(2,3,4,5)
        • a = torch.rand((2,3,4,5))
        • a = torch.rand([2,3,4,5])
        • 都是可以的
      • a = torch.randn(*sizes, out=None) → Tensor  # 标准正态分布:从标准正态分布中随机选取size尺寸的数
      • a = torch.normal(means,std, out=None) → Tensor  # 离散正态分布:其中标准差std是一个张量,包含每个输出的标准差
      • a = torch.linspace(start,end,steps=100,out=None) → Tensor  # 线性间距向量 返回一个1维张量,包含在start和end之间的steps个点。

  • Pytorch张量增加/删除维度1,输出张量类型

    • 在张量后面增加[None]可以在张量第一维度之前增加维度1:

      • a = torch.rand(2,3,4,1).type(torch.CharTensor) 

      • a.shape  #torch.Size([2,3,4,1])

      • a.dtype  # torch.int8

      • b = a[None]

      • b.shape  # torch.Size([1,2,3,4,1])

      • b.dtype  # torch.int8

      • b = b.flatten()   # 转换为1维张量

      • a.size(),a.dtype  # (torch.Size([24]), torch.int8)


 

  • 元组转换成列表:list(seq):https://www.runoob.com/python/python-lists.html
    • list.extend(seq)在列表末尾一次性追加另一个列表的多个值
    • list.pop([indx=-1]),根据索引移除列表中的一个元素,默认为最后一个元素
    • list.remove(obj) 移除列表中某个值的第一个匹配项
    • list中双冒号的用法:
      • python 序列切片:[start:end:step],其中start,end,step都可以省略,当省略start,默认为0,当省略end,默认为最后一个元素,当省略step,默认步长为1,当step=-1,则从后往前数。
  • python中显示图像的方式:
    • import matplotlib.pyplot as plt
    • plt.imshow(a)  # a 是一个numpy数组
    • plt.show()
    使用colab运行.py文件:(使用colab必须拥有Google账号!)
    • 首先将所需要运行的程序全部上传至Google Drive
    • 然后挂载本地存储空间:https://course.fast.ai/start_colab.html(Fast.ai库推荐使用,这个链接的最后教我们如何挂载云端存储器)
    • 然后使用%cd 命令将运行路径设置到.py文件所在的路径
    • 使用!pwd命令查看当前路径
    • 最后使用 %run example.py运行.py文件
  • python读取与显示图片:2种方法:https://www.cnblogs.com/yinxiangnan-charles/p/5928689.html
    • matplotlib.     读入的图片是数组形式,可以使用numpy库处理
      • import matplotlib.plot as plt  # 显示图片
      • import matplotlib.image as image # 读取图片
      • img = image.imread('path.jpg')
      • plt.imshow(img)
      • plt.show()
    • PIL.  读入的图片不是数组形式,需要使用np.array(img)转换成数组再处理
      • import PIL.Image as image
      • img = image.open('path.jpg')
      • img.show()
  • 使用Colab运行.py文件,以及显示图片
    • 运行:使用%run example.py
    • 显示图片:
      • 先在example.py文件内每个显示图片语句后面加上plt.show()
      • 在example.py文件内部:
        • import matplotlib.pyplot as plt
        • plt.imshow(image)
        • plt.show()  # 保证每个要显示图片的语句后面有这句话
      • 在colab notebook中,使用魔法方法和语句:
        • %matplotlib inline
        • %run example.py
      • 即可运行外部example.py文件,也可以在notebook中显示图片。
  • scripy库是python三大常用库之一,还包括:numpy, matplotlib库。scripy库是建立在numpy库数组操作之上的处理库,可以完成常见的数组操作:图像io: imread, imsave, imresize等,傅里叶变换,微分方程求解,线性代数模块等等。
    • from scripy.misc import imread, imresize, imsave
    • import scripy.io 

    


 

  • torch.nn.utils.weight_norm实现权值归一化,torch.nn.utils.weight_norm(module, name='weight', dim=0),在给定的模型module上应用weight_norm方法,返回参数被normalized的模型。它将参数分解成两部分表示:振幅和方向:weight→magnitude+direction
Args:
    module (Module): containing module
    name (str, optional): name of weight parameter
    dim (int, optional): dimension over which to compute the norm

Returns:
    The original module with the weight norm hook
    >>> m = weight_norm(nn.Linear(20, 40), name='weight')
    >>> m
    Linear(in_features=20, out_features=40, bias=True)
    >>> m.weight_g.size()
    torch.Size([40, 1])
    >>> m.weight_v.size()
    torch.Size([40, 20])    

 

 

  • torch.nn.functional.pad(input, pad, model='constant', value=0)
    • 当输入是4D张量时,pad应该一个四元素的(pad_l, pad_r, pad_t, pad_b)
  • numpy.random.standard_normal(size=None)→float / ndarray 生成一个尺寸为size的均值为0,方差为1的标准正态分布
  • pytorch中.fill_(value)的用法:
    • 作用:将张量按指定数值填充
    • 返回:张量
    • 例子:  
a = torch.FloatTensor(1);a
>>>tensor([0.])

a = torch.FloatTensor(1).fill_(1);a
tensor([1.])
  • python 中@staticmethod返回函数的静态方法,该方法不强制传递参数;例子:
    • class c(object):
          @staticmethod
          def f(arg1, arg2,...):
              ...
      class c(object):
          @staticmethod
          def f():
              print('runoob')
      
      c().f();    # 静态方法无需实例化
      cobj = c()
      cobj.f()    # 也可以实例化后调用
      
      runoob
      runoob
  • class torch.nn.Parameter()是variable类的一个子类。当torch.nn.Parameter()和module一起使用时,当parameter被赋值给module时,参数会自动加入到参数列表中,默认requires_grad=True,而variable赋值给module时,不会出现在参数列表中,且默认requires_grad=False
  • pytorch 错误类型:exp_vml_cpu not implemented for 'Long';
    • 是因为数值类型的原因
    • 解决:a  = torch.tensor(2) → a = torch.tensor(2.)

    


 

  • python中assert的作用:断言命令,是在条件为False时,触发异常,执行后面的语句
    • assert expression

      也有下面形式:

    • assert expression [,arguments]:
      
      assert 1>1, '1等于1';
      
      >>> Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      AssertionError: 1等于1

 

  • python 中lmdb数据库:详细介绍参考:https://zhuanlan.zhihu.com/p/70359311
    • lmdb是什么:全称Lighting Memory-Mapping Database。它是存储大型数据集(如ImageNet)的方式之一
    • 数据存储方式:以(key-value)的方式存储的是数据集的指针,所以每个键-值对都是数据集的一个样本
    • 优势:快。因为它存储的是指向键-值对的内存地址的指针。
    • 文件格式:一个文件夹,包括数据文件(data.mdb)+锁文件(lock.mdb)
    • LMDB的基本函数:
      • env = lmdb.open():创建lmdb环境
      • txn = env.begin():建立事务
      • txn.put(key,value):进行插入和修改
      • txn.delete(key):进行删除
      • txn.get(key):进行查询
      • txn.cursor():进行遍历
      • txn.commit():进行提交
  • pytorch中 class torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1, last_epoch=-1)
    • 首先torch.optim.lr_scheduler是pytorch中根据epoch调整学习率的方法
    • milestones是一个函数或者列表,当epoch达到该特定值时,new_lr = lr * gamma
  • python 异常处理:
    • python 提供了两种异常处理功能:1、断言(assert):当条件为False时,执行语句;2、异常处理(try)
    • try:
          预执行的代码
      except someError:
          当上面的代码发生someError异常时,运行except语句体
          someError指示python标准异常https://www.runoob.com/python/python-exceptions.html
      else:
          当try中没有异常发生时,运行这里的语句;
          当try中有异常发生时,且为someError时,运行except的语句,不再运行此处语句
      finally:
          不管是否发生异常,都会执行的语句。
      try:
          with open('./testdir/testTry',mode='w') as f:
              f.write('Another Try')
              print('5555')
      except IOError:
          print('We cant write')
      else:
          print('I am else')
      finally:
          print('I am finally')
      
      
      输出:
      I am try
      I am else
      I am finally

      当我们故意将testTry.txt文件设置成只读模式时,再运行上述语句:

    • try:
          with open('./testdir/testTry',mode='w') as f:
              f.write('Another Try')
              print('5555')
      except IOError:
          print('We cant write')
      else:
          print('I am else')
      finally:
          print('I am finally')
      
      
      输出:
      We cant write
      I am finally
  • pytorch中model.train()和model.eval()的作用:
    • 时机:它们仅在model中存在dropout和batchnorm时能够发挥作用。
    • 作用:当模型中存在dropout和batchnorm时,使用model.train()表示,在训练时,model使用它们;而model.eval()表示,在测试时,不会使用dropout和batchnorm。
    • 建议:model.train()和model.eval()建议在训练和测试时写上,因为现在的网络大多数会使用dropout和batchnorm,以免不写造成不好后果

 


 

  • pytorch 中 detach()的作用:
    • .detach()返回一个新的变量,这个变量永远(never)不会带有.grad属性,当改变其梯度时才会再计算梯度
    • torch.manual_seed(20)
      a = torch.rand((1,100),requires_grad=True);
      line = nn.Linear(100,10,False)
      b = line(a)
      out = b.sigmoid().max()
      out.backward()
      a.requires_grad
      输出:
      True
      
      当
      torch.manual_seed(20)
      a = torch.rand((1,100),requires_grad=True).detach();
      line = nn.Linear(100,10,False)
      b = line(a)
      out = b.sigmoid().max()
      out.backward()
      a.requires_grad
      输出:
      False
  • pytorch中.backward()中retain_graph的用法:
    • 当对某一子图要反复求导时,使用reatain_graph可以使得计算效率更高。  

 


 

  • python 文件与文件夹操作:
    • 改变文件夹工作目录:os.chdir('欲到达的工作目录')
    • 获取当前工作目录:os.getcwd()
    • 获取当前目录下的所有文件和文件夹:os.listdir()
    • 移动文件shutil.move(‘文件路径’,‘目标路径’)
    • 文件重命名:os.rename('文件路径',‘新的文件名’)
    • 数字转换成字符串操作:str(x)
  • 列表与数组的转换:
    • 列表转数组:np.array(list)
    • 数组转列表:array.tolist()

 


 

  • tensorflow中用于深度学习的4-D张量的输入格式:[batch, in_height, in_weight, in_channels]
  • tensorflow中tf.scan的用法:
    • 语法:output = tf.scan(fun, eles, initializer=None);
    • 意义:o(t) = fun(o(t-1), eles(t)), 其中o(0) = initializer,eles(t)是沿着eles的第0维依次迭代产生
    • 例子:
    • with tf.Session() as sess:
          a = tf.constant([[1],[2],[3],[4],[5]],dtype=tf.float32)
          v0 = tf.constant([1,],dtype=tf.float32)
          alphas = tf.constant([.1,],dtype=tf.float32)
          def damped(cur, right):
              return cur * alphas + right
          b = tf.scan(damped, a, initializer=v0)
          # print(sess.run(a))
          print(sess.run(b))
      
      
      输出:
      [[1.1    ]        # v0 = v0+a[0]*alphas 
       [2.11   ]        # v0 = v0+a[1]*alphas
       [3.211  ]
       [4.3211 ]
       [5.43211]]

       


 

  • tensorflow中tf.variable_scope(<scope_name>)和tf.get_variable(<name>,<shape>,<initializer>)的意义与用法:
    • 意义:它们实现“共享变量”的作用
    • 解读:共享变量是什么意思呢?形象的理解:
      • 首先理解变量是可以被赋值的东西。假设小明想从山东济宁欢城镇坐高铁去杭州上学,小李想从山东济宁两城镇坐高铁去杭州上班,他们很有钱,于是打算自己建造一条高铁去杭州,说时迟那时快,他们就把铁路建到了枣庄市,这天他们聊天发现都是在建去往杭州的高铁,于是准备合作,那不如就共同建造一个枣庄到杭州的铁路吧,那么这个枣庄站就是一个变量,可以被共享。
      • 然后理解命名空间。小明去枣庄站有自己的交通工具,小李去枣庄站也有他自己的交通工作,尽管枣庄站是他们共同享用的,但是对他们的意义却是不同的,于是{小明的枣庄站,小李的枣庄站}就是一个命名空间
    • 代码例子:https://docs.pythontab.com/tensorflow/how_tos/variable_scope/
      • 可以使用tf.Variable创建变量,这就相当于小明小李各自建了一条去杭州的高铁,于是有了很多的变量:
      • def my_image_filter(input_images):
            conv1_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
                name="conv1_weights")
            conv1_biases = tf.Variable(tf.zeros([32]), name="conv1_biases")
            conv1 = tf.nn.conv2d(input_images, conv1_weights,
                strides=[1, 1, 1, 1], padding='SAME')
            relu1 = tf.nn.relu(conv1 + conv1_biases)
        
            conv2_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
                name="conv2_weights")
            conv2_biases = tf.Variable(tf.zeros([32]), name="conv2_biases")
            conv2 = tf.nn.conv2d(relu1, conv2_weights,
                strides=[1, 1, 1, 1], padding='SAME')
            return tf.nn.relu(conv2 + conv2_biases)

        仅在这里我们就有了四个不同的变量:conv1_weights,conv1_biasesconv2_weights, 和conv2_biases.

      • 使用变量空间和以后:tf.variable_scope(<name>) 和 tf.get_variable(<name>,<shape>,<initializer>):
      • def conv_relu(input, kernel_shape, bias_shape):
            # Create variable named "weights".
            weights = tf.get_variable("weights", kernel_shape,
                initializer=tf.random_normal_initializer())
            # Create variable named "biases".
            biases = tf.get_variable("biases", bias_shape,
                initializer=tf.constant_intializer(0.0))
            conv = tf.nn.conv2d(input, weights,
                strides=[1, 1, 1, 1], padding='SAME')
            return tf.nn.relu(conv + biases)
        def my_image_filter(input_images):
            with tf.variable_scope("conv1"):
                # Variables created here will be named "conv1/weights", "conv1/biases".
                relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
            with tf.variable_scope("conv2"):
                # Variables created here will be named "conv2/weights", "conv2/biases".
                return conv_relu(relu1, [5, 5, 32, 32], [32])

        因为共享变量不能重复,即小明的枣庄站不可能有两个。所以需要使用scope.reuse_variables()。现在,让我们看看当我们调用 my_image_filter() 两次时究竟会发生了什么.

      • with tf.variable_scope("image_filters") as scope:
            result1 = my_image_filter(image1)
            scope.reuse_variables()
            result2 = my_image_filter(image2)
  • tf.scatter_nd_add(ref, indices, updates, use_locking=False, name=None) 稀疏变量相加:按照索引的位置求和

    • ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
      indices = tf.constant([[4], [3], [1], [7]])
      updates = tf.constant([9, 10, 11, 12])
      add = tf.scatter_nd_add(ref, indices, updates)
      with tf.Session() as sess:
        print sess.run(add)
      
      [out]
      [1, 13, 3, 14, 14, 6, 7, 20]

       

 


 

  • np.linalg.norm(x, ord=None, axis=None, keepdims=False):计算矩阵/矢量的范数
    • 意义:该函数可以返回以下8种矩阵范数的一种或者无穷多矢量范数的一种,具体返回哪一种要看ord参数
    • 参数: 
      • x : 输入数组
      • ord : {non-zero int, inf, -inf, 'fro', 'nuc'}
      • axis : {int, 2-tuple of ints, None}
      • keepdims : bool

The following norms can be calculated:
===== ============================ ==========================
ord    norm for matrices           norm for vectors
===== ============================ ==========================
None       Frobenius norm           2-norm
'fro'     Frobenius norm           --
'nuc'        nuclear norm             --
inf      max(sum(abs(x), axis=1))         max(abs(x))
-inf     min(sum(abs(x), axis=1))       min(abs(x))
0        --                  sum(x != 0)
1       max(sum(abs(x), axis=0))       as below
-1     min(sum(abs(x), axis=0))         as below
2      2-norm (largest sing. value)        as below
-2       smallest singular value           as below
other    --                   sum(abs(x)**ord)**(1./ord)
===== ============================ ==========================

  • np.asarray(a, dtype=None, order=None)
    • 意义:将输入转换成数组
    • a : array_like: 可以是列表, 元组的列表, 元组, 元组的元组,列表的元组以及n-d数组
    • dtype: 默认根据输入的类型决定输出的类型
    • order: 使用row-major还是column-major内存格式
    • a = [1,2]
      np.asarray(a)
      [out]
      array([1,2])
  • 静态图和动态图:
    • 动态图:所思即所得,简单说,我们敲了一段代码想要立马看到它的结果,如 b = rand(shape=[1,2],dtype = float32) + 1,只需要运行这行写好的代码即可
    • 静态图:所思tf.Session.run()之后才得到。同样是上行代码,我们必须要使用sess.run(b)才能得到结果,即我们要先构建图,之后调用sess.run()运行图
    • 区别:
      • 动态图使得调试更加容易;
      • 静态图需要先生成图结构,再执行相应操作,这使得我们难以发现程序中的问题。
    • TensorFlow 1.4之前的版本都是静态图,之后推出了动态图
    • Pytorch使用的是动态图
  • tf.scatter_nd_add(ref, indices, updates, use_locking=False, name=None)的意义和用法:
    • 意义:稀疏相加,即将张量updates按照整数张量indices作为索引坐标,加到可变张量ref上
    • 注意:ref必须是可变张量,由tf.Variable()定义,由tf.assign赋值
    • indices必须是整数类型(int32, int64)
    • updates:是加到ref上的张量,类型必须与ref相同
    • 例子:讲一个30*1的张量加到3*5*5的可变张量上:
    • import tensorflow as tf
      """
      练习tf.scattered_nd_add(ref, indices, updates, use_locking=False, name=None)
      """
      ## ref
      ref = tf.Variable(tf.zeros([3,5,5]),trainable=False)
      ref = tf.assign(ref,tf.zeros([3,5,5]))
      
      ## indices
      i = tf.range(3,dtype=tf.int32)
      i = tf.expand_dims(i,axis=1)
      i = tf.tile(i,[1,10])
      i = tf.reshape(i,[30,1])
      p = tf.random_uniform([30,2],maxval=5,dtype=tf.int32)
      idx = tf.concat([i,p],axis=1)
      
      ## update
      u = tf.ones([30])
      
      ## result
      res = tf.scatter_nd_add(ref,idx,u)
      
      with tf.Session() as sess:
          print(sess.run(res))
          print(sess.run(res).shape)
      
      [out]
      [[[0. 0. 1. 0. 0.]
        [0. 1. 0. 0. 0.]
        [0. 0. 1. 1. 1.]
        [2. 1. 1. 0. 0.]
        [1. 0. 0. 0. 0.]]
      
       [[0. 1. 0. 0. 0.]
        [0. 0. 0. 0. 0.]
        [0. 1. 0. 0. 0.]
        [1. 0. 1. 2. 0.]
        [1. 1. 1. 0. 1.]]
      
       [[1. 0. 1. 0. 1.]
        [0. 0. 2. 1. 0.]
        [0. 1. 0. 0. 0.]
        [0. 0. 2. 0. 1.]
        [0. 0. 0. 0. 0.]]]
      (3, 5, 5)
      View Code
  • tensorflow如何返回运算的中间变量?
    • 这个真的要先吐槽一波,太cd了!tensorflow是静态图,所以在建好图以后才能,运行sess.run()才能知道中间发生了什么,所以每次建好图运行sess.run()的时候就像刮彩票一样
    • 下面介绍怎么返回中间变量:
    • with tf.Session() as sess:
         ...:     a = tf.random_uniform([2,])
         ...:     b = 1.0 + a
         ...:     [a,b] = sess.run([a,b])
         ...:     print(a,b)
      
      [out]
      [0.23544157 0.9657197 ] [1.2354416 1.9657197]

  


 

  • tf.image.resize_images(images, size, method=ResizeMethod.BILINEAR, align_corners=False)
      • 将images缩放大小为size;images可以是4-d张量:[batch, height, width, channels] 或者形状为[height, width, channels]的3-d张量,注意tensorflow的张量为[B,H,W, C]而Pytorch[B,C,H,W]
      • size: [new_height, size_width]
      • 返回值:4-d张量[batch, new_height, new_width, channels]或者3-d张量[new_height, new_width, channels]
  • tensorflow中数组与张量的互相转换
    • 数组到张量:np.asarray(a, dtype=None, order=None)
    • 张量到数组:tf.convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None)
  • tf.data.TFRecordDataset(filenames, compression_type=None, buffer_size=None, num_parallel_reads=None)
    • 意义:读取一个TFRecord文件格式
    • 注意:当从远程文件系统读取TFRecord文件时,num_parallel_reads可以用于提高表现
    • filenames: 'tf.string'张量或者包含一个或多个文件名的'tf.data.Dataset'
    • compression_type: (Optional.) A `tf.string` scalar evaluating to one of `""` (no compression), `"ZLIB"`, or `"GZIP"`.

  • tf.data.TFRecordDataset.map(self, map_func, num_parallel_calls=None)
    • 将dataset的每一个元素,依次映射到map_func函数进行处理,将结果返回,构成一个经过map_func处理的新的数据集,新数据集内元素的顺序与原始数据集顺序一致。
  • python中的filter(function or None, iterable) --> filter object的作用:
    • 作用:将iterable的每一次可迭代的对象依次传入function, 并输出function为True的可迭代对象。
    • 注意:返回的是filter对象,因此使用list()转换成列表。
    • a = range(10)
      b = filter(lambda x : x %2 == 1, a)
      b = list(b)
      [out]
      [1, 3, 5, 7, 9]
  • tensorflow中set_shape的作用是定义一个变量的形状。

      


 

  • tensorflow中的保存和重构模型变量:tf.train.Saver()
  •  tensorflow中ckpt文件的意思:https://www.zhihu.com/question/61946760
    • checkpoint 用于存放文件列表,包括各种断点文件
    • model.ckpt.meata 保存网络结构
    • model.ckpt保存网络数据
  • tensorflow中的zip(iter1 [, iter2,...])的作用:
    • 返回zip对象,使用.__next__()方法获取元组,元组的第i个元素,来自于第i个可迭代参数。.__next__()方法继续取值,知道最短的迭代对象被取完。

例子:

a = [j.item() for i,j in enumerate(np.random.randint(10,size=4))]
b = [j.item() for i,j in enumerate(np.random.rand(5,))]
a,b
[out]
([7, 3, 9, 8],  [0.2828299613581847,
  0.44183731917417024,
  0.2797388093264329,
  0.6623954773073408,
  0.7222045742528438])

dict(zip(a,b))

[out]:
{7: 0.2828299613581847,
 3: 0.44183731917417024,
 9: 0.2797388093264329,
 8: 0.6623954773073408}

  • 使用Python调试程序时,显示“UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”错误
    •   解决:import tkinter  
      import tkinter
      import matplotlib 
      matplotlib.use('TkAgg')
      
      marker = np.zeros([192,192,3])
      marker[92,92,:] = 1000.0
      
      plt.imshow(marker)
      plt.show()
  • 生成kernel时如何中心化呢?
    • 方法:首先随机生成kernel的非0位置坐标p; 其次标准化:使得位置p均值为0,方差为1;最后,位置 p + floor(kernel // 2)便使得kernel位于图像中心。
posted on 2020-02-12 18:15  think_deeply  阅读(335)  评论(0编辑  收藏  举报