tensorflow:3.1)add_to_collection和L2正則化

1.add_to_collection
add_to_collectio爲Graph的一個方法,可以簡單地認爲Graph下維護了一個字典,key爲name,value爲list,而add_to_collection就是把變量添加到對應key下的list中

add_to_collection(name,value)
Stores value in the collection with the given name.
Note that collections are not sets, so it is possible to add a value to a collection several times.
Args:
name: The key for the collection. The GraphKeys class contains many standard names for collections.
value: The value to add to the collection.

下面給出一個簡單的demo,其目的是爲了說明在collection中的變量是對象引用

sess=tf.InteractiveSession()
#初始化2個Variable
v1=tf.Variable(tf.constant(1))
v2=tf.Variable(tf.constant(1))
#設置保存到collection的name爲collection
name='collection'
#把v1和v2添加到默認graph的collection中
tf.add_to_collection(name,v1)
tf.add_to_collection(name,v2)
#獲得名爲name的集合
c1 = tf.get_collection(name)
tf.global_variables_initializer().run()
print("the first collection: %s"%sess.run(c1))
#修改v1和v2的值,必須使用eval()或run()進行執行
tf.assign(v1,tf.constant(3)).eval()
tf.assign(v2,tf.constant(4)).eval()
#再次查看collection中的值
c2 = tf.get_collection(name)
print("the second collection: %s"%sess.run(c2))
print("the sum of collection: %s"%sess.run(tf.add_n(c2))
#resut:
#the first collection: [1, 1]
#the second collection: [3, 4]
#the sum of collection: 7

2.L2正則化
你可以簡單理解L2爲歐式距離,具體如何正則化權重,請參考neural-networks-and-deeplearning,這裏我只進行簡單的介紹。loss0 表示原始的損失函數,後面的部分爲L2正則化。

loss=loss0+λ2ww2

規範化的效果是讓網絡傾向於學習小一點的權重,大的權重只有能夠給出代價函數第一項足夠的提升時才被允許。換言之,規範化可以當做一種尋找小的權重和最小化原始的代價函數之間的折中。這兩部分之前相對的重要性就由的值來控制了λ 越小,就偏向於最小化原始代價函數,反之,傾向於小的權重。

在下一節,因爲要使用L2正則化權重,所以使用collection來保存多個權重向量的L2值,在把它們累加即λ2Σw2

發佈了175 篇原創文章 · 獲贊 202 · 訪問量 63萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章