实例88:构建InfoGAN生成MNIST模拟数据

在MNIST数据集上使用InfoGAN网络模型生活才能模拟数据,并且加入标签的loss函数同时实现AC-GAN网络。其中D和G都是卷积函数来生成,相当于在DCGAN基础上的InfoGAN例子。

实例描述

通过使用InfoGAN网络学习MNIST数据特征,生成以假乱真的MNIST的模拟样本,并发现内部潜在的特征信息。

1.引入头文件并加载MNIST数据

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from scipy.stats import norm
import tensorflow.contrib.slim as slim

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/data/")#, one_hot=True)

2.网络结构介绍

建立两个噪声数据(一般噪声和隐含信息)与label结合放到生成器中,生成模拟样本,然后将模拟样本和真实样本分别输入到判别器中,生成判别结果、重构的隐含信息,以及样本标签。
在优化时,让判别器对真实的样本判别结果为1、对模拟数据的判别结果为0来做损失值计算(loss);对生成器让判别结果过为1来做损失值计算。

3.定义生成器和判别器

先从模拟噪声数据来恢复样本,生成器采用反卷积函数,这里通过两个全连接+两个反卷积模拟样本的生成,并且每一层都有BN处理。

def generator(x):
    
    
    reuse = len([t for t in tf.global_variables() if t.name.startswith('generator')]) > 0
    ##定义生成器的变量域
    with tf.variable_scope('generator', reuse = reuse):
        #全连接层1024
        x = slim.fully_connected(x, 1024)
        x = slim.batch_norm(x, activation_fn=tf.nn.relu)
        
        #全连接成7*7*128
        x = slim.fully_connected(x, 7*7*128)
        x = slim.batch_norm(x, activation_fn=tf.nn.relu)
        x = tf.reshape(x, [-1, 7, 7, 128])
        
        #反卷积层,生成64个
        x = slim.conv2d_transpose(x, 64, kernel_size=[4,4], stride=2, activation_fn = None)
        x = slim.batch_norm(x, activation_fn = tf.nn.relu)
        #反卷积生成一个
        z = slim.conv2d_transpose(x, 1, kernel_size=[4, 4], stride=2, activation_fn=tf.nn.sigmoid)
    return z

def leaky_relu(x):
     return tf.where(tf.greater(x, 0), x, 0.01 * x)

def discriminator(x, num_classes=10, num_cont=2):
    reuse = len([t for t in tf.global_variables() if t.name.startswith('discriminator')]) > 0

    with tf.variable_scope('discriminator', reuse=reuse):
        x = tf.reshape(x, shape=[-1, 28, 28, 1])
        
        #两次卷积
        x = slim.conv2d(x, num_outputs = 64, kernel_size=[4,4], stride=2, activation_fn=leaky_relu)
        x = slim.conv2d(x, num_outputs=128, kernel_size=[4,4], stride=2, activation_fn=leaky_relu)
        x = slim.flatten(x)     #将x扁平化,指保留批次
        
        #全连接
        shared_tensor = slim.fully_connected(x, num_outputs=1024, activation_fn = leaky_relu)
        #全连接
        recog_shared = slim.fully_connected(shared_tensor, num_outputs=128, activation_fn = leaky_relu)
        
        #1维输出层
        disc = slim.fully_connected(shared_tensor, num_outputs=1, activation_fn=None)
        disc = tf.squeeze(disc, -1)     #删除维度为1
        #10维分类
        recog_cat = slim.fully_connected(recog_shared, num_outputs=num_classes, activation_fn=None)
        #2维输出层
        recog_cont = slim.fully_connected(recog_shared, num_outputs=num_cont, activation_fn=tf.nn.sigmoid)
    return disc, recog_cat, recog_cont

如果判别器输入的是真正的样本,同样也要经过两次卷积,两次全连接层,生成的数据可以分别连接不同的输出层产生不同的结果,其中1维的输出层产生的判别结果为1或是0,10维的输出层产生分类结果,2维输出层产生隐含维度信息。

4.定义网络模型

一般噪声维度为38,应节点为z_rand;隐含信息维度为2,应节点为z_con,二者都是符合标准高斯分布的随机数。将他们与one_hot转换后的标签连接在一起放到生成器中。

batch_size = 10   # 获取样本的批次大小32
classes_dim = 10  # 10 classes
con_dim = 2   
rand_dim = 38  
n_input  = 784


x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.int32, [None])

z_con = tf.random_normal((batch_size, con_dim))#2列
z_rand = tf.random_normal((batch_size, rand_dim))#38列
z = tf.concat(axis=1, values=[tf.one_hot(y, depth = classes_dim), z_con, z_rand])#50列
gen = generator(z)
genout= tf.squeeze(gen, -1)


y_real = tf.ones(batch_size) #真
y_fake = tf.zeros(batch_size)#假

# 判别器
disc_real, class_real, _ = discriminator(x)
disc_fake, class_fake, con_fake = discriminator(gen)
pred_class = tf.argmax(class_fake, dimension=1)

5.定义损失函数与优化器

  判别器中,判别结果loss有两个:真实输入结果与模拟输入结果,将两者结合在一起生成loss_d。生成器的loss为自己输出的模拟数据,让其在判断器中为真,生成loss_g。
  定义网络中共有的loss:真实标签与输入真实样本判断的标签、真实的标签与输入模拟熟数据判别的标签、隐含信息的重构误差。
  这里也应用了一个技巧:将判别器的学习率设置的很小,将生成器的学习率设置的大一些。让生成器更快的进化速度来模拟真实数据。

# 判别器 loss
#判断真实输入为真
loss_d_r = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_real, labels=y_real))
#判断模拟输入为假
loss_d_f = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_fake, labels=y_fake))
loss_d = (loss_d_r + loss_d_f) / 2

# 生成器loss
#将生成器的结果不断趋近真
loss_g = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_fake, labels=y_real))

#  共有的loss
#模拟数据标签识别
loss_cf = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=class_fake, labels=y))
#真实数据标签识别
loss_cr = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=class_real, labels=y))
loss_c =(loss_cf + loss_cr) / 2

# 隐含信息loss
loss_con =tf.reduce_mean(tf.square(con_fake-z_con))

# 获得各个网络中各自的训练参数
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if 'discriminator' in var.name]
g_vars = [var for var in t_vars if 'generator' in var.name]


disc_global_step = tf.Variable(0, trainable=False)
gen_global_step = tf.Variable(0, trainable=False)

train_disc = tf.train.AdamOptimizer(0.0001).minimize(loss_d + loss_c + loss_con, var_list = d_vars, global_step = disc_global_step)
train_gen = tf.train.AdamOptimizer(0.001).minimize(loss_g + loss_c + loss_con, var_list = g_vars, global_step = gen_global_step)

  AC-GAN就是将loss_cr加入到loss_c中。没有loss_cr,会损失真实分类与模拟数据之间对应关系。

6.开始训练与测试

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)

        # 遍历全部数据集
        for i in range(total_batch):

            batch_xs, batch_ys = mnist.train.next_batch(batch_size)#取数据
            feeds = {x: batch_xs, y: batch_ys}

            # Fit training using batch data
            l_disc, _, l_d_step = sess.run([loss_d, train_disc, disc_global_step],feeds)
            l_gen, _, l_g_step = sess.run([loss_g, train_gen, gen_global_step],feeds)

        # 显示训练中的详细信息
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f} ".format(l_disc),l_gen)

    print("完成!")
    
    # 测试
    print ("Result:", loss_d.eval({x: mnist.test.images[:batch_size],y:mnist.test.labels[:batch_size]})
                        , loss_g.eval({x: mnist.test.images[:batch_size],y:mnist.test.labels[:batch_size]}))

7.可视化

  可视化部分会生活舱呢个两个图片:原样本对应的模拟数据图片、利用隐含信息生成的模拟样本图片。

  • 原样本与对应的模拟数据图片会将对应的分类、预测分类、隐含信息一起打印出来。
  • 利用隐含信息生成的模拟样本图片会在整个[0,1]空间里均匀抽样,与样本的标签混合在一起,生成模拟数据。
 # 根据图片模拟生成图片
    show_num = 10
    gensimple,d_class,inputx,inputy,con_out = sess.run(
        [genout,pred_class,x,y,con_fake], feed_dict={x: mnist.test.images[:batch_size],y: mnist.test.labels[:batch_size]})

    f, a = plt.subplots(2, 10, figsize=(10, 2))
    for i in range(show_num):
        a[0][i].imshow(np.reshape(inputx[i], (28, 28)))
        a[1][i].imshow(np.reshape(gensimple[i], (28, 28)))
        print("d_class",d_class[i],"inputy",inputy[i],"con_out",con_out[i])
        
    plt.draw()
    plt.show()  
    

    my_con=tf.placeholder(tf.float32, [batch_size,2])
    myz = tf.concat(axis=1, values=[tf.one_hot(y, depth = classes_dim), my_con, z_rand])
    mygen = generator(myz)
    mygenout= tf.squeeze(mygen, -1) 
    
    my_con1 = np.ones([10,2])
    a = np.linspace(0.0001, 0.99999, 10)
    y_input= np.ones([10])
    figure = np.zeros((28 * 10, 28 * 10))
    my_rand = tf.random_normal((10, rand_dim))
    for i in range(10):
        for j in range(10):
            my_con1[j][0]=a[i]
            my_con1[j][1]=a[j]
            y_input[j] = j
        mygenoutv =  sess.run(mygenout,feed_dict={y:y_input,my_con:my_con1})
        for jj in range(10):
            digit = mygenoutv[jj].reshape(28, 28)
            figure[i * 28: (i + 1) * 28,
                   jj * 28: (jj + 1) * 28] = digit
    
    plt.figure(figsize=(10, 10))
    plt.imshow(figure, cmap='Greys_r')
    plt.show() 

在这里插入图片描述

  从上面的结果中,可以很容易观察到,除了可控的类别信息外,隐含信息找某些维度具有非常显著的语义信息。两个维度可能与倾斜和粗细程度。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值