设置Keras模型中层堆栈的权重?



我使用Keras模型类,并且有顺序层的堆栈,并且想知道如何访问堆栈中的层来设置它们的权重。

class sho_Model(tf.keras.Model):
def __init__(self):
super(sho_Model, self).__init__()
self.hidden_x1 = keras.models.Sequential(layers=[
Conv1D(filters=8, kernel_size=7, activation=selu, input_shape=(1, 80, 2)),
Conv1D(filters=6, kernel_size=7, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu)                              
])
self.hidden_xfc = keras.models.Sequential(layers=[
Dense(20, activation=selu),
Dense(20, activation=selu)
])
self.hidden_x2 = keras.models.Sequential(layers=[
MaxPool1D(pool_size=2),
Conv1D(filters=4, kernel_size=5, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu),
Conv1D(filters=4, kernel_size=5, activation=selu),
AveragePooling1D(pool_size=2),
Conv1D(filters=2, kernel_size=3, activation=selu),
AveragePooling1D(pool_size=2),
Conv1D(filters=2, kernel_size=3, activation=selu),
AveragePooling1D(pool_size=2)
])
self.hidden_encoded = Flatten()
self.hidden_embedding = keras.models.Sequential(layers=[ 
Dense(16, activation=selu),
Dense(8, activation=selu),
Dense(4) 
])

def call(self, inputs, n=-1):
x = K.permute_dimensions(inputs, (2, 1))
x = self.hidden_x1(x)
xfc = K.reshape(x, (n, 256))
xfc = self.hidden_xfc(xfc)
x = K.reshape(x, (n, 2, 128))
x = self.hidden_x2(x)
encoded = self.hidden_encoded(x)
encoded = K.concatenate((encoded, xfc), 1)
embedding = self.hidden_embedding(encoded)
return embedding

我有一个类似

的东西
curr_layer = 0
for layer in keras_model.layers:
layer.set_weights(...)
curr_layer+=1

,但这只是访问顺序容器(正确的术语?),而不是单个层。

既然已经定义了那些顺序的"容器";作为单独的层,您可以使用多级for循环来遍历各个层:

curr_layer = 0
for container in keras_model.layers:
if container.name.startswith('flatten'):
# Skip the flatten layer
continue
for layer in container.layers:
layer.set_weights(...)
curr_layer += 1

如果要保存和恢复先前训练模型的权值,更简单的方法是使用savesave_weights方法使用load_weightstf.keras.models.load_model方法保存和恢复权值。

相关内容

  • 没有找到相关文章

最新更新