人工智能导论实验生成对抗网络
时间: 2023-12-14 09:34:13 浏览: 175
生成对抗网络(GAN)是一种深度学习模型,由两个神经网络组成:生成器和判别器。生成器试图生成与真实数据相似的数据,而判别器则试图区分生成的数据和真实数据。这两个网络相互竞争,直到生成器生成的数据足够逼真,以至于判别器无法区分真实数据和生成的数据。
下面是一个简单的GAN实现,用于生成手写数字图像:
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
# 定义生成器
def generator(z, reuse=None):
with tf.variable_scope('gen', reuse=reuse):
hidden1 = tf.layers.dense(inputs=z, units=128)
alpha = 0.01
hidden1 = tf.maximum(alpha * hidden1, hidden1)
hidden2 = tf.layers.dense(inputs=hidden1, units=128)
hidden2 = tf.maximum(alpha * hidden2, hidden2)
output = tf.layers.dense(inputs=hidden2, units=784, activation=tf.nn.tanh)
return output
# 定义判别器
def discriminator(X, reuse=None):
with tf.variable_scope('dis', reuse=reuse):
hidden1 = tf.layers.dense(inputs=X, units=128)
alpha = 0.01
hidden1 = tf.maximum(alpha * hidden1, hidden1)
hidden2 = tf.layers.dense(inputs=hidden1, units=128)
hidden2 = tf.maximum(alpha * hidden2, hidden2)
logits = tf.layers.dense(hidden2, units=1)
output = tf.sigmoid(logits)
return output, logits
# 定义损失函数
def loss_func(logits_in, labels_in):
return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits_in, labels=labels_in))
# 定义placeholder
real_images = tf.placeholder(tf.float32, shape=[None, 784])
z = tf.placeholder(tf.float32, shape=[None, 100])
# 生成器生成的图像
G = generator(z)
# 判别器判断真实图像
_output_real, D_logits_real = discriminator(real_images)
# 判别器判断生成图像
D_output_fake, D_logits_fake = discriminator(G, reuse=True)
# 定义损失函数
D_real_loss = loss_func(D_logits_real, tf.ones_like(D_logits_real) * 0.9)
D_fake_loss = loss_func(D_logits_fake, tf.zeros_like(D_logits_real))
D_loss = D_real_loss + D_fake_loss
G_loss = loss_func(D_logits_fake, tf.ones_like(D_logits_fake))
# 定义优化器
learning_rate = 0.001
tvars = tf.trainable_variables()
d_vars = [var for var in tvars if 'dis' in var.name]
g_vars = [var for var in tvars if 'gen' in var.name]
D_trainer = tf.train.AdamOptimizer(learning_rate).minimize(D_loss, var_list=d_vars)
G_trainer = tf.train.AdamOptimizer(learning_rate).minimize(G_loss, var_list=g_vars)
# 加载MNIST数据集
mnist = input_data.read_data_sets("MNIST_data/")
# 定义训练参数
batch_size = 100
epochs = 100
init = tf.global_variables_initializer()
# 开始训练
samples = []
with tf.Session() as sess:
sess.run(init)
for epoch in range(epochs):
for i in range(mnist.train.num_examples // batch_size):
batch = mnist.train.next_batch(batch_size)
batch_images = batch[0].reshape((batch_size, 784))
batch_images = batch_images * 2 - 1
batch_z = np.random.uniform(-1, 1, size=(batch_size, 100))
_ = sess.run(D_trainer, feed_dict={real_images: batch_images, z: batch_z})
_ = sess.run(G_trainer, feed_dict={z: batch_z})
# 每个epoch结束后,输出损失函数和生成的图像
print("Epoch:", epoch, "D loss:", sess.run(D_loss, feed_dict={real_images: batch_images, z: batch_z}),
"G loss:", sess.run(G_loss, feed_dict={z: batch_z}))
sample_z = np.random.uniform(-1, 1, size=(1, 100))
gen_sample = sess.run(generator(z, reuse=True), feed_dict={z: sample_z})
samples.append(gen_sample)
# 输出生成的图像
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=10, ncols=10, sharex=True, sharey=True, figsize=(20, 20))
for i in range(10):
for j in range(10):
axes[i, j].imshow(samples[(i * 10) + j][0].reshape((28, 28)), cmap='Greys_r')
plt.show()
```
阅读全文