以下是GAN示例代码:
import argparse # argparse是python用于解析命令行参数和选项的标准模块
import numpy as np
from scipy.stats import norm
import tensorflow as tf
import matplotlib.pyplot as plt
from matplotlib import animation
import seaborn as sns
sns.set(color_codes=True) # set( )通过设置参数可以用来设置背景,调色板等,更加常用。
seed = 42
np.random.seed(seed)
tf.set_random_seed(seed)
class DataDistribution(object):
def __init__(self):
self.mu = 4 # 均值
self.sigma = 0.5 # 方差
def sample(self, N):
samples = np.random.normal(self.mu, self.sigma, N)
samples.sort() # 从小到大排序
return samples
class GeneratorDistribution(object):
def __init__(self, range):
self.range = range
def sample(self, N):
return np.linspace(-self.range, self.range, N) + \
np.random.random(N) * 0.01
def linear(input, output_dim, scope=None, stddev=1.0):
norm = tf.random_normal_initializer(stddev=stddev)
const = tf.constant_initializer(0.0)
with tf.variable_scope(scope or 'linear'):
w = tf.get_variable('w', [input.get_shape()[1], output_dim], initializer=norm)
b = tf.get_variable('b', [output_dim], initializer=const)
return tf.matmul(input, w) + b
def generator(input, h_dim):
h0 = tf.nn.softplus(linear(input, h_dim, 'g0'))
h1 = linear(h0, 1, 'g1')
return h1
def discriminator(input, h_dim):
h0 = tf.tanh(linear(input, h_dim * 2, 'd0'))
h1 = tf.tanh(linear(h0, h_dim * 2, 'd1'))
h2 = tf.tanh(linear(h1, h_dim * 2, scope='d2'))
h3 = tf.sigmoid(linear(h2, 1, scope='d3'))
return h3
def optimizer(loss, var_list, initial_learning_rate):
decay = 0.95
num_decay_steps = 150
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
initial_learning_rate,
batch,
num_decay_steps,
decay,
staircase=True
)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(
loss,
global_step=batch,
var_list=var_list
)
return optimizer
class GAN(object):
def __init__(self, data, gen, num_steps, batch_size, log_every):
self.data = data
self.gen = gen
self.num_steps = num_steps
self.batch_size = batch_size
self.log_every = log_every # 每log_every次打印一次loss
self.mlp_hidden_size = 4
self.learning_rate = 0.03
self._create_model()
def _create_model(self):
with tf.variable_scope('D_pre'):
self.pre_input = tf.placeholder(tf.float32, shape=(self.batch_size, 1))
self.pre_labels = tf.placeholder(tf.float32, shape=(self.batch_size, 1))
D_pre = discriminator(self.pre_input, self.mlp_hidden_size)
self.pre_loss = tf.reduce_mean(tf.square(D_pre - self.pre_labels))
self.pre_opt = optimizer(self.pre_loss, None, self.learning_rate)
# This defines the generator network - it takes samples from a noise
# distribution as input, and passes them through an MLP.
with tf.variable_scope('Gen'):
self.z = tf.placeholder(tf.float32, shape=(self.batch_size, 1))
self.G = generator(self.z, self.mlp_hidden_size)
# The discriminator tries to tell the difference between samples from the
# true data distribution (self.x) and the generated samples (self.z).
#
# Here we create two copies of the discriminator network (that share parameters),
# as you cannot use the same network with different inputs in TensorFlow.
with tf.variable_scope('Disc') as scope:
self.x = tf.placeholder(tf.float32, shape=(self.batch_size, 1))
self.D1 = discriminator(self.x, self.mlp_hidden_size)
scope.reuse_variables()
self.D2 = discriminator(self.G, self.mlp_hidden_size)
# Define the loss for discriminator and generator networks (see the original
# paper for details), and create optimizers for both
self.loss_d = tf.reduce_mean(-tf.log(self.D1) - tf.log(1 - self.D2))
self.loss_g = tf.reduce_mean(-tf.log(self.D2))
self.d_pre_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='D_pre')
self.d_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Disc')
self.g_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='Gen')
self.opt_d = optimizer(self.loss_d, self.d_params, self.learning_rate)
self.opt_g = optimizer(self.loss_g, self.g_params, self.learning_rate)
def train(self):
with tf.Session() as session:
tf.global_variables_initializer().run()
# pretraining discriminator
num_pretrain_steps = 1000
for step in range(num_pretrain_steps):
d = (np.random.random(self.batch_size) - 0.5) * 10.0
labels = norm.pdf(d, loc=self.data.mu, scale=self.data.sigma)
pretrain_loss, _ = session.run([self.pre_loss, self.pre_opt], {
self.pre_input: np.reshape(d, (self.batch_size, 1)),
self.pre_labels: np.reshape(labels, (self.batch_size, 1))
})
self.weightsD = session.run(self.d_pre_params)
# copy weights from pre-training over to new D network
for i, v in enumerate(self.d_params):
session.run(v.assign(self.weightsD[i]))
for step in range(self.num_steps):
# update discriminator
x = self.data.sample(self.batch_size)
z = self.gen.sample(self.batch_size)
loss_d, _ = session.run([self.loss_d, self.opt_d], {
self.x: np.reshape(x, (self.batch_size, 1)),
self.z: np.reshape(z, (self.batch_size, 1))
})
# update generator
z = self.gen.sample(self.batch_size)
loss_g, _ = session.run([self.loss_g, self.opt_g], {
self.z: np.reshape(z, (self.batch_size, 1))
})
if step % self.log_every == 0:
print('{}: {}\t{}'.format(step, loss_d, loss_g))
if step % 100 == 0 or step==0 or step == self.num_steps -1 :
self._plot_distributions(session)
def _samples(self, session, num_points=10000, num_bins=100):
xs = np.linspace(-self.gen.range, self.gen.range, num_points)
bins = np.linspace(-self.gen.range, self.gen.range, num_bins)
# data distribution
d = self.data.sample(num_points)
pd, _ = np.histogram(d, bins=bins, density=True)
# generated samples
zs = np.linspace(-self.gen.range, self.gen.range, num_points)
g = np.zeros((num_points, 1))
for i in range(num_points // self.batch_size):
g[self.batch_size * i:self.batch_size * (i + 1)] = session.run(self.G, {
self.z: np.reshape(
zs[self.batch_size * i:self.batch_size * (i + 1)],
(self.batch_size, 1)
)
})
pg, _ = np.histogram(g, bins=bins, density=True)
return pd, pg
def _plot_distributions(self, session):
pd, pg = self._samples(session)
p_x = np.linspace(-self.gen.range, self.gen.range, len(pd))
f, ax = plt.subplots(1)
ax.set_ylim(0, 1)
plt.plot(p_x, pd, label='real data')
plt.plot(p_x, pg, label='generated data')
plt.title('1D Generative Adversarial Network')
plt.xlabel('Data values')
plt.ylabel('Probability density')
plt.legend()
plt.show()
def main(args):
model = GAN(
DataDistribution(), # 真实数据
GeneratorDistribution(range=8),
args.num_steps,
args.batch_size,
args.log_every,
)
model.train()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--num-steps', type=int, default=1200,
help='the number of training steps to take')
parser.add_argument('--batch-size', type=int, default=12,
help='the batch size')
parser.add_argument('--log-every', type=int, default=10,
help='print loss after this many steps')
return parser.parse_args()
if __name__ == '__main__':
main(parse_args())
解析模块:
import argparse
使用步骤:
1. import argparse
2. parser = argparse.ArgumentParser()
3. parser.add_argument('--num-steps', type=int, default=1200,
help='the number of training steps to take')
parser.add_argument('--batch-size', type=int, default=12,
help='the batch size')
parser.add_argument('--log-every', type=int, default=10,
help='print loss after this many steps')
4. parser.parse_args()
name or flags:命令行参数名或者选项。其中命令行参数如果没给定,且没有设置defualt,则出错。但是如果是选项的话,则设置为None;
nargs:命令行参数的个数,一般使用通配符表示,其中,'?'表示只用一个,'*'表示0到多个,'+'表示至少一个;
default:默认值;
type:参数的类型,默认是字符串string类型,还有float、int等类型;
help:和ArgumentParser方法中的参数作用相似,出现的场合也一致;
函数部分:
tf.set_random_seed(seed)
设置图级随机seed。
依赖于随机seed的操作实际上从两个seed中获取:图级和操作级seed。 这将设置图级别的seed。
其与操作级seed的相互作用如下:
1.如果没有设置图形级别和操作seed,则使用随机seed进行操作。
2.如果设置了图级seed,但操作seed没有设置:系统确定性地选择与图级seed一起的操作seed,以便获得唯一的随机序列。
3.如果没有设置图级seed,但是设置了操作seed:使用默认的图级seed和指定的操作seed来确定随机序列。
4.如果图级和操作seed都被设置:两个seed联合使用以确定随机序列。
示例可以参考网址:http://blog.csdn.net/eml_jw/article/details/72353470
tf.random_normal_initializer(mean=0.0, stddev=1.0, seed=None, dtype=tf.float32)
返回一个生成具有正态分布的张量的初始化器。
参数:
mean:python标量或标量tensor,产生的随机值的平均值。
stddev:一个python标量或一个标量tensor,标准偏差的随机值生成
seed:一个Python整数。 用于创建随机seed有关行为,请参阅API:set_random_seed。
dtype:数据类型, 只支持浮点类型。
函数返回:产生具有正态分布的张量的初始化器。
tf.variable_scope()
参考网址:http://blog.csdn.net/eml_jw/article/details/72408306
python中list()与numpy中的array的转换:
示例:
a=([1.2 , 34, 3.7, 6.3])
a为python的list类型
将a转化为numpy的array:
np.array(a)
array([ 1.2 , 34. , 3.7, 6.3 ])
将a转化为python的list
a.tolist()
关于学习率更新:
这里使用的是指数衰减学习率法;
在Tensorflow中,为解决设定学习率(learning rate)问题,提供了指数衰减法来解决。
通过tf.train.exponential_decay函数实现指数衰减学习率。
步骤:1.首先使用较大学习率(目的:为快速得到一个比较优的解);
2.然后通过迭代逐步减小学习率(目的:为使模型在训练后期更加稳定);
实现的函数公式为:
decayed_learning_rate=learining_rate*decay_rate^(global_step/decay_steps)
实现步骤为:
global_step = tf.Variable(0)
#生成学习率
learning_rate = tf.train.exponential_decay(initial_learning_rate, global_step, num_decay_steps, decay_rate, staircase=True)
#使用指数衰减学习率
learning_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(....., global_step=global_step)
learning_rate
: 初始的
learning rate
global_step
: 全局的step,与
decay_step
和
decay_rate
一起决定了
learning rate
的变化。
staircase
: 如果为 True
global_step/decay_step
向下取整
管理计算图等资源:
TensorFlow 还提供了管理 Tensor 和计算的机制,计算图可以通过 tf.Graph.device 函数来指定运行计算的设备。下面程序将加法计算放在 GPU 上执行。
TensorFlow 可以通过集合 (collection) 来管理不同类别的资源。
例如使用 tf.add_to_collection 函数可以将资源加入一个或多个集合。
使用 tf.get_collection 获取一个集合里面的所有资源。这些资源可以是张量 / 变量或者运行 Tensorflow 程序所需要的资源。
(在神经网络的训练中会大量使用集合管理技术)
集合名称 | 集合内容 | 使用场景 |
---|---|---|
tf.GraphKeys.GLOBAL_VARIABLES | 所有变量 | 持久化 Tensorflow 模型 |
tf.GraphKeys.TRAINABLE_VARIABLES | 可学习的变量 (神经网络的参数) | 模型训练 / 生成模型可视化内容 |
tf.GraphKeys.SUMMARIES | 日志生成相关的张量 | Tensorflow 计算可视化 |
tf.GraphKeys.QUEUE_RUNNERS | 处理输入的 QueueRunner | 输入处理 |
tf.GraphKeys.MOVING_AVERAGE_VARIABLES | 所有计算了滑动平均值的变量 | 计算变量的滑动平均值 |