【问题标题】:How to freeze selected weights in keras or tf.keras?如何在 keras 或 tf.keras 中冻结选定的权重?
【发布时间】:2020-01-03 12:04:14
【问题描述】:

我正在尝试一些需要冻结某些选定权重的东西。举个例子

from keras.models import Sequential
from keras.layers import Dense,Input

model = Sequential()
model.add(Dense(4, input_shape=(4,),activation='relu'))
model.add(Dense(3,name="hidden",activation='relu'))
model.add(Dense(2,activation='sigmoid'))
model.compile(loss='mse', optimizer='adam')

print(model.layers[1].get_weights()[0])

这会将输入打印到隐藏层权重。

# Weights input x hidden
# Freeze 2Rx3C and 4Rx2C
# 2Rx3C=0.14362943; 4Rx2C=-0.23868048
array([[-0.05557871,  0.10941017, -0.59108734],
       [ 0.37056673,  0.2968588 ,  0.14362943],
       [-0.05471832, -0.21425706,  0.6455065 ],
       [-0.7883829 , -0.23868048, -0.517396  ]], dtype=float32)

根据这个权重矩阵,我想冻结(2nd Row, 3rd Column)(4th Row, 2nd Column) 中的值,即分别为0.14362943-0.23868048。我不想在反向传播上更新这些值。如何冻结这些选定的权重?

【问题讨论】:

  • 嗨,艾卡。答案能解决你的问题吗?

标签: tensorflow keras keras-layer tf.keras keras-2


【解决方案1】:

你需要使用tf.identity,当你想在设备之间显式传输张量时使用它。

matrixVariable = tf.Variable(<your matrix>)
matrixVariableSliced = matrixVariable[<sliced matrix>] #take out your required weights
matrixVariable_stop = tf.stop_gradient(tf.identity(matrixVariableSliced)) 
matrixVariable = tf.concat((matrixVariableSliced, matrixVariable_stop), axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2018-04-26
    • 2020-01-28
    • 2021-10-28
    • 1970-01-01
    相关资源
    最近更新 更多