TensorFlow, Mxnet, PyTorch: 要点总结及常见神经网络代码实现

2022-09-23 13:47:55

一、深度学习框架

TensorFlow 1.x

# 所需模块import numpyas npimport tensorflowas tf#从TF1.x中导入import tensorflow.compat.v1as tf#从TF2.0中导入1.x# 生成
tf.Variable(1,trainable=True)#生成参数变量
tf.placeholder((None,3), dtype=tf.float32)#生成占位符
tf.range(10)#生成序列
tf.one_hot(X,10)#生成One-Hot数组
tf.zeros((2,3),dtype=tf.int32)#生成零数组
tf.ones((2,3),dtype=tf.int32)#生成一数组
tf.fill((2,3),dtype=tf.float32)#生成常数数组
tf.constant([1,2])#生成定值数组
tf.random_uniform((2,3,5),seed=1)#生成均匀分布随机数数组
tf.random_normal((2,3,5),stddev=1.5)#生成正态分布随机数数组
tf.truncated_normal((2,3,5),stddev=1.5)#生成正态分布随机数数组(大于2倍sigma将被剪裁)# 数学运算
tf.add(X1,X2)#加法
tf.add_n([X1,X2,X3])#加法
tf.subtract(X1,X2)#减法
tf.multiply(X1,X2)#乘法
tf.square(X)#平方
tf.matmul(X,W)#点积
tf.transpose(X)#转置
tf.clip_by_value(X,min_,max_)#裁剪
tf.assign(x,10)#赋值# 统计学运算
tf.reduce_sum(X)#求和
tf.reduce_mean(X)#平均
tf.argmax(X,1)#最大值索引# 条件判断
tf.greater(X1,X2)#比较大小
tf.less(X1,X2)#比较大小
tf.equal(X1,X2)#相等判断
tf.where(tf.greater(X1,X2),Y1,Y2)#条件索引
tf.cond(cond,func_1,func_2)#条件判断
tf.while_loop(cond,body,variables)#条件循环# 全局信息
tf.shape(X)#维度
tf.expand_dims(X,axis=0)#扩充维度
tf.squeeze(X)#压缩维度
tf.global_variables()#查看全局变量
tf.trainable_variables()#查看参数变量
tf.cast(X,tf.float32)#改变元素类型
tf.map_fn(func,elems=X)#逐元素映射
tf.gather(X,indicies)#调用元素
tf.split(X,5,axis=0)#拆分
tf.concat(*outputs,axis=0)#合并
tf.sequence_mask(mask_arr,max_len)#生成Mask矩阵
tf.boolean_mask(X,mask)#应用Mask矩阵# 滑动平均
ema= tf.train.ExponentialMovingAverage(0.97)#滑动平均类
ema.apply([w1,w2,w3])#应用衰减
ema.average(w1)#提取滑动平均值# 数据迭代
dataset= tf.data.Dataset.from_tensor_slices(data)#建立数据集
dataset.shuffle(1000).batch(100)#打乱并生成批量
iterator= tf.data.Iterator.from_structure(dataset.output_types,dataset.output_shapes)#生成迭代器
iterator.make_initializer(dataset)#激活迭代器
iterator.get_next()#获取批量数据# 命令行接口
tf.app.flags.DEFINE_integer("t",7,"")#定义整数
tf.app.flags.DEFINE_float("t",7.4,"")#定义浮点
tf.app.flags.DEFINE_boolean("t",True,"")#定义布尔值
tf.app.flags.DEFINE_string("t","te","")#定义字符串
tf.app.flags.FLAGS.t#读取指定参数
tf.app.flags.FLAGS.__flags#读取所有参数
tf.app.flags.mark_flag_as_required()#标记为必填参数
tf.app.run()#启动程序
$ python code.py--t=7--h=True#指定参数运行文件
hparams= tf.contrib.training.HParams(lr=0.1)#定义超参数对象
hparams.batch_size=32#超参数扩展
hparams.values()#转换为字典
hparams.to_json()#转换为Json字符串# TFRecord
_integers,_floats,_bytes=[1,1,1],[2,2,2],[b'3',b'3',b'3']
writer= tf.python_io.TFRecordWriter(r'/data.tfrecords')#定义写入类对象for iinrange(len(_integers)):
    features= tf.train.Features(feature={'_integers':tf.train.Feature(int64_list=tf.train.Int64List(value=[_integers[i]])),'_floats':tf.train.Feature(float_list=tf.train.FloatList(value=[_floats[i]])),'_bytes':tf.train.Feature(bytes_list=tf.train.BytesList(value=[_bytes[i]]))})
    example= tf.train.Example(features=features)
    writer.write(example.SerializeToString())#写入文件
writer.close()
ex=next(tf.python_io.tf_record_iterator(r'/data.tfrecords'))#查看数据类型print(tf.train.Example.FromString(ex))
reader= tf.TFRecordReader()#定义读取类对象
queue= tf.train.string_input_producer([r'/data.tfrecords'])#定义读取队列
_, serialized_example= reader.read(queue)#按队列读取
features= tf.parse_single_example(serialized_example,features={'_integers':tf.FixedLenFeature([],tf.int64),'_floats':tf.FixedLenFeature([],tf.float32)})
_integers= tf.cast(features['_integers'], tf.int64)
_floats= tf.cast(features['_floats'], tf.float32)with tf.Session()as sess:
    tf.global_variables_initializer().run()
    coord= tf.train.Coordinator()
    threads= tf.train.start_queue_runners(sess=sess, coord=coord)for iinrange(3):print(_integers.eval())
    coord.request_stop()
    coord.join(threads=threads)# TensorBoard
tf.summary.histogram(name,variable)#将变量加入监测目标(会话中执行)
tf.summary.scalar(name,scalar)#将标量加入监测目标(会话中执行)
tf.summary.image(name,image)#将图像加入监测目标(会话中执行)
tf.summary.text(name,text)#将文本加入监测目标(立即执行)
tf.summary.audio(name,audio)#将音频加入监测目标(立即执行)
summary_op= tf.summary.merge_all()#将以上检测目标汇总
options= tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)#配置运行时记录的信息对象(会话中执行)
run_metadata= tf.RunMetadata()#配置运行时记录的Proto对象(会话中执行)
summary,_= sess.run((summary_op,train_op),feed_dict=feed_dict,options=options,run_metadata=run_metada)
writer= tf.summary.FileWriter('/logs',tf.get_default_graph())#配置日志文件并写入计算图
writer.add_run_metadata(run_metadata,'step %03d'%i)#添加间隔记录至日志文件
writer.add_summary(summary,i)#添加检测目标汇总至日志文件
writer.close()#关闭日志文件
$ tensorboard--logdir='D:/logs'#打开TensorBoard(浏览器中输入localhost:6006)# 会话
config= tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)#会话设置
sess= tf.Session(config=config)#开启普通会话
sess= tf.InteractiveSession(config=config)#开启交互式会话
sess.run(tf.global_variables_initializer)#启动全部变量print(x.eval())#交互式对话下快速取值
sess.close()#关闭会话# 命名空间with tf.name_scope('A'):with tf.variable_scope('B',reuse=tf.AUTO_REUSE):
		a= tf.Variable(1,name='a')#在命名空间和变量空间下生成变量
		b= tf.get_variable(name='b',shape=(1),initializer=tf.zeros_initializer)#在变量空间下生成变量
tf.zeros_initializer#零初始器
tf.ones_initializer#一初始器
tf.constant_initializer(2)#常数初始器
tf.random_uniform_initializer#均匀分布随机数初始器
tf.random_normal_initializer#正态分布随机数初始器
tf.truncated_normal_initializer#正态分布裁剪随机数初始器(剪裁范围在±2σ之外的随机数)with tf.variable_scope('',reuse=True):
	x2= tf.get_variable(name='W/X')#调用变量# 计算图
graph= tf.Graph()#计算图(不同计算图上的变量和运算不会共享)
graph.device('/gpu:0')#指定计算图地址with graph.as_default():#设置默认计算图
	x= tf.constant([1,2,3])#在默认计算图上生成变量
sess= tf.Session(graph=graph)#在指定计算图开启会话
sess.graph.finalize()#锁定计算图(无法继续添加节点)
tf.reset_default_graph()#重置默认计算图(清空内存占用)# 数据集from tensorflow.examples.tutorials.ministimport input_data#MNIST手写识别数据库
mnist= input_data.read_data_sets('/MINIST_data/', one_hot=True)#读取数据到指定路径
X_train,y_train,X_test,y_test= mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
mnist.train.next_batch(64)#选取批量数据# 计算设备
config= tf.ConfigProto(log_device_placement=True,#显示计算设备
						allow_soft_placement=True)#自动将GPU无法执行的操作转回CPU
config.gpu_options.allow_growth=True#按需分配GPU显存
config.gpu_options.per_process_gpu_memory_fraction=0.4#指定分配GPU显存
sess= tf.Session(config=config)#应用以上配置with tf.device('/cpu:0'):#指定存储设备
	x= tf.constant([1,2,3])#在指定存储设备上生成变量
os.environ['CUDA_VISIBLE_DEVICES']='2'#指定参与计算的GPU设备
$ CUDA_VISIBLE_DEVICES='0,2' python code.py#指定参与计算的GPU设备# 分布式计算
cluster= tf.train.ClusterSpec({'ps':['tf-ps0:2222',#定义集群并分配工作与任务给不同端口'tf-ps1:2222']})#(这是一个TF常用集群配置方法)'worker':['tf-worker0:2222',#(ps负责存储、获取以及更新变量的取值)'tf-worker1:2222',#(ps, abbr. Parameter Server)'tf-worker2:2222'],#(worker负责反向传播算法获取梯度)
server= tf.train.Server(cluster, job_name='ps', task_index=0)#为指定工作与任务创建服务器
server= tf.train.Server.create_local_server()#创建本地单进程服务器
server.start()#开启服务器
server.join()#暂停服务器
sess= tf.Session(target=server.target)#在服务器上新建会话
device_setter= tf.train.replica_device_setter(work_device='/job:worker/task:0',cluster=cluster)#配置计算分配器
optimizer= tf.train.SyncReplicasOptimizer(#配置同步模式优化器
		tf.train.GradientDescentOptimizer(learning_rate),
		replicas_to_aggregate=n_workers,
		total_num_replicas=n_workers)
sync_replicas_hook= optimizer.make_session_run_hook(is_chief)#配置同步模式hookwith tf.device(device_setter):#指定计算设备并分配计算资源
	is_chief=(TASK_ID==0)											
	global_step,loss,train_op= build_model(x,y_,is_chief)#在build_model函数中定义节点(需提前完成x、y_的分配)
	hooks=[sync_replicas_hook,#同步模式(异步模式删除sync_replicas_hook)
			tf.train.StopAtStepHook(last_step=TRAINING_STEPS)]#设定训练终止迭代数with tf.train.MonitoredTrainingSession(#开启分布式计算中心会话
			master=server.target,									
			is_chief=is_chief,										
			checkpoint_dir=MODEL_SAVE_PATH,
			hooks=hooks,
			save_checkpoint_secs=60,
			config=config)as sess:whilenot sess.should_stop():#迭代
			x,y= data.next_batch(BATCH_SIZE)				
			l,step,_= sess.run((loss,train_op,global_step),feed_dict=feed_dict(x,y))# 深度学习:优化
tf.nn.tanh(Z)#Tanh激活函数
tf.nn.relu(Z)#Relu激活函数
tf.nn.sigmoid(Z)#Sigmoid激活函数
tf.nn.softmax(Z)#Softmax归一化函数
tf.nn.softmax_cross_entropy_with_logits(logits=y,labels=y_)#交叉熵损失函数(标签为概率分布)
tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=y_)#交叉熵损失函数(标签为数值)
tf.train.GradientDescentOptimizer(learning_rate=0.01)#梯度下降优化器
tf.train.AdamOptimizer(learning_rate=0.01)#Adam优化器
tf.train.MomentumOptimizer(learning_rate=0.01)#Momentum优化器
train_op= Optimizer.minimize(loss)#定义优化流程# 深度学习:梯度剪裁
grads= Optimizer.compute_gradients(loss)#定义梯度剪裁流程for i,(g, v)inenumerate(grads):if gisnotNone: 
    	grads[i]=(tf.clip_by_norm(g, clipping_theta), v)#剪裁梯度
train_op= Trainer.apply_gradients(grads)#应用剪裁后的梯度# 深度学习:构建网络
tf.nn.embedding_lookup(embedding,data)#词向量映射
tf.nn.conv2d(X,filter=[1,2,2,1],strides=[1,1,1,1],padding='SAME')#卷积层
tf.nn.bias_add(X,bias)#添加偏置项
tf.nn.relu(X)#激活
tf.nn.moments(X,axes=[0,
  • 作者:luv_dusk
  • 原文链接:https://blog.csdn.net/weixin_43269174/article/details/88008917
    更新时间:2022-09-23 13:47:55