请用TensorFlow2构建一个DCGAN模型生成数字图片,包括模型的搭建,编译及训练。
时间: 2024-03-16 22:40:58 浏览: 105
好的,我可以为您提供一个基于TensorFlow2的DCGAN模型生成数字图片的示例代码,包括模型的搭建、编译和训练过程。
首先,我们需要导入所需的库和模块:
```python
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
```
然后,我们需要定义生成器和判别器模型。生成器用于生成合成图像,判别器用于判断输入的图像是真实图像还是合成图像。
```python
# 定义生成器模型
def make_generator_model():
model = tf.keras.Sequential()
model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # 注意:batch size 没有限制
model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)
return model
# 定义判别器模型
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Flatten())
model.add(layers.Dense(1))
return model
```
接下来,我们需要定义损失函数、优化器和辅助函数:
```python
# 定义损失函数
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
# 定义生成器损失函数
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
# 定义判别器损失函数
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
# 定义生成器和判别器优化器
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
# 定义辅助函数,用于生成一些噪声作为输入,并生成合成图像
def generate_and_save_images(model, epoch, test_input):
# 生成图像
predictions = model(test_input, training=False)
# 绘制图像
fig = plt.figure(figsize=(4, 4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
# 保存图像
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
```
然后,我们需要定义训练过程:
```python
# 定义训练过程
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, 100])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
```
接下来,我们需要加载数据集并进行训练:
```python
# 加载数据集
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # 将像素值归一化到 [-1, 1] 区间内
BUFFER_SIZE = 60000
BATCH_SIZE = 256
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
# 定义模型
generator = make_generator_model()
discriminator = make_discriminator_model()
# 训练模型
EPOCHS = 100
num_examples_to_generate = 16
noise_dim = 100
seed = tf.random.normal([num_examples_to_generate, noise_dim])
for epoch in range(EPOCHS):
for image_batch in train_dataset:
train_step(image_batch)
# 生成一些图像并保存
if epoch % 10 == 0:
generate_and_save_images(generator, epoch, seed)
# 生成最终的一些图像并保存
generate_and_save_images(generator, EPOCHS, seed)
```
以上就是基于TensorFlow2的DCGAN模型生成数字图片的示例代码,包括模型的搭建、编译和训练过程。
阅读全文