前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >tensorflow 实现wgan-gp mnist图片生成

tensorflow 实现wgan-gp mnist图片生成

作者头像
DoubleV
发布于 2018-09-12 07:09:40
发布于 2018-09-12 07:09:40
1.6K00
代码可运行
举报
文章被收录于专栏:GAN&CVGAN&CV
运行总次数:0
代码可运行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25737169/article/details/76695935

生成对抗网络GAN目前在图片生成以及对抗训练上取得了非常好的应用,本文旨在做一个简单的tf wgan-gp mnist 生成教程,所使用的代码非常简单,希望和大家共同学习。代码如下: 所使用的环境: tensorflow 1.2.0 GPU加速,CPU上也是可以的,就是很慢,可以把batchsize改小,用cpu好训练一些,顺便把生成图像代码处改一下,我的batchsize64,save_images的参数是[8,8],如果batchsize=16,就改为[4,4]

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#coding:utf-8
import os
import numpy as np
import scipy.misc
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data #as mnist_data

def conv2d(name, tensor,ksize, out_dim, stddev=0.01, stride=2, padding='SAME'):
    with tf.variable_scope(name):
        w = tf.get_variable('w', [ksize, ksize, tensor.get_shape()[-1],out_dim], dtype=tf.float32,
                            initializer=tf.random_normal_initializer(stddev=stddev))
        var = tf.nn.conv2d(tensor,w,[1,stride, stride,1],padding=padding)
        b = tf.get_variable('b', [out_dim], 'float32',initializer=tf.constant_initializer(0.01))
        return tf.nn.bias_add(var, b)

def deconv2d(name, tensor, ksize, outshape, stddev=0.01, stride=2, padding='SAME'):
    with tf.variable_scope(name):
        w = tf.get_variable('w', [ksize, ksize, outshape[-1], tensor.get_shape()[-1]], dtype=tf.float32,
                            initializer=tf.random_normal_initializer(stddev=stddev))
        var = tf.nn.conv2d_transpose(tensor, w, outshape, strides=[1, stride, stride, 1], padding=padding)
        b = tf.get_variable('b', [outshape[-1]], 'float32', initializer=tf.constant_initializer(0.01))
        return tf.nn.bias_add(var, b)

def fully_connected(name,value, output_shape):
    with tf.variable_scope(name, reuse=None) as scope:
        shape = value.get_shape().as_list()
        w = tf.get_variable('w', [shape[1], output_shape], dtype=tf.float32,
                                    initializer=tf.random_normal_initializer(stddev=0.01))
        b = tf.get_variable('b', [output_shape], dtype=tf.float32, initializer=tf.constant_initializer(0.0))

        return tf.matmul(value, w) + b

def relu(name, tensor):
    return tf.nn.relu(tensor, name)

def lrelu(name,x, leak=0.2):
    return tf.maximum(x, leak * x, name=name)


DEPTH = 28
OUTPUT_SIZE = 28
batch_size = 64
def Discriminator(name,inputs,reuse):
    with tf.variable_scope(name, reuse=reuse):
        output = tf.reshape(inputs, [-1, 28, 28, 1])
        output1 = conv2d('d_conv_1', output, ksize=5, out_dim=DEPTH)
        output2 = lrelu('d_lrelu_1', output1)

        output3 = conv2d('d_conv_2', output2, ksize=5, out_dim=2*DEPTH)
        output4 = lrelu('d_lrelu_2', output3)

        output5 = conv2d('d_conv_3', output4, ksize=5, out_dim=4*DEPTH)
        output6 = lrelu('d_lrelu_3', output5)

        # output7 = conv2d('d_conv_4', output6, ksize=5, out_dim=8*DEPTH)
        # output8 = lrelu('d_lrelu_4', output7)

        chanel = output6.get_shape().as_list()
        output9 = tf.reshape(output6, [batch_size, chanel[1]*chanel[2]*chanel[3]])
        output0 = fully_connected('d_fc', output9, 1)
        return output0


def generator(name, reuse=False):
    with tf.variable_scope(name, reuse=reuse):
        noise = tf.random_normal([batch_size, 128])#.astype('float32')

        noise = tf.reshape(noise, [batch_size, 128], 'noise')
        output = fully_connected('g_fc_1', noise, 2*2*8*DEPTH)
        output = tf.reshape(output, [batch_size, 2, 2, 8*DEPTH], 'g_conv')

        output = deconv2d('g_deconv_1', output, ksize=5, outshape=[batch_size, 4, 4, 4*DEPTH])
        output = tf.nn.relu(output)
        output = tf.reshape(output, [batch_size, 4, 4, 4*DEPTH])

        output = deconv2d('g_deconv_2', output, ksize=5, outshape=[batch_size, 7, 7, 2* DEPTH])
        output = tf.nn.relu(output)

        output = deconv2d('g_deconv_3', output, ksize=5, outshape=[batch_size, 14, 14, DEPTH])
        output = tf.nn.relu(output)

        output = deconv2d('g_deconv_4', output, ksize=5, outshape=[batch_size, OUTPUT_SIZE, OUTPUT_SIZE, 1])
        # output = tf.nn.relu(output)
        output = tf.nn.sigmoid(output)
        return tf.reshape(output,[-1,784])


def save_images(images, size, path):
    # 图片归一化
    img = (images + 1.0) / 2.0
    h, w = img.shape[1], img.shape[2]
    merge_img = np.zeros((h * size[0], w * size[1], 3))
    for idx, image in enumerate(images):
        i = idx % size[1]
        j = idx // size[1]
        merge_img[j * h:j * h + h, i * w:i * w + w, :] = image
    return scipy.misc.imsave(path, merge_img)


LAMBDA = 10
EPOCH = 40
def train():
    # print  os.getcwd()
    with tf.variable_scope(tf.get_variable_scope()):
        # real_data = tf.placeholder(dtype=tf.float32, shape=[-1, OUTPUT_SIZE*OUTPUT_SIZE*3])
        path = os.getcwd()
        data_dir = path + "/train.tfrecords"#准备使用自己的数据集
        # print data_dir
        '''获得数据'''
        z = tf.placeholder(dtype=tf.float32, shape=[batch_size, 100])#build placeholder
        real_data = tf.placeholder(tf.float32, shape=[batch_size,784])

        with tf.variable_scope(tf.get_variable_scope()):
            fake_data = generator('gen',reuse=False)
            disc_real = Discriminator('dis_r',real_data,reuse=False)
            disc_fake = Discriminator('dis_r',fake_data,reuse=True)

        t_vars = tf.trainable_variables()
        d_vars = [var for var in t_vars if 'd_' in var.name]
        g_vars = [var for var in t_vars if 'g_' in var.name]

        '''计算损失'''
        gen_cost = tf.reduce_mean(disc_fake)
        disc_cost = -tf.reduce_mean(disc_fake) + tf.reduce_mean(disc_real)

        alpha = tf.random_uniform(
            shape=[batch_size, 1],minval=0.,maxval=1.)
        differences = fake_data - real_data
        interpolates = real_data + (alpha * differences)
        gradients = tf.gradients(Discriminator('dis_r',interpolates,reuse=True), [interpolates])[0]
        slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))
        gradient_penalty = tf.reduce_mean((slopes - 1.) ** 2)
        disc_cost += LAMBDA * gradient_penalty

        with tf.variable_scope(tf.get_variable_scope(), reuse=None):
            gen_train_op = tf.train.AdamOptimizer(
                learning_rate=1e-4,beta1=0.5,beta2=0.9).minimize(gen_cost,var_list=g_vars)
            disc_train_op = tf.train.AdamOptimizer(
                learning_rate=1e-4,beta1=0.5,beta2=0.9).minimize(disc_cost,var_list=d_vars)

        saver = tf.train.Saver()

        # os.environ['CUDA_VISIBLE_DEVICES'] = str(0)#gpu环境
        # config = tf.ConfigProto()
        # config.gpu_options.per_process_gpu_memory_fraction = 0.5#调用50%GPU资源
        # sess = tf.InteractiveSession(config=config)
        sess = tf.InteractiveSession()
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        if not os.path.exists('img'):
            os.mkdir('img')

        init = tf.global_variables_initializer()
        # init = tf.initialize_all_variables()
        sess.run(init)
        mnist = input_data.read_data_sets("data", one_hot=True)
        # mnist = mnist_data.read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
        for epoch in range (1, EPOCH):
            idxs = 1000
            for iters in range(1, idxs):
                img, _ = mnist.train.next_batch(batch_size)

                # img2 = tf.reshape(img, [batch_size, 784])
                for x in range (0,5):
                    _, d_loss = sess.run([disc_train_op, disc_cost], feed_dict={real_data: img})
                _, g_loss = sess.run([gen_train_op, gen_cost])
                # print "fake_data:%5f disc_real:%5f disc_fake:%5f "%(tf.reduce_mean(fake_data)
                #                         ,tf.reduce_mean(disc_real),tf.reduce_mean(disc_fake))
                print("[%4d:%4d/%4d] d_loss: %.8f, g_loss: %.8f"%(epoch, iters, idxs, d_loss, g_loss))

            with tf.variable_scope(tf.get_variable_scope()):
                samples = generator('gen', reuse=True)
                samples = tf.reshape(samples, shape=[batch_size, 28,28,1])
                samples=sess.run(samples)
                save_images(samples, [8,8], os.getcwd()+'/img/'+'sample_%d_epoch.png' % (epoch))

            if epoch>=39:
                checkpoint_path = os.path.join(os.getcwd(),
                                               'my_wgan-gp.ckpt')
                saver.save(sess, checkpoint_path, global_step=epoch)
                print '*********    model saved    *********'

        coord.request_stop()
        coord.join(threads)
        sess.close()
if __name__ == '__main__':
    train()

生成结果:

第一个epoch生成结果

第39个epoch生成结果

实验总结:一开始使用DCGAN做实验,但是怎么调都不收敛,dcgan需要小心的平衡生成器和辨别器的训练成都,中间换了好几个学习率,效果都不太理想,就使用了wgan-gp,后者就好训练多了,完全不用担心训练失衡的问题,用着还是很顺手的。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年08月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
使用tf.keras,您可以设计,拟合,评估和使用深度学习模型,从而仅用几行代码即可做出预测。它使普通的深度学习任务(如分类和回归预测建模)可供希望完成任务的普通开发人员使用。
拓端
2020/10/23
1.5K0
TensorFlow2 keras深度学习:MLP,CNN,RNN
它由节点层组成,其中每个节点连接到上一层的所有输出,每个节点的输出连接到下一层节点的所有输入。
拓端
2020/10/23
2.3K0
TensorFlow 2keras开发深度学习模型实例:多层感知器(MLP),卷积神经网络(CNN)和递归神经网络(RNN)
它由节点层组成,其中每个节点连接到上一层的所有输出,每个节点的输出连接到下一层节点的所有输入。
拓端
2020/11/03
2.4K0
TensorFlow 2keras开发深度学习模型实例:多层感知器(MLP),卷积神经网络(CNN)和递归神经网络(RNN)
[译]标准化Keras:TensorFlow 2.0中的高级API指南
Keras是一个非常受欢迎的构建和训练深度学习模型的高级API。它用于快速原型设计、最前沿的研究以及产品中。虽然现在的TensorFlow已经支持Keras,在2.0中,我们将Keras更紧密地集成到TensorFlow平台。
云水木石
2019/07/02
1.8K0
[译]标准化Keras:TensorFlow 2.0中的高级API指南
一文上手Tensorflow2.0之tf.keras|三
【磐创AI导读】:本系列文章介绍了与tensorflow的相关知识,包括其介绍、安装及使用等。本篇文章将接着上篇文章继续介绍它的使用。查看上篇:一文上手最新TensorFlow2.0系列(二)。想要获取更多的机器学习、深度学习资源,欢迎大家点击上方蓝字关注我们的公众号:磐创AI。
磐创AI
2019/08/23
1.6K0
深度学习工具和框架详细指南:PyTorch、TensorFlow、Keras
在深度学习的世界中,PyTorch、TensorFlow和Keras是最受欢迎的工具和框架,它们为研究者和开发者提供了强大且易于使用的接口。在本文中,我们将深入探索这三个框架,涵盖如何用它们实现经典深度学习模型,并通过代码实例详细讲解这些工具的使用方法。
平凡之路.
2024/11/21
1.2K0
Keras vs tf.keras: 在TensorFlow 2.0中有什么区别?
在本文中,您将发现Keras和tf.keras之间的区别,包括TensorFlow 2.0中的新增功能。
AI算法与图像处理
2019/10/31
2.8K0
TensorFlow2.0(11):tf.keras建模三部曲
Keras是一个基于Python编写的高层神经网络API,凭借用户友好性、模块化以及易扩展等有点大受好评,考虑到Keras的优良特性以及它的受欢迎程度,TensorFlow2.0中将Keras的代码吸收了进来,化身为tf.keras模块供用户使用。
统计学家
2019/12/27
8550
【TensorFlow2.0】以后我们再也离不开Keras了?
在TensorFlow2.0中,Keras是一个用于构建和训练深度学习模型的高阶 API。因此如果你正在使用TensorFow2.0,那么使用Keras构建深度学习模型是您的不二选择。在Keras API中总共有如下三大块:
用户1508658
2019/07/28
1.2K0
Keras中神经网络模型的5阶段生命周期
使用Python的Keras库可以很容易创建和评测深度学习神经网络,但是您必须遵循严格的模型生命周期。
用户1161128
2018/02/05
3.1K0
英文教程太难啃?这里有一份TensorFlow2.0中文教程(持续更新中)
虽然,自 TensorFlow 2.0 发布以来,我们总是能够听到「TensorFlow 2.0 就是 keras」、「说的很好,但我用 PyTorch」类似的吐槽。但毋庸置疑,TensorFlow 依然是当前最主流的深度学习框架(感兴趣的读者可查看机器之心文章:2019 年,TensorFlow 被拉下马了吗?)。
机器之心
2019/05/14
1.1K0
英文教程太难啃?这里有一份TensorFlow2.0中文教程(持续更新中)
TensorFlow 2.0 的新增功能:第一、二部分
本书的这一部分将为您简要概述 TensorFlow 2.0 中的新增功能,与 TensorFlow 1.x 的比较,惰性求值和急切执行之间的差异,架构级别的更改以及关于tf.keras和Estimator的 API 使用情况。
ApacheCN_飞龙
2023/04/26
3.8K0
TensorFlow 2 和 Keras 高级深度学习:1~5
在第一章中,我们将介绍在本书中将使用的三个深度学习人工神经网络。 这些网络是 MLP,CNN 和 RNN(在第 2 节中定义和描述),它们是本书涵盖的所选高级深度学习主题的构建块,例如自回归网络(自编码器,GAN 和 VAE),深度强化学习 ,对象检测和分割以及使用互信息的无监督学习。
ApacheCN_飞龙
2023/04/26
2.1K0
TensorFlow2.0+的API结构梳理
本文梳理了tf 2.0以上版本的API结构,用于帮助国内的初学者更好更快的了解这个框架,并为检索官方的API文档提供一些关键词。
孔西皮
2021/03/18
8960
Keras中创建LSTM模型的步骤[通俗易懂]
本文是对The 5 Step Life-Cycle for Long Short-Term Memory Models in Keras的复现与解读,新手博主,边学边记,以便后续温习,或者对他人有所帮助
全栈程序员站长
2022/10/03
3.8K0
Keras中创建LSTM模型的步骤[通俗易懂]
Python深度学习框架:PyTorch、Keras、Scikit-learn、TensorFlow如何使用?学会轻松玩转AI!
总的来说,这四个工具箱各有各的优点,适合不同的任务和学习阶段。 你想盖什么样子的“房子”(解决什么问题),就选择合适的工具箱。 接下来让我们去了解一下他们吧
小白的大数据之旅
2024/11/26
1.8K0
Python深度学习框架:PyTorch、Keras、Scikit-learn、TensorFlow如何使用?学会轻松玩转AI!
《机器学习实战:基于Scikit-Learn、Keras和TensorFlow》第10章 使用Keras搭建人工神经网络
下载本书代码和电子书:https://www.jianshu.com/p/4a94798f7dcc
SeanCheney
2019/10/16
3.4K0
《机器学习实战:基于Scikit-Learn、Keras和TensorFlow》第10章 使用Keras搭建人工神经网络
tensorflow中keras.models()的使用总结
初学者在调用keras时,不需要纠结于选择tf.keras还是直接import keras,现如今两者没有区别。从具体实现上来讲,Keras是TensorFlow的一个依赖(dependency)。但,从设计上希望用户只透过TensorFlow来使用,即tf.keras。
用户1483438
2022/01/02
6.6K0
深度学习(八) TensorFlow、PyTorch、Keras框架大比拼(8/10)
深度学习框架在当今人工智能和机器学习领域中占据着至关重要的地位。其中,TensorFlow 由 Google 开发,自 2015 年发布以来,凭借其灵活的计算图、自动微分功能以及跨平台支持等特点,迅速成为主流深度学习框架之一。它在图像识别、自然语言处理、语音识别等多个领域都有广泛应用。例如,在图像识别任务中,通过卷积神经网络能够准确识别物体、人脸和车辆等。
正在走向自律
2024/12/18
6360
深度学习(八) TensorFlow、PyTorch、Keras框架大比拼(8/10)
如何从零开发一个复杂深度学习模型
深度学习框架中涉及很多参数,如果一些基本的参数如果不了解,那么你去看任何一个深度学习框架是都会觉得很困难,下面介绍几个新手常问的几个参数。 batch 深度学习的优化算法,说白了就是梯度下降。每次的参数更新有两种方式。 第一种,遍历全部数据集算一次损失函数,然后算函数对各个参数的梯度,更新梯度。这种方法每更新一次参数都要把数据集里的所有样本都看一遍,计算量开销大,计算速度慢,不支持在线学习,这称为Batch gradient descent,批梯度下降。 另一种,每看一个数据就算一下损失函数,然后求梯度更新
朱晓霞
2018/04/18
3.3K0
如何从零开发一个复杂深度学习模型
推荐阅读
相关推荐
Python安装TensorFlow 2、tf.keras和深度学习模型的定义
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验