GAN算法python实现
时间: 2023-09-30 14:06:35 浏览: 128
基于python实现模糊人脸修复模型的部署源码(GFPGAN,Codeformer,GPEN等算法).zip
5星 · 资源好评率100%
GAN是生成式对抗网络(Generative Adversarial Network)的缩写,是一种深度学习的算法。下面是一个简单的GAN算法Python实现示例:
```python
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.layers import Dense, Dropout, Input
from keras.models import Model, Sequential
from keras.optimizers import Adam
# 定义生成器模型
def build_generator():
generator = Sequential()
generator.add(Dense(256, input_dim=100, activation='relu'))
generator.add(Dense(512, activation='relu'))
generator.add(Dense(784, activation='tanh'))
generator.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5))
return generator
# 定义判别器模型
def build_discriminator():
discriminator = Sequential()
discriminator.add(Dense(512, input_dim=784, activation='relu'))
discriminator.add(Dropout(0.3))
discriminator.add(Dense(256, activation='relu'))
discriminator.add(Dropout(0.3))
discriminator.add(Dense(1, activation='sigmoid'))
discriminator.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5))
return discriminator
# 定义GAN模型
def build_gan(generator, discriminator):
discriminator.trainable = False
gan = Sequential()
gan.add(generator)
gan.add(discriminator)
gan.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5))
return gan
# 加载MNIST数据集
(train_data, _), (_, _) = mnist.load_data()
# 数据预处理
train_data = train_data.reshape(train_data.shape[0], 784)
train_data = train_data / 127.5 - 1.
# 定义超参数
epochs = 10000
batch_size = 128
sample_interval = 1000
# 构建GAN模型
generator = build_generator()
discriminator = build_discriminator()
gan = build_gan(generator, discriminator)
# 开始训练
for epoch in range(epochs):
# 训练判别器
idx = np.random.randint(0, train_data.shape[0], batch_size)
real_imgs = train_data[idx]
noise = np.random.normal(0, 1, (batch_size, 100))
fake_imgs = generator.predict(noise)
d_loss_real = discriminator.train_on_batch(real_imgs, np.ones((batch_size, 1)))
d_loss_fake = discriminator.train_on_batch(fake_imgs, np.zeros((batch_size, 1)))
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# 训练生成器
noise = np.random.normal(0, 1, (batch_size, 100))
g_loss = gan.train_on_batch(noise, np.ones((batch_size, 1)))
# 打印训练结果
print("Epoch %d [D loss: %f] [G loss: %f]" % (epoch, d_loss, g_loss))
# 保存生成器的图片
if epoch % sample_interval == 0:
noise = np.random.normal(0, 1, (25, 100))
gen_imgs = generator.predict(noise)
gen_imgs = 0.5 * gen_imgs + 0.5
fig, axs = plt.subplots(5, 5)
cnt = 0
for i in range(5):
for j in range(5):
axs[i,j].imshow(gen_imgs[cnt, :].reshape(28, 28), cmap='gray')
axs[i,j].axis('off')
cnt += 1
fig.savefig("gan_mnist_%d.png" % epoch)
```
该示例代码中,首先定义了一个生成器模型和一个判别器模型,然后通过这两个模型构建出GAN模型。接着加载MNIST数据集,并对数据进行预处理。最后开始训练GAN模型,每隔一定的时间就保存一些生成器生成的图片。
阅读全文