#### 目录

(2条消息) tensorflow零基础入门学习_重邮研究森的博客-CSDN博客_tensorflow 学习 https://blog.csdn.net/m0_60524373/article/details/124143223 https://blog.csdn.net/m0_60524373/article/details/124143223​>- 本文为[365天深度学习训练营](https://mp.weixin.qq.com/s/k-vYaC8l7uxX51WoypLkTw) 中的学习记录博客

## 1.跑通代码

```import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
tf.config.experimental.set_memory_growth(gpus[0], True)  # 设置GPU显存用量按需使用
tf.config.set_visible_devices([gpus[0]], "GPU")
# 打印显卡信息，确认GPU可用
print(gpus)
from tensorflow.keras import layers, datasets, Sequential, Model, optimizers
from tensorflow.keras.layers import LeakyReLU, UpSampling2D, Conv2D
import matplotlib.pyplot as plt
import numpy             as np
import sys,os,pathlib
img_shape  = (28, 28, 1)
latent_dim = 200
def build_generator():
# ======================================= #
#     生成器，输入一串随机数字生成图片
# ======================================= #
model = Sequential([
layers.Dense(256, input_dim=latent_dim),
layers.LeakyReLU(alpha=0.2),  # 高级一点的激活函数
layers.BatchNormalization(momentum=0.8),  # BN 归一化
layers.Dense(512),
layers.LeakyReLU(alpha=0.2),
layers.BatchNormalization(momentum=0.8),
layers.Dense(1024),
layers.LeakyReLU(alpha=0.2),
layers.BatchNormalization(momentum=0.8),
layers.Dense(np.prod(img_shape), activation='tanh'),
layers.Reshape(img_shape)
])
noise = layers.Input(shape=(latent_dim,))
img = model(noise)
return Model(noise, img)
def build_discriminator():
# ===================================== #
#   鉴别器，对输入的图片进行判别真假
# ===================================== #
model = Sequential([
layers.Flatten(input_shape=img_shape),
layers.Dense(512),
layers.LeakyReLU(alpha=0.2),
layers.Dense(256),
layers.LeakyReLU(alpha=0.2),
layers.Dense(1, activation='sigmoid')
])
img = layers.Input(shape=img_shape)
validity = model(img)
return Model(img, validity)
# 创建判别器
discriminator = build_discriminator()
# 定义优化器
discriminator.compile(loss='binary_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
# 创建生成器
generator = build_generator()
gan_input = layers.Input(shape=(latent_dim,))
img = generator(gan_input)
# 在训练generate的时候不训练discriminator
discriminator.trainable = False
# 对生成的假图片进行预测
validity = discriminator(img)
combined = Model(gan_input, validity)
combined.compile(loss='binary_crossentropy', optimizer=optimizer)
def sample_images(epoch):
"""
保存样例图片
"""
row, col = 4, 4
noise = np.random.normal(0, 1, (row*col, latent_dim))
gen_imgs = generator.predict(noise)
fig, axs = plt.subplots(row, col)
cnt = 0
for i in range(row):
for j in range(col):
axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray')
axs[i,j].axis('off')
cnt += 1
fig.savefig("images/%05d.png" % epoch)
# fig.savefig(" E:/2021_Project_YanYiXia/AI/21/对抗网络（GAN）手写数字生成/images/%05d.png" % epoch)
plt.close()
def train(epochs, batch_size=128, sample_interval=50):
# 加载数据
(train_images, _), (_, _) = tf.keras.datasets.mnist.load_data()
# 将图片标准化到 [-1, 1] 区间内
train_images = (train_images - 127.5) / 127.5
# 数据
train_images = np.expand_dims(train_images, axis=3)
# 创建标签
true = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
# 进行循环训练
for epoch in range(epochs):
# 随机选择 batch_size 张图片
idx = np.random.randint(0, train_images.shape[0], batch_size)
imgs = train_images[idx]
# 生成噪音
noise = np.random.normal(0, 1, (batch_size, latent_dim))
# 生成器通过噪音生成图片，gen_imgs的shape为：(128, 28, 28, 1)
gen_imgs = generator.predict(noise)
# 训练鉴别器
d_loss_true = discriminator.train_on_batch(imgs, true)
d_loss_fake = discriminator.train_on_batch(gen_imgs, fake)
# 返回loss值
d_loss = 0.5 * np.add(d_loss_true, d_loss_fake)
# 训练生成器
noise = np.random.normal(0, 1, (batch_size, latent_dim))
g_loss = combined.train_on_batch(noise, true)
print("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100 * d_loss[1], g_loss))
# 保存样例图片
if epoch % sample_interval == 0:
sample_images(epoch)
#train(epochs=30000, batch_size=256, sample_interval=200)
import imageio
def compose_gif():
# 图片地址
data_dir = "E:/2021_Project_YanYiXia/AI/21/对抗网络（GAN）手写数字生成/images"
data_dir = pathlib.Path(data_dir)
paths = list(data_dir.glob('*'))
gif_images = []
for path in paths:
print(path)
imageio.mimsave("test.gif", gif_images, fps=2)
compose_gif()```

## 2.代码分析

1->import

2->设置生成器和判别器

3->创建生成器和判别器

4->训练模型

5->验证

### 2.3

`在训练生成器的时候不训练判别器`

### 2.4

`discriminator.train_on_batch(imgs, true)的意思是，输入为img，输出为true，返回结果为loss`

​ 上面是保存样例图片代码