tensorflow的学习笔记--常用方法和代码片段

今天整理下学习的tensorflow的几个常用的方法和代码片段.

  1. tf.get_collection("") 从集合中取出全部变量,生成一个列表

  2. tf.add_n([]) 列表内对应元素相加

  3. tf.cast(x,dtype) 把x转为dtype类型

  4. tf.argmax(x,axis) 返回最大值所在索引号,如 tf.argmax([0,1,0]) 返回2

  5. with tf.Graph().as_default() as g: 其内定义的节点在计算图g中

  6. 保存模型:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
            saver=tf.train.Saver()# 实例化saver对象
    with tf.Session() as sess: # 在with结构的for循环一定轮数是,保存模型到当前会话
    for i in range(STEPS):
    if i%轮数 ==0
    saver.save(sess,os.path.join(""),global_step=global_step)

    ```

    7. 加载模型

    ``` python

    with tf.Session() as sess:
    ckpt=tf.train.get_checkpoint_path
    if ckpt and ckpt.model_checkpoint_path:
    saver.restore(sess,ckpt.model_checkpoint_path)
  7. 反向传播均方误差和减少loss

    1
    2
    3
    4
    5
    loss=tf.reduce_mean(tf.square(y_-y))
    # 三个减少loss的训练方法
    train_step=tf.train.GradientDescentOptimizer(learnig_rate).minimize(loss)
    train_step=tf.train.MomentumOptimizer(learnig_rate,momentum).minimize(loss)
    train_step=tf.train.AdamOptimizer(learnig_rate).minimize(loss)
  8. 损失函数

    1
    2
    3
    4
    5
    6
    7
    # tf.nn.relu   #未找到使用地方
    # tf.nn.sigmoid #未找到使用地方
    # tf.nn.tanh #未找到使用地方
    loss=tf.reduce_sum(tf.where(tf.greater(y,y_),COST(y-y_),PROFIT(y_-y))) #自定义损失函数

    ce=tf.nn.sparse_softmax_cross_entropy_with_logits(logtis=y,labels=tf.argmax(y_,1))#交叉熵
    cem=tf.reduce_mean(ce)#交叉熵
  9. 学习率计算

    1
    2
    3
    4
    5

    # 指数衰减学习率
    global_step=tf.Variable(0,trainable=False)
    learning_rate=tf.train.exponential_decay(LEARNINF_RATE_BASE,global_step,LEARNINF_RATE_STEP,LEARNINF_RATE_DECAY,staircase=True)

  1. 滑动平均

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    ema=tf.train.ExponentialMovingAverage(衰减率MOVING_AVERAGE_DECAY,当前轮数global_step)   

    ema_op=ema.apply([])
    ema_op=ema.apply(tf.trainable_variables()) # 每运行此据,所有待优化的参数求滑动平均

    with tf.control_dependencies([train_step,ema_op]):
    train_op=tf.no_op(name='train')

    ema.average(查看参数的滑动平均)

  2. 正则化

    1
    2
    3
    4
    5
    6
    loss(w)=tf.contrib.layers.l1_regularizer(REGULARIZER)(w) #w加和
    loss(w)=tf.contrib.layers.l2_regularizer(REGULARIZER)(w) # w平方加和

    tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))

    loss=cem+tf.add_n(tf.get_collection('losses'))
  3. 实例化可还原滑动平均值的saver

    1
    2
    3
    ema=tf.train.ExponentialMovingAverage(滑动平均数)
    ema_restore=ema.variable_to_restore()
    saver=tf.train.Saver(ema_restore)
  4. 准确率计算方法

    1
    2
    correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

tensorflow的学习笔记--常用方法和代码片段

http://blog.laofu.online/2019/04/14/2019-04-14-tensorflow-method/

作者

付威

发布于

2019-04-14

更新于

2020-08-10

许可协议

评论