TensorFlow - GAN实现训练和测试,mnist数据集

写GAN网络的测试代码参考博客

遇到的问题:    

我在代码: generator.load_weights('D:/imageRegistration/languageGan/MyGAN/models/G_model/450.h5',by_name = True)  中加入了by_name=True 这一句,测试的过程中,测试生成器时,一直生成的还是噪声图,但是在输出的图片文件夹中,输出的图片中数字的效果还是很好的,我把这一句去掉之后,测试生成器,生成的图片效果就与图片中的效果差不多。

 

keras源码engine中toplogy.py定义了加载权重的函数:

load_weights(self, filepath, by_name=False)

其中默认by_name为False,这时候加载权重按照网络拓扑结构加载,适合直接使用keras中自带的网络模型,如VGG16、VGG19/resnet50等

若将by_name改为True则加载权重按照layer的name进行,layer的name相同时加载权重,适合用于改变了。模型的相关结构或增加了节点但利用了原网络的主体结构情况下使用。

引用博客

加载模型

load_weights()

load_model()

参考博客

# -*- coding: utf-8 -*-
"""
Created on Sat May 22 15:40:12 2021

@author: LiMeng
"""
from keras.datasets import mnist
from keras.layers import Dense, Dropout, Input
from keras.models import Model,Sequential
from keras.layers.advanced_activations import LeakyReLU
from keras.optimizers import Adam
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
#from google.colab import drive
print_dir = "D:/imageRegistration/languageGan/MyGAN/printImage"
model_dir_G = "D:/imageRegistration/languageGan/MyGAN/models/G_model"
model_dir_D = "D:/imageRegistration/languageGan/MyGAN/models/D_model"


# Load the dataset
def load_data():
    (x_train, y_train), (_, _) = mnist.load_data()
    x_train = (x_train.astype(np.float32) - 127.5)/127.5
  
  # Convert shape from (60000, 28, 28) to (60000, 784)
    x_train = x_train.reshape(60000, 784)
    return (x_train, y_train)

X_train, y_train = load_data()
print(X_train.shape, y_train.shape)

def build_generator():
    model = Sequential()
    
    model.add(Dense(units=256, input_dim=100))
    model.add(LeakyReLU(alpha=0.2))
    
    model.add(Dense(units=512))
    model.add(LeakyReLU(alpha=0.2))
    
    model.add(Dense(units=1024))
    model.add(LeakyReLU(alpha=0.2))
    
    model.add(Dense(units=784, activation='tanh'))
    
    model.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
    return model

generator = build_generator()
generator.summary()
"""
dropout是指在深度学习网络的训练过程中,对于神经网络单元,按照一定的概率将其暂时从网络中丢弃。注意是暂时,对于随机梯度下降来说,由于是随机丢弃,故而每一个mini-batch都在训练不同的网络。
dropout是CNN中防止过拟合提高效果的一个大杀器
"""
def build_discriminator():
    model = Sequential()
    
    model.add(Dense(units=1024 ,input_dim=784))
    model.add(LeakyReLU(alpha=0.2))
    model.add(Dropout(0.3))
       
    model.add(Dense(units=512))
    model.add(LeakyReLU(alpha=0.2))
    model.add(Dropout(0.3))
       
    model.add(Dense(units=256))
    model.add(LeakyReLU(alpha=0.2))
    model.add(Dropout(0.3))
      
    model.add(Dense(units=1, activation='sigmoid'))
    
    model.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
    return model
  
#discriminator = build_discriminator()
#discriminator.summary()

def build_GAN(discriminator, generator):
    discriminator.trainable=False
    GAN_input = Input(shape=(100,))
    x = generator(GAN_input)
    GAN_output= discriminator(x)
    GAN = Model(inputs=GAN_input, outputs=GAN_output)
    GAN.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))
    return GAN

#GAN = build_GAN(discriminator, generator)
#GAN.summary()

def draw_images(generator, epoch, examples=25, dim=(5,5), figsize=(10,10)):
    noise= np.random.normal(loc=0, scale=1, size=[examples, 100])
    generated_images = generator.predict(noise)
    generated_images = generated_images.reshape(25,28,28)
    plt.figure(figsize=figsize)
    for i in range(generated_images.shape[0]):
        plt.subplot(dim[0], dim[1], i+1)
        plt.imshow(generated_images[i], interpolation='nearest', cmap='Greys')
        plt.axis('off')
    plt.tight_layout()
    plt.savefig('D:/imageRegistration/languageGan/MyGAN/printImage/Generated_images%d.png' %epoch)
    
    
def train_GAN(epochs=1, batch_size=128,sample_interval = 50):
    
  #Loading the data
    X_train, y_train = load_data()

  # Creating GAN
    generator = build_generator()
    discriminator = build_discriminator()
    GAN = build_GAN(discriminator, generator)
#  print("\nepochs %d\n" %epochs)
    for i in range(1, epochs+1):
        print("\nEpoch %d\n" %i)
    
        for _ in tqdm(range(batch_size)):
           # Generate fake images from random noiset
            """
           np.random.normal生成正态分布:均值为0,方差为1,维度为(batch_size,100)--->(128,100)
           generator生成器的输入是128张100维的数据 fake_images即为generator生成的虚假图像
           np.random.randint(low,high,size,dtype) array = np.random.randint(0, X_train.shape[0], batch_size)
              生成128维(行向量) 0-60000的数字,X_train.shape[0]为 60000,
            """
            noise= np.random.normal(0,1, (batch_size, 100))
            fake_images = generator.predict(noise)
            """
           #画出虚假图像
           plt.imshow(fake_images)
           plt.title("fake_images")
            """
      # Select a random batch of real images from MNIST
      
            real_images = X_train[np.random.randint(0, X_train.shape[0], batch_size)]
            """
           #画出真实图像
           plt.imshow(real_images)
           plt.title("real_images")
            """
      # Labels for fake and real images           
            label_fake = np.zeros(batch_size)
            label_real = np.ones(batch_size) 

      # Concatenate fake and real images 
            """
          X = np.concatenate([fake_images, real_images])
          y = np.concatenate([label_fake, label_real])
            """
      # Train the discriminator
            discriminator.trainable=True
            """
           discriminator.train_on_batch(X, y)
            """
            d_loss_real = discriminator.train_on_batch(real_images, label_real)
            d_loss_fake = discriminator.train_on_batch(fake_images,label_fake)
            d_loss = 0.5 * np.add(d_loss_real,d_loss_fake)
            print('\n')
            print('     ---d_loss_real, d_loss_fake, d_loss: ',d_loss_real,d_loss_fake,d_loss)
      # Train the generator/chained GAN model (with frozen weights in discriminator) 
            discriminator.trainable=False
            """
           GAN.train_on_batch(noise, label_real)
            """
            g_loss = GAN.train_on_batch(noise, label_real)
            print('     ---g_loss\n',g_loss)
        """
        print("%d [D loss :%f, acc: %.2f] [G loss: %f]" , i, d_loss[0], 100*d_loss[1], g_loss)
        """
        if i % sample_interval == 0:
            generator.save('D:/imageRegistration/languageGan/MyGAN/models/G_model/%d.h5'%i)
            discriminator.save('D:/imageRegistration/languageGan/MyGAN/models/D_model/%d.h5'%i)     
      #Draw generated images every 15 epoches   
        
        if i == 1 or i % 10 == 0:
            draw_images(generator, i)
            
            
def test(gen_number = 10, save=False): 
 #test#    generator.load_weights('D:/imageRegistration/languageGan/MyGAN/models/G_model/450.h5')
    #discriminator.load_weights("D:/image registration/language gan/My GAN/models/G_model/2.h5",by_name=True)
    noise_test = np.random.normal(0,1,(1,100))
    fake_images = generator.predict(noise_test)
#    fake_images = 0.5*fake_images + 0.5
    fake_images = fake_images.reshape(28,28)
    plt.imshow(fake_images)      
#train_GAN(epochs=10000, batch_size=128)
test()

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用TensorFlow训练测试手写数字识别的MNIST数据集十分简单。首先,我们需要导入TensorFlowMNIST数据集: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data 接下来,我们可以使用input_data.read_data_sets()函数加载MNIST数据集,其中参数为下载数据集的路径。我们可以将数据集分为训练集、验证集和测试集。这里我们将验证集作为模型的参数调整过程,测试集用于最终模型评估。 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 接下来,我们可以使用TensorFlow创建一个简单的深度学习模型。首先,我们创建一个输入占位符,用于输入样本和标签。由于MNIST数据集是28x28的图像,我们将其展平为一个784维的向量。 x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) 接下来,我们可以定义一个简单的全连接神经网络,包含一个隐藏层和一个输出层。我们使用ReLU激活函数,并使用交叉熵作为损失函数。 hidden_layer = tf.layers.dense(x, 128, activation=tf.nn.relu) output_layer = tf.layers.dense(hidden_layer, 10, activation=None, name="output") cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output_layer, labels=y)) 然后,我们可以使用梯度下降优化器来最小化损失函数,并定义正确预测的准确率。这样就完成了模型的构建。 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(output_layer, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 接下来,我们可以在一个会话中运行模型。在每次迭代中,我们从训练集中随机选择一批样本进行训练。在验证集上进行模型的参数调整过程,最后在测试集上评估模型的准确率。 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch_x, batch_y = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_x, y: batch_y}) val_accuracy = sess.run(accuracy, feed_dict={x: mnist.validation.images, y: mnist.validation.labels}) print("Validation Accuracy:", val_accuracy) test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}) print("Test Accuracy:", test_accuracy) 通过这个简单的代码,我们可以使用TensorFlow训练测试MNIST数据集,并得到测试集上的准确率。 ### 回答2: gan tensorflow mnist是指使用TensorFlow框架训练生成对抗网络(GAN)来生成手写数字图像的任务。 首先,手写数字数据集是一个非常常见且经典的机器学习数据集MNIST数据集包含了由0到9之间的手写数字的图像样本。在gan tensorflow mnist任务中,我们的目标是使用GAN生成与这些手写数字样本类似的新图像。 GAN是一种由生成器和判别器组成的模型生成器任务是生成看起来真实的图像,而判别器任务是判断给定图像是真实的(来自训练数据集)还是生成的(来自生成器)。这两个模型通过对抗训练来相互竞争和提高性能。 在gan tensorflow mnist任务中,我们首先需要准备和加载MNIST数据集。利用TensorFlow的函数和工具,我们可以轻松地加载和处理这些图像。 接下来,我们定义生成器和判别器模型生成模型通常由一系列的卷积、反卷积和激活函数层组成,以逐渐生成高质量的图像。判别器模型则类似于一个二分类器,它接收图像作为输入并输出真实或生成的预测结果。 我们使用TensorFlow的优化器和损失函数定义GAN模型训练过程。生成器的目标是误导判别器,使其将生成的图像误认为是真实图像,从而最大限度地降低判别器的损失函数。判别器的目标是准确地区分真实和生成的图像,从而最大限度地降低自身的损失函数。 最后,我们使用训练数据集训练GAN模型。通过多次迭代,生成器和判别器的性能会随着时间的推移而得到改善。一旦训练完成,我们可以使用生成模型生成新的手写数字图像。 总结来说,gan tensorflow mnist是指使用TensorFlow框架训练生成对抗网络来生成手写数字图像的任务。通过定义生成器和判别器模型,使用优化器和损失函数进行训练,我们可以生成类似于MNIST数据集手写数字的新图像。 ### 回答3: 用TensorFlow训练MNIST数据集可以实现手写数字的分类任务。首先我们需要导入相关库和模块,如tensorflow、keras以及MNIST数据集。接着,我们定义模型的网络结构,可以选择卷积神经网络(CNN)或者全连接神经网络(DNN)。对于MNIST数据集,我们可以选择使用CNN,因为它能更好地处理图像数据。 通过调用Keras中的Sequential模型来定义网络结构,可以添加多个层(如卷积层、池化层、全连接层等),用来提取特征和做出分类。其中,输入层的大小与MNIST图片的大小相对应,输出层的大小等于类别的数量(即0~9的数字)。同时,我们可以选择优化器(如Adam)、损失函数(如交叉熵)和评估指标(如准确率)。 接下来,我们用模型编译来配置模型的学习过程。在编译时,我们可以设置优化器、损失函数和评估指标。然后,我们用训练数据对模型进行拟合,通过迭代优化来调整模型的权重和偏置。迭代次数可以根据需要进行调整,以达到训练效果的需求。 训练结束后,我们可以使用测试数据对模型进行评估,获得模型测试集上的准确率。最后,我们可以使用模型对新的未知数据进行预测,得到相应的分类结果。 综上所述,使用TensorFlow训练MNIST数据集可以实现手写数字的分类任务,通过定义模型结构、编译模型、拟合模型、评估模型和预测来完成整个过程。这个过程需要一定的编程知识和理解深度学习的原理,但TensorFlow提供了方便的api和文档,使我们能够相对容易地实现这个任务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值