深度学习之DCGAN

article/2025/8/26 22:36:20

这一此的博客我给大家介绍一下DCGAN的原理以及DCGAN的实战代码,今天我用最简单的语言给大家介绍DCGAN。
相信大家现在对深度学习有了一定的了解,对GAN也有了认识,如果不知道什么是GAN的可以去看我以前的博客,接下来我给大家介绍一下DCGAN的原理。
DCGAN
DCGAN的全称是Deep Convolution Generative Adversarial Networks(深度卷积生成对抗网络)顾名思义也就是在深度卷积的基础上加上了一个GAN,就构成了我们所说的DCGAN。
在这里插入图片描述
这是DCGAN中生成网络G的模型,通过随机输入的一个噪声,通过反卷积之后我们得到了一个64X64X3的RGB的图像.
这里我们要介绍一下反卷积:
卷积相信大家都很了解了把,反卷积其实就是卷积的一一个反向的过程。这里的反向的过程说的其实是还原输入图片的大小而不是原封不动地还原数据,这里要注意以下反卷积的意义。
例如:我们输入一个 3x3的一个灰度图经过一个卷积核为2x2 strides=2反卷积之后就变成了6x6的灰度图,也就是反卷积图片大小的变化和卷积过程是相反的。
DCGAN中我们要注意以下几点:
1.判别网络D判别完了之后我们把输出的结果要送入一个输出单元为一个的全连接网络
2.在判别网络的所有层上使用LeakyReLU激活函数。
3.在生成网络的所有层上使用RelU激活函数,除了输出层使用Tanh激活函数。
接下来我们来看一下实现代码:

# -*- coding: utf-8 -*-
//导入相应的模块
import tensorflow as tf
import numpy as np
import urllib
import tarfile
import os
import matplotlib.pyplot as plt
%matplotlib inline
from imageio import imread, imsave, mimsave
from scipy.misc import imresize
import glob
# 下载和处理LFW数据
url = 'http://vis-www.cs.umass.edu/lfw/lfw.tgz'
filename = 'lfw.tgz'
directory = 'lfw_imgs'
new_dir = 'lfw_new_imgs'
if not os.path.isdir(new_dir):os.mkdir(new_dir)
#判断是否存在该文件夹    if not os.path.isdir(directory):if not os.path.isfile(filename):urllib.request.urlretrieve(url, filename)tar = tarfile.open(filename, 'r:gz')tar.extractall(path=directory)tar.close()count = 0for dir_, _, files in os.walk(directory):#取出所有的图片重新命名for file_ in files:img = imread(os.path.join(dir_, file_))imsave(os.path.join(new_dir, '%d.png' % count), img)count += 1
# dataset = 'lfw_new_imgs' # LFW
dataset = 'celeba' # CelebA
images = glob.glob(os.path.join(dataset, '*.*')) 
print(len(images))
batch_size = 100
z_dim = 100
WIDTH = 64
HEIGHT = 64OUTPUT_DIR = 'samples_' + dataset
if not os.path.exists(OUTPUT_DIR):os.mkdir(OUTPUT_DIR)
#设置图片保存路径X = tf.placeholder(dtype=tf.float32, shape=[None, HEIGHT, WIDTH, 3], name='X')
noise = tf.placeholder(dtype=tf.float32, shape=[None, z_dim], name='noise')
is_training = tf.placeholder(dtype=tf.bool, name='is_training')def lrelu(x, leak=0.2):return tf.maximum(x, leak * x)
#激活函数输出X和0.2X之间比较大的一个
def sigmoid_cross_entropy_with_logits(x, y):return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, labels=y)
#损失函数
//定义判别器进行卷积操作
def discriminator(image, reuse=None, is_training=is_training):momentum = 0.9with tf.variable_scope('discriminator', reuse=reuse):#下面的每个变量名都带上discriminatorh0 = lrelu(tf.layers.conv2d(image, kernel_size=5, filters=64, strides=2, padding='same'))h1 = tf.layers.conv2d(h0, kernel_size=5, filters=128, strides=2, padding='same')h1 = lrelu(tf.contrib.layers.batch_norm(h1, is_training=is_training, decay=momentum))h2 = tf.layers.conv2d(h1, kernel_size=5, filters=256, strides=2, padding='same')h2 = lrelu(tf.contrib.layers.batch_norm(h2, is_training=is_training, decay=momentum))h3 = tf.layers.conv2d(h2, kernel_size=5, filters=512, strides=2, padding='same')h3 = lrelu(tf.contrib.layers.batch_norm(h3, is_training=is_training, decay=momentum))h4 = tf.contrib.layers.flatten(h3)h4 = tf.layers.dense(h4, units=1)//送入是由一个输出神经元的全连接网络,因为只需要一个真假的答案所以只要一个输出return tf.nn.sigmoid(h4), h4
//定义生成器进行反卷积的操作
def generator(z, is_training=is_training):momentum = 0.9with tf.variable_scope('generator', reuse=None):#下面的变量名都带上generatod = 4h0 = tf.layers.dense(z, units=d * d * 512)h0 = tf.reshape(h0, shape=[-1, d, d, 512])h0 = tf.nn.relu(tf.contrib.layers.batch_norm(h0, is_training=is_training, decay=momentum))h1 = tf.layers.conv2d_transpose(h0, kernel_size=5, filters=256, strides=2, padding='same')h1 = tf.nn.relu(tf.contrib.layers.batch_norm(h1, is_training=is_training, decay=momentum))h2 = tf.layers.conv2d_transpose(h1, kernel_size=5, filters=128, strides=2, padding='same')h2 = tf.nn.relu(tf.contrib.layers.batch_norm(h2, is_training=is_training, decay=momentum))h3 = tf.layers.conv2d_transpose(h2, kernel_size=5, filters=64, strides=2, padding='same')h3 = tf.nn.relu(tf.contrib.layers.batch_norm(h3, is_training=is_training, decay=momentum))h4 = tf.layers.conv2d_transpose(h3, kernel_size=5, filters=3, strides=2, padding='same', activation=tf.nn.tanh, name='g')//输出用tanh激活激活return h4

这里给大家图片变化的步骤
在这里插入图片描述

g = generator(noise)#输入随机噪声产生图片
d_real, d_real_logits = discriminator(X)
d_fake, d_fake_logits = discriminator(g, reuse=True)vars_g = [var for var in tf.trainable_variables() if var.name.startswith('generator')]#取出所有的生成器数据
vars_d = [var for var in tf.trainable_variables() if var.name.startswith('discriminator')]#取出所有的判别器的数据loss_d_real = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_real_logits, tf.ones_like(d_real)))
#真实数据对判别器产生的损失,要尽可能给高分
loss_d_fake = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_fake_logits, tf.zeros_like(d_fake)))
#生成的假数据对判别器产生的损失要尽可能给低分
loss_g = tf.reduce_mean(sigmoid_cross_entropy_with_logits(d_fake_logits, tf.ones_like(d_fake)))
#生成器的数据对生成器产生的损失要尽可能给高分
loss_d = loss_d_real + loss_d_fake#生成器的损失
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):optimizer_d = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(loss_d, var_list=vars_d)optimizer_g = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(loss_g, var_list=vars_g)
def read_image(path, height, width):image = imread(path)h = image.shape[0]w = image.shape[1]def read_image(path, height, width):image = imread(path)h = image.shape[0]w = image.shape[1]if h > w:image = image[h // 2 - w // 2: h // 2 + w // 2, :, :]#高度取中间部分宽度和深度全部都要else:image = image[:, w // 2 - h // 2: w // 2 + h // 2, :]    image = imresize(image, (height, width))#改变图片的大小return image / 255.#把图片范围转到了0-1if h > w:image = image[h // 2 - w // 2: h // 2 + w // 2, :, :]#高度取中间部分宽度和深度全部都要else:image = image[:, w // 2 - h // 2: w // 2 + h // 2, :]    image = imresize(image, (height, width))#改变图片的大小return image / 255.#把图片范围转到了0-1
#这段代码为一个辅助函数代码,大家可以不用看
def montage(images):    if isinstance(images, list):images = np.array(images)img_h = images.shape[1]img_w = images.shape[2]n_plots = int(np.ceil(np.sqrt(images.shape[0])))if len(images.shape) == 4 and images.shape[3] == 3:m = np.ones((images.shape[1] * n_plots + n_plots + 1,images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5elif len(images.shape) == 4 and images.shape[3] == 1:m = np.ones((images.shape[1] * n_plots + n_plots + 1,images.shape[2] * n_plots + n_plots + 1, 1)) * 0.5elif len(images.shape) == 3:m = np.ones((images.shape[1] * n_plots + n_plots + 1,images.shape[2] * n_plots + n_plots + 1)) * 0.5else:raise ValueError('Could not parse image shape of {}'.format(images.shape))for i in range(n_plots):for j in range(n_plots):this_filter = i * n_plots + jif this_filter < images.shape[0]:this_img = images[this_filter]m[1 + i + i * img_h:1 + i + (i + 1) * img_h,1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_imgreturn m
ess = tf.Session()
sess.run(tf.global_variables_initializer())
z_samples = np.random.uniform(-1.0, 1.0, [batch_size, z_dim]).astype(np.float32)
samples = []
loss = {'d': [], 'g': []}offset = 0
for i in range(60000):n = np.random.uniform(-1.0, 1.0, [batch_size, z_dim]).astype(np.float32)offset = (offset + batch_size) % len(images)batch = np.array([read_image(img, HEIGHT, WIDTH) for img in images[offset: offset + batch_size]])batch = (batch - 0.5) * 2#把图片范围转到-1-1之间d_ls, g_ls = sess.run([loss_d, loss_g], feed_dict={X: batch, noise: n, is_training: True})loss['d'].append(d_ls)loss['g'].append(g_ls)sess.run(optimizer_d, feed_dict={X: batch损失, noise: n, is_training: True})sess.run(optimizer_g, feed_dict={X: batch, noise: n, is_training: True})sess.run(optimizer_g, feed_dict={X: batch, noise: n, is_training: True})if i % 500 == 0:print(i, d_ls, g_ls)gen_imgs = sess.run(g, feed_dict={noise: z_samples, is_training: False})gen_imgs = (gen_imgs + 1) / 2#再把图片转到0-1之间imgs = [img[:, :, :] for img in gen_imgs]gen_imgs = montage(imgs)plt.axis('off')plt.imshow(gen_imgs)imsave(os.path.join(OUTPUT_DIR, 'sample_%d.jpg' % i), gen_imgs)plt.show()samples.append(gen_imgs)plt.plot(loss['d'], label='Discriminator')
plt.plot(loss['g'], label='Generator')
plt.legend(loc='upper right')
plt.savefig(os.path.join(OUTPUT_DIR, 'Loss.png'))
plt.show()
mimsave(os.path.join(OUTPUT_DIR, 'samples.gif'), samples, fps=10)
#saver = tf.train.Saver()
#saver.save(sess, os.path.join(OUTPUT_DIR, 'dcgan_' + dataset), global_step=60000)  保存现有的模型

这段代码来自CSDN—张宏伦 , 代码注释原创
我用他的模型跑出来的结果为:
生成了人脸并把100张图片融合为一张图片
在这里插入图片描述


http://chatgpt.dhexx.cn/article/k6GJLIv0.shtml

相关文章

对抗神经网络(二)——DCGAN

一、DCGAN介绍 DCGAN即使用卷积网络的对抗网络&#xff0c;其原理和GAN一样&#xff0c;只是把CNN卷积技术用于GAN模式的网络里&#xff0c;G&#xff08;生成器&#xff09;网在生成数据时&#xff0c;使用反卷积的重构技术来重构原始图片。D&#xff08;判别器&#xff09;网…

对抗生成网络GAN系列——DCGAN简介及人脸图像生成案例

&#x1f34a;作者简介&#xff1a;秃头小苏&#xff0c;致力于用最通俗的语言描述问题 &#x1f34a;往期回顾&#xff1a;对抗生成网络GAN系列——GAN原理及手写数字生成小案例 &#x1f34a;近期目标&#xff1a;写好专栏的每一篇文章 &#x1f34a;支持小苏&#xff1a;点赞…

DCGAN理论讲解及代码实现

目录 DCGAN理论讲解 DCGAN的改进&#xff1a; DCGAN的设计技巧 DCGAN纯代码实现 导入库 导入数据和归一化 定义生成器 定义鉴别器 初始化和 模型训练 运行结果 DCGAN理论讲解 DCGAN也叫深度卷积生成对抗网络&#xff0c;DCGAN就是将CNN与GAN结合在一起&#xff0c;生…

torch学习 (三十七):DCGAN详解

文章目录 引入1 生成器2 鉴别器3 模型训练&#xff1a;生成器与鉴别器的交互4 参数设置5 数据载入6 完整代码7 部分输出图像示意7.1 真实图像7.2 训练200个批次7.2 训练400个批次7.2 训练600个批次 引入 论文详解&#xff1a;Unsupervised representation learning with deep c…

GANs系列:DCGAN原理简介与基础GAN的区别对比

本文长期不定时更新最新知识&#xff0c;防止迷路记得收藏哦&#xff01; 还未了解基础GAN的&#xff0c;可以先看下面两篇文章&#xff1a; GNA笔记--GAN生成式对抗网络原理以及数学表达式解剖 入门GAN实战---生成MNIST手写数据集代码实现pytorch 背景介绍 2016年&#…

Pix2Pix和CycleGAN

GAN的局限性 即便如此&#xff0c;传统的GAN也不是万能的&#xff0c;它有下面两个不足&#xff1a; 1. 没有**用户控制&#xff08;user control&#xff09;**能力 在传统的GAN里&#xff0c;输入一个随机噪声&#xff0c;就会输出一幅随机图像。 但用户是有想法滴&#xff…

PyTorch 实现Image to Image (pix2pix)

目录 一、前言 二、数据集 三、网络结构 四、代码 &#xff08;一&#xff09;net &#xff08;二&#xff09;dataset &#xff08;三&#xff09;train &#xff08;四&#xff09;test 五、结果 &#xff08;一&#xff09;128*128 &#xff08;二&#xff09;256*256 …

pix2pix、pix2pixHD 通过损失日志进行训练可视化

目录 背景 代码 结果 总结 背景 pix2pix(HD)代码在训练时会自动保存一个损失变化的txt文件&#xff0c;通过该文件能够对训练过程进行一个简单的可视化&#xff0c;代码如下。 训练的损失文件如图&#xff0c;对其进行可视化。 代码 #coding:utf-8 ## #author: QQ&#x…

Pix2Pix代码解析

参考链接&#xff1a;https://github.com/yenchenlin/pix2pix-tensorflow https://blog.csdn.net/stdcoutzyx/article/details/78820728 utils.py from __future__ import division import math import json import random import pprint import scipy.misc import numpy as…

pix2pix 与 pix2pixHD的大致分析

目录 pix2pix与pix2pixHD的生成器 判别器 PatchGAN&#xff08;马尔科夫判别器&#xff09; 1、pix2pix 简单粗暴的办法 如何解决模糊呢&#xff1f; 其他tricks 2、pix2pixHD 高分辨率图像生成 模型结构 Loss设计 使用Instance-map的图像进行训练 语义编辑 总结 …

Tensorflow2.0之Pix2pix

文章目录 Pix2pix介绍Pix2pix应用Pix2pix生成器及判别器网络结构代码实现1、导入需要的库2、下载数据包3、加载并展示数据包中的图片4、处理图片4.1 将图像调整为更大的高度和宽度4.2 随机裁剪到目标尺寸4.3 随机将图像做水平镜像处理4.4 图像归一化4.5 处理训练集图片4.6 处理…

pix2pix算法笔记

论文:Image-to-Image Translation with Conditional Adversarial Networks 论文链接:https://arxiv.org/abs/1611.07004 代码链接:https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix 这篇论文发表在CVPR2017,简称pix2pix,是将GAN应用于有监督的图像到图像翻译的经…

Pix2Pix原理解析以及代码流程

文章目录 1、网络搭建2、反向传播过程3、PatchGAN4.与CGAN的不同之处 1、网络搭建 class UnetGenerator(nn.Module):"""Create a Unet-based generator"""def __init__(self, input_nc, output_nc, num_downs, ngf64, norm_layernn.BatchNorm2d…

图像翻译网络模型Pix2Pix

Pix2pix算法(Image-to-Image Translation,图像翻译)&#xff0c;它的核心技术有三点&#xff1a;基于条件GAN的损失函数&#xff0c;基于U-Net的生成器和基于PatchGAN的判别器。Pix2Pix能够在诸多图像翻译任务上取得令人惊艳的效果&#xff0c;但因为它的输入是图像对&#xff…

GAN系列之pix2pix、pix2pixHD

1. 摘要 图像处理的很多问题都是将一张输入的图片转变为一张对应的输出图片&#xff0c;比如灰度图、梯度图、彩色图之间的转换等。通常每一种问题都使用特定的算法&#xff08;如&#xff1a;使用CNN来解决图像转换问题时&#xff0c;要根据每个问题设定一个特定的loss funct…

Pix2Pix原理解析

1.网络搭建 class UnetGenerator(nn.Module):"""Create a Unet-based generator"""def __init__(self, input_nc, output_nc, num_downs, ngf64, norm_layernn.BatchNorm2d, use_dropoutFalse):"""Construct a Unet generatorPa…

如何利用Pix2Pix将黑白图片自动变成彩色图片

实现黑白图片自动变成彩色图片 如果你有一幅黑白图片,你该如何上色让他变成彩色的呢?通常做法可能是使用PS工具来进行上色。那么,有没有什么办法进行自动上色呢?自动将黑白图片变成彩色图片?答案是有的,使用深度学习中的Pix2Pix网络就可以实现这一功能。 如图所示,我们…

Pix2Pix进一步了解

参考&#xff1a;Pix2Pix视频解读 一、Pix2Pix是输入图片矩阵而不是标签向量 1、生成器方面 Pix2Pix与CGAN之间的联系&#xff1a;CGAN生成器输入的是一个label&#xff0c;而我们现在要做的是把这个lable换成一个图片&#xff0c;如下所示。这个图片是一个建筑物的模…

CycleGAN与pix2pix训练自己的数据集-Pytorch

github&#xff1a;https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix 参考&#xff1a;https://blog.csdn.net/Gavinmiaoc/article/details/80585531 文章目录 CycleganDownload&Prerequisitesbefore your work数据集训练测试 pix2pix数据集训练测试 Cyclegan Do…

pix2pix学习系列(1):预训练模型测试pix2pix

pix2pix学习系列&#xff08;1&#xff09;&#xff1a;预训练模型测试pix2pix 参考文献&#xff1a; [Pytorch系列-66]&#xff1a;生成对抗网络GAN - 图像生成开源项目pytorch-CycleGAN-and-pix2pix - 使用预训练模型测试pix2pix模型 运行环境 win 10 1、代码下载 Gith…