我用下面的例子来说明我的问题:
class Encoder(K.layers.Layer):
def __init__(self, filters):
super(Encoder, self).__init__()
self.conv1 = Conv2D(filters=filters[0], kernel_size=3, strides=1, activation='relu', padding='same')
self.conv2 = Conv2D(filters=filters[1], kernel_size=3, strides=1, activation='relu', padding='same')
self.conv3 = Conv2D(filters=filters[2], kernel_size=3, strides=1, activation='relu', padding='same')
self.pool = MaxPooling2D((2, 2), padding='same')
def call(self, input_features):
x = self.conv1(input_features)
#print("Ex1", x.shape)
x = self.pool(x)
#print("Ex2", x.shape)
x = self.conv2(x)
x = self.pool(x)
x = self.conv3(x)
x = self.pool(x)
return x
class Decoder(K.layers.Layer):
def __init__(self, filters):
super(Decoder, self).__init__()
self.conv1 = Conv2D(filters=filters[2], kernel_size=3, strides=1, activation='relu', padding='same')
self.conv2 = Conv2D(filters=filters[1], kernel_size=3, strides=1, activation='relu', padding='same')
self.conv3 = Conv2D(filters=filters[0], kernel_size=3, strides=1, activation='relu', padding='valid')
self.conv4 = Conv2D(1, 3, 1, activation='sigmoid', padding='same')
self.upsample = UpSampling2D((2, 2))
def call(self, encoded):
x = self.conv1(encoded)
print("dx1", x.shape)
x = self.upsample(x)
#print("dx2", x.shape)
x = self.conv2(x)
x = self.upsample(x)
x = self.conv3(x)
x = self.upsample(x)
return self.conv4(x)
class Autoencoder(K.Model):
def __init__(self, filters):
super(Autoencoder, self).__init__()
self.loss = []
self.encoder = Encoder(filters)
self.decoder = Decoder(filters)
def call(self, input_features):
#print(input_features.shape)
encoded = self.encoder(input_features)
#print(encoded.shape)
reconstructed = self.decoder(encoded)
#print(reconstructed.shape)
return reconstructed
max_epochs = 5
model = Autoencoder(filters)
model.compile(loss='binary_crossentropy', optimizer='adam')
loss = model.fit(x_train_noisy,
x_train,
validation_data=(x_test_noisy, x_test),
epochs=max_epochs,
batch_size=batch_size)
正如你所看到的,model
是使用keras.Layer中的一些层创建的,那么如果我想使用model.summary()
函数来显示模型的架构,我将有:
Model: "autoencoder"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
encoder (Encoder) multiple 14192
decoder (Decoder) multiple 16497
=================================================================
Total params: 30,689
Trainable params: 30,689
Non-trainable params: 0
对我来说,我想有一个更详细的描述编码器层和解码器层。有什么想法吗
1条答案
按热度按时间km0tfn4u1#
之所以会得到这样的输出是因为使用了子类API来构建模型。众所周知,与顺序或函数API不同,子类API不允许您构建模型摘要或绘图函数。这里有两个非常相关的职位存在。
但是,在您的情况下,您可能需要更改设置以使
summary
和plot_model
有用。那些是1.子类
keras.Model
而不是编码器和解码器子组件的keras.layers.Layer
。1.在
init
方法中初始化图层时,请确保这些图层的顺序与call
方法的顺序相同。编码器
在上面的1和2之后。
解码器
在上面的1和2之后。
自动编码器
由于上面的1和2,我们将如下构建自动编码器。
构建模型
很好。但是正如您所看到的,在摘要中,
Output Shape
列没有提供信息。为了解决这个问题,我们可以使用一个类方法(build_graph
),如下所示:摘要
就是这样。但是,如果你认为这应该是开箱即用的支持,请随时在keras-github中打开ticket。