gan python实现
时间: 2023-07-07 19:40:22 浏览: 83
GAN是生成式对抗网络(Generative Adversarial Networks)的缩写,是一种用于生成模拟数据的机器学习模型。下面是一个简单的GAN Python实现示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Dense, Input
from keras.models import Model
from keras.optimizers import Adam
# 生成器模型
def build_generator(latent_dim):
inputs = Input(shape=(latent_dim,))
x = Dense(128, activation='relu')(inputs)
x = Dense(256, activation='relu')(x)
x = Dense(512, activation='relu')(x)
outputs = Dense(784, activation='sigmoid')(x)
model = Model(inputs=inputs, outputs=outputs)
return model
# 判别器模型
def build_discriminator():
inputs = Input(shape=(784,))
x = Dense(512, activation='relu')(inputs)
x = Dense(256, activation='relu')(x)
x = Dense(128, activation='relu')(x)
outputs = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inputs, outputs=outputs)
return model
# GAN模型
def build_gan(generator, discriminator):
discriminator.trainable = False
inputs = Input(shape=(100,))
gan_outputs = discriminator(generator(inputs))
model = Model(inputs=inputs, outputs=gan_outputs)
model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5))
return model
# 加载数据集
(X_train, _), (_, _) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], 784)
X_train = X_train.astype('float32') / 255
# 构建模型
generator = build_generator(100)
discriminator = build_discriminator()
gan = build_gan(generator, discriminator)
# 训练GAN模型
for epoch in range(1000):
noise = np.random.normal(0, 1, (100,)) # 生成噪声
fake_images = generator.predict(noise) # 生成假图片
real_images = X_train[np.random.randint(0, X_train.shape[0], size=100)] # 从真实数据集中随机取出100张图片
# 训练判别器
discriminator.trainable = True
discriminator.train_on_batch(real_images, np.ones((100,)))
discriminator.train_on_batch(fake_images, np.zeros((100,)))
# 训练生成器
noise = np.random.normal(0, 1, (100,))
discriminator.trainable = False
gan.train_on_batch(noise, np.ones((100,)))
# 每100轮输出一次生成的图片
if epoch % 100 == 0:
print('Epoch %d' % epoch)
plt.imshow(fake_images[0].reshape(28, 28), cmap='gray')
plt.show()
```
以上是一个基本的GAN Python实现示例,它使用了Keras深度学习框架和MNIST手写数字数据集来生成手写数字图像。该示例中的生成器和判别器模型都是基于全连接层的简单模型,可以根据需求进行更改和优化。
阅读全文