簡體   English   中英

如何只訓練新的舉重?

[英]How do I train only the new weights?

考慮10個單元的(密集)層。 我現在想在此層添加另一個(單個)單元。 但是,如何確保不訓練之前的10個權重,而僅訓練新的10個權重?

您可以將變量列表傳遞給不同的優化器。 一個用於訓練前10個單元,另一個用於與tf.cond()一起訓練另一個單元,因此,當您只想使用10或11個神經元時,可以在圖形中擁有兩個分支。 您還可以使用tf.stop_gradient()這實際上取決於您的用例。

沒有更多的信息,很難回答,但遵循以下方式:

import tensorflow as tf

choose_branch=tf.placeholder(tf.bool)
w_old=tf.Variable(np.random.normal(size=(1,10)).astype("float32"))
b=tf.Variable(np.zeros((1)).astype("float32"))
x=tf.placeholder(tf.float32,size=[None,1])
target=tf.placeholder(tf.float32,size=[None,1])

hidden_old=tf.nn.relu(tf.matmul(x,w_old)+b)

w_proj_old=tf.Variable(np.random.normal(size=(10,1)).astype("float32")

y_old=tf.matmul(hidden_old, w_proj_old)

cost_old=tf.reduce_mean(tf.square(y_old-target))

w_plus=tf.Variable(np.random.normal(size=(1,1)).astype("float32"))
w_proj_plus=tf.Variable(np.random.normal(size=(1,1)).astype("float32")

w_proj_new=tf.concat([w_proj_old,w_proj_plus],axis=1)

w_new=tf.concat([w_old,w_plus],axis=1)
hidden_new=tf.nn.relu(tf.matmul(x,w_new,axis=1))+b))

y_new=tf.matmul(hidden_new, w_proj_new)

cost_new=tf.reduce_mean(tf.square(y_new-target))

opt_old=tf.train.GradientDescentOptimizer(0.001)
opt_new=tf.train.GradientDescentOptimizer(0.0001)

train_step_old=opt_old.minimize(var_list=[w_old,b,w_proj_old,b])
train_step_new=opt_new.minimize(var_list=[w_plus,w_proj_plus])
y=tf.cond(choose_branch,lambda: y_old,lambda: y_new)

小心代碼未經測試。

為了進行這種高級操作,我發現切換到較低的Tensorflow API更容易。

通常將完全連接的層定義為矩陣乘法。 例如,假設您的上一層具有128功能,並且您想要實現一個具有256功能的完全連接的層。 你可以寫

batch_size = 128
num_in = 128
num_out = 256

h = tf.zeros((batch_size, num_in)) # actually, the output of the previous layer

# create the weights for the fully connected layer
w = tf.get_variable('w', shape=(num_in, num_out))
# compute the output
y = tf.matmul(h, w)
# -- feel free to add biases and activation

現在,讓我們假設您已經訓練了w並且想要在此層添加一些額外的神經元。 您可以創建一個包含額外權重的額外變量,並將其與現有變量連接起來。

num_out_extra = 10
# now w is set to trainable=False, we don't want its values to change
w = tf.get_variable('w', shape=(num_in, num_out), trainable=False)
# our new weights
w_extra = tf.get_variable('w_extra', shape=(num_in, num_out_extra))
w_total = tf.concat([w, w_extra], axis=-1)
y = tf.matmul(h, w_total)
# now y has 266 features

當然,您將需要以一種或另一種方式初始化所有權重。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM