Читать книгу 120 практических задач онлайн

IMG_HEIGHT = 64

IMG_WIDTH = 64

BATCH_SIZE = 128

BUFFER_SIZE = 60000

def load_image(image_path):

image = tf.io.read_file(image_path)

image = tf.image.decode_jpeg(image, channels=3)

image = tf.image.resize(image, [IMG_HEIGHT, IMG_WIDTH])

image = (image – 127.5) / 127.5 # Нормализация изображений в диапазоне [-1, 1]

return image

def load_dataset(data_dir):

image_paths = [os.path.join(data_dir, img) for img in os.listdir(data_dir)]

image_dataset = tf.data.Dataset.from_tensor_slices(image_paths)

image_dataset = image_dataset.map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)

image_dataset = image_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE).prefetch(tf.data.experimental.AUTOTUNE)

return image_dataset

train_dataset = load_dataset(DATA_DIR)

# Шаг 3: Построение генератора

def build_generator():

model = models.Sequential()

model.add(layers.Dense(8 * 8 * 256, use_bias=False, input_shape=(100,)))

model.add(layers.BatchNormalization())

model.add(layers.LeakyReLU())

model.add(layers.Reshape((8, 8, 256)))

assert model.output_shape == (None, 8, 8, 256) # Убедитесь, что выходная форма такая

model.add(layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same', use_bias=False))

model.add(layers.BatchNormalization())

model.add(layers.LeakyReLU())

assert model.output_shape == (None, 16, 16, 128)

model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))

model.add(layers.BatchNormalization())

model.add(layers.LeakyReLU())

assert model.output_shape == (None, 32, 32, 64)

model.add(layers.Conv2DTranspose(3, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))

assert model.output_shape == (None, 64, 64, 3)

return model

# Шаг 4: Построение дискриминатора

def build_discriminator():

model = models.Sequential()

model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[64, 64, 3]))

model.add(layers.LeakyReLU())

model.add(layers.Dropout(0.3))

model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))