复制特定图层-keras的权重

时间:2018-11-15 07:12:14

标签: python keras neural-network deep-learning keras-layer

根据this,以下将权重从一种模型复制到另一种:

target_model.set_weights(model.get_weights())

复制特定图层的权重该怎么办?

model_1.layers[0].set_weights(source_model.layers[0].get_weights())
model_2.layers[0].set_weights(source_model.layers[0].get_weights())

如果我训练model_1model_2,它们将有不同的权重吗? documentation未声明此get_weights是否进行深拷贝。如果这不起作用,该如何实现?

1 个答案:

答案 0 :(得分:1)

当然,这将是砝码的副本。在两个单独的模型之间共享权重对象没有意义。您可以使用以下简单示例自己检查它:

model1 = Sequential()
model1.add(Dense(10, input_dim=2))

model2 = Sequential()
model2.add(Dense(10, input_dim=2))

model1.compile(loss='mse', optimizer='adam')
model2.compile(loss='mse', optimizer='adam')

测试:

>>> model1.layers[0].get_weights()
[array([[-0.42853734,  0.18648076, -0.47137827,  0.1792168 ,  0.0373047 ,
          0.2765705 ,  0.38383502,  0.09664273, -0.4971757 ,  0.41548246],
        [ 0.0403192 , -0.01309097,  0.6656211 , -0.0536288 ,  0.58677703,
          0.21625364,  0.26447064, -0.42619988,  0.17218047, -0.39748642]],
       dtype=float32),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)]

>>> model2.layers[0].get_weights()
[array([[-0.30062824, -0.3740575 , -0.3502644 ,  0.28050178, -0.68631136,
          0.1596322 ,  0.08288956, -0.20988202,  0.34323698,  0.2893324 ],
        [-0.29182747, -0.2754455 , -0.64082885,  0.29160154,  0.04342002,
         -0.4996035 ,  0.6608283 ,  0.10293472,  0.11375248, -0.43438092]],
       dtype=float32),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)]

>>> model2.layers[0].set_weights(model1.layers[0].get_weights())
>>> model2.layers[0].get_weights()
[array([[-0.42853734,  0.18648076, -0.47137827,  0.1792168 ,  0.0373047 ,
          0.2765705 ,  0.38383502,  0.09664273, -0.4971757 ,  0.41548246],
        [ 0.0403192 , -0.01309097,  0.6656211 , -0.0536288 ,  0.58677703,
          0.21625364,  0.26447064, -0.42619988,  0.17218047, -0.39748642]],
       dtype=float32),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)]

>>> id(model1.layers[0].get_weights()[0])
140494823634144

>>> id(model2.layers[0].get_weights()[0])
140494823635664

内核权重数组的id不同,因此它们是不同的对象,但具有相同的值。