Keras 使用 Lambda 层

from tensorflow.python.keras.models import Sequential, Model
from tensorflow.python.keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout, Conv2DTranspose, Lambda, Input, Reshape, Add, Multiply
from tensorflow.python.keras.optimizers import Adam

def deconv(x):
    height = x.get_shape()[1].value
    width = x.get_shape()[2].value
    
    new_height = height*2
    new_width = width*2
    
    x_resized = tf.image.resize_images(x, [new_height, new_width], tf.image.ResizeMethod.NEAREST_NEIGHBOR)
    
    return x_resized

def Generator(scope='generator'):
    imgs_noise = Input(shape=inputs_shape)
    x = Conv2D(filters=32, kernel_size=(9,9), strides=(1,1), padding='same', activation='relu')(imgs_noise)
    x = Conv2D(filters=64, kernel_size=(3,3), strides=(2,2), padding='same', activation='relu')(x)
    x = Conv2D(filters=128, kernel_size=(3,3), strides=(2,2), padding='same', activation='relu')(x)

    x1 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x)
    x1 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x1)
    x2 = Add()([x1, x])

    x3 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x2)
    x3 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x3)
    x4 = Add()([x3, x2])

    x5 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x4)
    x5 = Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu')(x5)
    x6 = Add()([x5, x4])

    x = MaxPool2D(pool_size=(2,2))(x6)

    x = Lambda(deconv)(x)
    x = Conv2D(filters=64, kernel_size=(3, 3), strides=(1,1), padding='same',activation='relu')(x)
    x = Lambda(deconv)(x)
    x = Conv2D(filters=32, kernel_size=(3, 3), strides=(1,1), padding='same',activation='relu')(x)
    x = Lambda(deconv)(x)
    x = Conv2D(filters=3, kernel_size=(3, 3), strides=(1, 1), padding='same',activation='tanh')(x)

    x = Lambda(lambda x: x+1)(x)
    y = Lambda(lambda x: x*127.5)(x)
    
    model = Model(inputs=imgs_noise, outputs=y)
    model.summary()
    
    return model

my_generator = Generator()
my_generator.compile(loss='binary_crossentropy', optimizer=Adam(0.7, decay=1e-3), metrics=['accuracy'])

 

你可能感兴趣的:(AI学习)