1. 程式人生 > >【TensorFlow】正則化(過擬合問題)

【TensorFlow】正則化(過擬合問題)

轉載自:https://www.cnblogs.com/linyuanzhou/p/6923607.html,尊重原創

tf.add_to_collection:把變數放入一個集合,把很多變數變成一個列表

tf.get_collection:從一個結合中取出全部變數,是一個列表

tf.add_n:把一個列表的東西都依次加起來

例如:

  1. import tensorflow as tf;    
  2. import numpy as np;    
  3. import matplotlib.pyplot as plt;    
  4. v1 = tf.get_variable(name='v1', shape=[1], initializer=tf.constant_initializer(0))  
  5. tf.add_to_collection('loss', v1)  
  6. v2 = tf.get_variable(name='v2', shape=[1], initializer=tf.constant_initializer(2))  
  7. tf.add_to_collection('loss', v2)  
  8. with tf.Session() as sess:  
  9.     sess.run(tf.initialize_all_variables())  
  10.     print tf.get_collection('loss')  
  11.     print sess.run(tf.add_n(tf.get_collection('loss')))  

輸出:

[<tensorflow.Python.ops.variables.Variable object at 0x7f6b5d700c50>, <tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c90>]

tensorflow Regularizers

在損失函式上加上正則項是防止過擬合的一個重要方法,下面介紹如何在TensorFlow中使用正則項.

tensorflow中對引數使用正則項分為兩步: 
1. 建立一個正則方法(函式/物件) 
2. 將這個正則方法(函式/物件),應用到引數上

如何建立一個正則方法函式

tf.contrib.layers.l1_regularizer(scale, scope=None)

返回一個用來執行L1正則化的函式,函式的簽名是func(weights)
引數:

  • scale: 正則項的係數.
  • scope: 可選的scope name

tf.contrib.layers.l2_regularizer(scale, scope=None)

返回一個執行L2正則化的函式.

tf.contrib.layers.sum_regularizer(regularizer_list, scope=None)

返回一個可以執行多種(個)正則化的函式.意思是,建立一個正則化方法,這個方法是多個正則化方法的混合體.

引數: 
regularizer_list: regulizer的列表

已經知道如何建立正則化方法了,下面要說明的就是如何將正則化方法應用到引數上

應用正則化方法到引數上

tf.contrib.layers.apply_regularization(regularizer, weights_list=None)

先看引數

  • regularizer:就是我們上一步建立的正則化方法
  • weights_list: 想要執行正則化方法的引數列表,如果為None的話,就取GraphKeys.WEIGHTS中的weights.

函式返回一個標量Tensor,同時,這個標量Tensor也會儲存到GraphKeys.REGULARIZATION_LOSSES中.這個Tensor儲存了計算正則項損失的方法.

tensorflow中的Tensor是儲存了計算這個值的路徑(方法),當我們run的時候,tensorflow後端就通過路徑計算出Tensor對應的值

現在,我們只需將這個正則項損失加到我們的損失函式上就可以了.

如果是自己手動定義weight的話,需要手動將weight儲存到GraphKeys.WEIGHTS中,但是如果使用layer的話,就不用這麼麻煩了,別人已經幫你考慮好了.(最好自己驗證一下tf.GraphKeys.WEIGHTS中是否包含了所有的weights,防止被坑)

其它

在使用tf.get_variable()tf.variable_scope()的時候,你會發現,它們倆中有regularizer形參.如果傳入這個引數的話,那麼variable_scope內的weights的正則化損失,或者weights的正則化損失就會被新增到GraphKeys.REGULARIZATION_LOSSES中. 
示例:

import tensorflow as tf
from tensorflow.contrib import layers

regularizer = layers.l1_regularizer(0.1)
with tf.variable_scope('var', initializer=tf.random_normal_initializer(), 
regularizer=regularizer):
    weight = tf.get_variable('weight', shape=[8], initializer=tf.ones_initializer())
with tf.variable_scope('var2', initializer=tf.random_normal_initializer(), 
regularizer=regularizer):
    weight2 = tf.get_variable('weight', shape=[8], initializer=tf.ones_initializer())

regularization_loss = tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))

相關推薦

no