python代码笔记杂烩

目录

想要快速查找,可以试试Ctrl+F

  1. python
    1.0 others
    1.1 numpy
    1.2 dict
    1.3 collections
    1.4 functools
    1.5 argparse
    1.6 getopt
    1.7 main
  2. tensorflow
    2.1 tensorboard
    2.2 tf.train
    2.3 others
    2.4 tf.nn
    2.5 tf.app.flags
    2.6 name
    2.7 tf.WholeFileReader
    2.8 tf.slice
  3. pytorch

1. Python

1.0 others

1.0.1 range()

range(start, stop[, step])

1.0.2 ``


1.1 numpy

1.1.1 np.random.choice

import numpy as np
# 参数意思分别 是从a 中以概率P,随机选择3个, p没有指定的时候相当于是一致的分布
a1 = np.random.choice(a=5, size=3, replace=False, p=None) print(a1)
# 非一致的分布,会以多少的概率提出来
a2 = np.random.choice(a=5, size=3, replace=False, p=[0.2, 0.1, 0.3, 0.4, 0.0])
# replacement 代表的意思是抽样之后还放不放回去,如果是False的话,那么出来的三个数都不一样,如果是True的话, 有可能会出现重复的,因为前面的抽的放回去了。

1.1.2 np.argwhere(a)

np.argwhere( a ) 
# 返回非0的数组元组的索引,其中a是要索引数组的条件。

1.1.3


1.2 字典

1.2.1 setdefault()

dict.setdefault(key, default=None)
# key : 查找的键值
# default: 键不存在时,设置的默认键值
# return : 如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值

1.2.2 ``


1.3 collections

1.3.1 OrderedDict()

使用dict时,Key是无序的。在对dict做迭代时,无法确定Key的顺序。而如果要保持Key的顺序,可以用OrderedDict。注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序

from collections import OrderedDict
dict = OrderedDict()

1.3.2 ``

扫描二维码关注公众号,回复: 5475123 查看本文章

1.4 functools

functools模块用于高阶函数:作用于或者返回其它函数的函数。一般来说,对于该模块,任何可调用对象都可以视为一个函数。

1.4.1 partial

简单来说就是将一个已经定义好函数固定一些参数的值,然后封装成新的函数返回
参考链接

1.5 argparse

用于解析命令行参数,较为详细的解释可以参考博客

import argparse 
	
if __name__ == '__main__': 
	# 创建命令行解析器句柄,并自定义描述信息 
	parser = argparse.ArgumentParser(description='test the argparse package') 
	# 定义必选参数 
	positionArg parser.add_argument('positionArg') 
	# 定义可选参数verbosity2,并通过设定store_true表示该选项不需要接收参数,若不设action,则默认是需要接收参数的,否则报错 
	parser.add_argument('--verbosity2', '-v2', action='store_true', help='test the action arg') 
	# 指定参数类型(默认是 str) 
	parser.add_argument('x', type=int, help='test the type')  
	# 设置参数可选范围, 默认值 
	parser.add_argument('--verbosity4', '-v4', type=str, choices=['one', 'two', 'three'], default=1, help='test default value') args = parser.parse_args() 
	# 返回一个命名空间 
	print(args) params = vars(args) 
	# 返回 args 的属性和属性值的字典 
	for k, v in params.items():
		print(k, v)

1.6 getopt

同样是获取命令行参数,类似argparse

1.7 main

在C/C++/Java中,main是程序执行的起点,Python中,也有类似的运行机制,但方式却截然不同:Python使用缩进对齐组织代码的执行,所有没有缩进的代码(非函数定义和类定义),都会在载入时自动执行,这些代码,可以认为是Python的main函数。更详细的解释参考博客.
简单来说就是python 代码的执行不依赖于 main() 函数, python 代码从没有缩进的代码开始执行。

  1. python代码执行时首先从第一行往下扫描,执行所有没有缩进的代码行;
  2. 对那些def定义的函数跳过不执行;
  3. 最后如果扫描到下面这个语句,就会判断当前程序是否是直接在命令行运行(因为也可能是在其他包中被调用),如果是,则执行code...,否则一般遇到文件尾就结束了。
if name == '__mian__':
	code...

2. Tensorflow

2.1 tensorboard

2.1.1 with tf.name_scope()tf.variable_scope()

tf.name_scope()和tf.variable_scope()是两个作用域,一般与两个创建/调用变量的函数tf.variable() 和tf.get_variable()搭配使用。它们搭配在一起的两个常见用途:

  • 变量共享
  • tensorboard画流程图时为了可视化封装变量,这两种用途有特定的搭配方式,掌握好就可以用了。

区别是tf.variable_scope可以让不同scope中的变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable的变量
tf.name_scope可以让变量有相同的命名,只是限于tf.Variable的变量
参考链接1
参考链接2

2.1.2 tf.summary.scalar()

tf.summary()的各类方法,能够保存训练过程以及参数分布图并在tensorboard显示。
参考链接

tf.summary.scalar(tags, values, collections=None, name=None)
# 显示标量信息,例如:
tf.summary.scalar('mean', mean)

2.1.3 tf.summary.image()

tf.summary.image(tag, tensor, max_images=3, collections=None, name=None)
# 输出带图像的probuf,汇总数据的图像的的形式如下: ' tag /image/0', ' tag /image/1'...,如:input/image/0等。

2.1.4 tf.summary.histogram()

tf.summary.histogram(tags, values, collections=None, name=None)
# 用来显示训练过程中变量的分布情况
tf.summary.histogram('histogram', var)

2.1.5 tf.summary.merge_all()

# merge_all 可以将所有summary全部保存到磁盘,以便tensorboard显示。如果没有特殊要求,一般用这一句就可以显示训练时的各种信息了。
tf.summaries.merge_all(key='summaries')

2.1.6 tf.summary.merge()

tf.summary.merge(inputs, collections=None, name=None)
# 一般选择要保存的信息还需要用到tf.get_collection()函数,例如:
tf.summary.scalar('accuracy',acc)                   #生成准确率标量图  
merge_summary = tf.summary.merge([tf.get_collection(tf.GraphKeys.SUMMARIES,'accuracy'),...(其他要显示的信息)])  
train_writer = tf.summary.FileWriter(dir,sess.graph)#定义一个写入summary的目标文件,dir为写入文件地址  
......                                              # 交叉熵、优化器等定义
for step in xrange(training_step):                  #训练循环  
    train_summary = sess.run(merge_summary,feed_dict = {...})#调用sess.run运行图,生成一步的训练过程数据  
    train_writer.add_summary(train_summary,step)    #调用train_writer的add_summary方法将训练过程以及训练步数保存

2.1.7


2.2 tf.train

2.2.1 tf.train.get_or_create_global_step()

这个函数主要用于返回或者创建(如果有必要的话)一个全局步数的tensor。参数只有一个,就是图,如果没有指定那么就是默认的图。

2.2.2


2.3 others

2.3.1 sess.run()

run(fetches,feed_dict=None,options=None,run_metadata=None)
# fetches:可以是一个图中的element(元素),或者一些list、tuple、namedtuple, dict, or OrderedDict containing graph elements at its leaves,总之就是一般结构都可以。
# feed_dict:是一个字典,键是tensor的名字,值是重写的tensor的内容。通常用在Placeholder的实现上。feed 只在调用它的方法内有效, 方法结束, feed 就会消失。
# options:
# run_metadata:

什么时候需要运行sess.run?

  • 想要获取某个变量的时候
  • 执行某种操作的时候,这个操作不是一个变量,没有值
# 获取变量d的值
import tensorflow as tf
import numpy as np
a = np.zeros((16))
c = tf.reshape(a, [4, 4])
d = tf.reshape(c, [2, 8])
sess = tf.Session()
print(sess.rum(d))
# 如下图n这个更新操作,除此之外还包括神经网络训练的时候的optimizer
import tensorflow as tf
import numpy as np
a = np.zeros((16))
c = tf.reshape(a, [4, 4])
d = tf.reshape(c, [2, 8])
n = tf.assign(d, c)
sess.tf.Session()
sess.run(n)

2.3.2 tf.GraphKeys

简单来说,在创建图的过程中,TensorFlow的Python底层会自动用一些collection对op进行归类,方便之后的调用。这部分collection的名字被称为tf.GraphKeys,可以用来获取不同类型的op。当然,我们也可以自定义collection来收集op。
参考链接

2.3.3 tf.stack()tf.unstack()

分别表示矩阵的合并和分解

import tensorflow as tf 
import sys 
import os 
import numpy as np 
a = tf.constant([1 , 2 , 3]) 
b = tf.constant([4 , 5 , 6]) 
c = tf.stack([a , b] , axis=0) 
d = tf.unstack(c , axis=0) 
e = tf.unstack(c , axis=1) 

with tf.Session() as sess: 
	sess.run(tf.global_variables_initializer()) 
	print(sess.run(c)) 
	print(sess.run(d)) 
	print(sess.run(e))
# outputs :
[[1 2 3]
[4 5 6]]
[array([1, 2, 3]), array([4, 5, 6])]
[array([1, 4]), array([2, 5]), array([3, 6])]

2.3.4 tf.add_n()

实现一个列表的元素的相加。输入的对象是一个列表,列表里的元素可以是向量,矩阵,等

tf.add_n(inputs, name=None)
# inputs: A list of at least 1 Tensor objects of the same type in: float32, float64, int64, int32, uint8, int16, int8, complex64, qint8, quint8, qint32. Must all be the same size and shape.
# name: A name for the operation (optional).
# returns: A Tensor. Has the same type as inputs.
import tensorflow as tf;
import numpy as np;
 
input1 = tf.constant([1.0, 2.0, 3.0])
input2 = tf.Variable(tf.random_uniform([3]))
output = tf.add_n([input1, input2])
 
with tf.Session() as sess:
	sess.run(tf.initialize_all_variables())
	print sess.run(input1 + input2)
	print sess.run(output)
# outputs :
[ 1.68921876  2.73008633  3.04061747]
[ 1.68921876  2.73008633  3.04061747]

2.3.5 tf.tile()

应用于需要张量扩展的场景,具体说来就是:
如果现有一个形状如[width, height]的张量,需要得到一个基于原张量的,形状如[batch_size,width,height]的张量,其中每一个batch的内容都和原张量一模一样。

tf.tile(input, multiples, name=None)
# multiples : 一个list,表示每个维度上复制的次数。例如:
raw = tf.Variable(tf.random_normal(shape=(1, 3, 2)))
multi = tf.tile(raw, multiples=[2, 1, 1])

2.3.6 tf.where()

where(condition, name=None)
# returns : condition 中为 True 的元素坐标
where(condition, x=None, y=None, name=None)
# returns : condition 中为 True 的元素用 x 中对应位置元素代替,为 False 的元素用 y 中对应位置元素代替

2.3.7 tf.split()

主要作用就是切割一个张量,返回切割的结果。
参考链接

tf.split(value, num_or_size_splits, axis=0, num=None, name='split')
# value : 需要被切割的张量
# num_or_size_splits : 可以是一个整数或一个向量
# axis : 被切割的维度

2.3.8 tf.trainable_variables() & tf.all_variables()

tf.trainable_variables 返回的是需要训练的变量列表,即创建时未声明 trainable = False
tf.all_variables 返回的是所有变量的列表
参考链接

2.3.9 tf.device(device_name)

指定运行设备,可以是 CPU(/cpu:0) 或 GPU(\gpu:0),区别在于使用 CPU 时 tensor 放在内存中,使用 GPU 时放在显存中
参考链接

2.3.10 tf.contrib.framework.nest.map_structure_up_to()

官方文档

tf.contrib.framework.nest.map_structure_up_to(shallow_tree, func, *inputs)

2.3.11 tf.contrib.framework.nest.map_structure()

用一个统一的函数处理一个
官方文档

tf.contrib.framework.nest.map_structure(func, *structure, **check_types_dict)
# 用函数 func 处理 structure 中的每一项,返回处理后的结果
# 即 returns[i] = func(structure[i])

2.3.12 tf.transpose()

tf.transpose(input, [dimension_1, dimenaion_2,..,dimension_n])
# 将张量 input 的不同维度进行交换

2.3.13 tf.convert_to_tensor

用于将不同数据变成张量:比如可以让数组变成张量、也可以让列表变成张量

A = list([1,2,3])
B = tf.convert_to_tensor(A)

2.3.14 tf.pad()

参考链接

tf.pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0)

2.3.15 tf.reduce_prod()

降维点乘,可以类比 reduce_sum()reduce_mean()

reduce_prod(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None)
# input_tensor :要降维相乘的 tensor
# axis : 要相乘的维度
from tensorflow import reduce_prod as reduce
from tensorflow import Session

c = [[[1,2],
      [3,4]],
     
     [[5,6],
      [7,8]]]
b = reduce(c,axis=[0])

with Session() as sess:
    print(sess.run(b))
    print(b.get_shape())

# outputs :
[[ 5 12]
 [21 32]]
(2, 2)

2.3.16 tf.clip_by_value()

输入一个张量A,把A中的每一个元素的值都压缩在min和max之间。小于min的让它等于min,大于max的元素的值等于max。

tf.clip_by_value(A, min, max)

# 例如 :
A = np.array([[1,1,2,4], [3,4,8,5]])  
with tf.Session() as sess:  
    print sess.run(tf.clip_by_value(A, 2, 5)) 

# outputs :
[[2 2 2 4]
 [3 4 5 5]]

2.3.17 tf.less()

tf.less(x,y,name=None)
# 逐元素比较 x < y 是否成立
# returns : bool型的tensor

2.3.18 tf.cond()

类似 if...else...,不过还是略有不同
参考链接

tf.cond(pred, fn1, fn2, name=None)

2.3.19 tf.multinomial()

从多项式分布中抽取样本

tf.multinomial(logits, num_samples, seed=None, name=None)
# logits : 形状为 [batch_size, num_classes] 的二维张量;每个切片:[i, :] 表示所有类的非标准化对数概率
# num_samples : 0维张量,为每行切片绘制的独立样本数
# seed : Python整数,用于为分发创建一个随机种子
# returns : 形状为[batch_size, num_samples]

2.3.20 tf.cast()

tf.cast(x, dtype, name=None) 
# 将 x 的数据类型转化为 dtype

2.3.21 tf.squeeze()

squeeze(input,axis=None,name=None,squeeze_dims=None)
# 去掉所有维数为 1 的维度

2.3.21 tf.cond()


2.3.21 tf.cond()


2.3.21 tf.cond()


2.4 tf.nn

2.4.1 tf.nn.dynamic_rnn()

参考链接

2.4.2 tf.nn.softmax()

tf.nn.softmax(logits,axis=None,name=None,dim=None)
# axix : 默认最后一个维度

2.5 tf.app.flags

类似于python 的 argparse,详细解释见博客1(例子2更容易理解一点)、博客2

import tensorflow as tf 

FLAGS = tf.app.flags.FLAGS 
tf.app.flags.DEFINE_string('string', 'train', 'This is a string') 
tf.app.flags.DEFINE_float('learning_rate', 0.001, 'This is the rate in training') 
tf.app.flags.DEFINE_boolean('flag', True, 'This is a flag') 

def main(unuse_args): 
	print('string: ', FLAGS.string) 
	print('learning_rate: ', FLAGS.learning_rate) 
	print('flag: ', FLAGS.flag) 
if __name__ == '__main__': 
	tf.app.run()

主函数中的tf.app.run()会调用main,并传递参数,因此必须在main函数中设置一个参数位置。如果要更换main名字,只需要在tf.app.run()中传入一个指定的函数名即可。

def test(args):
    # test
    ...
if __name__ == '__main__':
    tf.app.run(test)

2.6 name

参考资料:TF中的name有什么用
Tensorflow中定义变量时往往还会设置一个name,那么这个name和变量名有什么区别呢?它有什么作用呢?简单来说这个name有两个作用:

  1. 保存程序数据到文件时,用name保存;
  2. 用TensorBoard可视化时用name显示名称

2.7 tf.WholeFileReader

用队列读取文件
tensorflow读取图片的方法
十图详解TensorFlow数据读取机制(附代码)

2.8 tf.slice

切割多维数组
tf.slice()到底怎么切的,看不懂你掐死我

slice(input_, begin, size, name=None)
# input_: 是你输入的tensor,就是被切的那个
# begin: 是每一个维度的起始位置
# size: 相当于问每个维度拿几个元素出来

3.pytorch

安装请移步官网

猜你喜欢

转载自blog.csdn.net/weixin_41024483/article/details/84300987