GAN手写体生成(MINIST)

参考教材:人工智能导论(第4版) 王万良 高等教育出版社
实验环境:Python3.7 + Tensor flow 2.1

人工智能导论实验导航

实验一:斑马问题 https://blog.csdn.net/weixin_46291251/article/details/122246347

实验二:图像恢复 https://blog.csdn.net/weixin_46291251/article/details/122561220

实验三:花卉识别 https://blog.csdn.net/weixin_46291251/article/details/122561505

实验四:手写体生成 https://blog.csdn.net/weixin_46291251/article/details/122576478

实验源码: xxx

4.1实验介绍

4.1.1实验背景

深度学习为人工智能核心技术,本章主要围绕深度学习涉及的全连接神经网络、卷积神经网络和对抗神经网络而开设的实验。

生成对抗网络是一种训练生成网络的框架,比如生成图片的深度卷积神经网络。构建一个用来生成图片的GAN模型需要同时具备判别模型和生成模型,判别模型,用来分析一张图片是真实的还是仿造的;生成模型使用反转的卷积层将输入转换为对应像素值的完整二维图像。本实验通过GAN模型的搭建,主要介绍TensorFlow2.0计算的基本流程,以及构建网络的基本要素。

4.1.2实验目的

本章实验的主要目的是掌握深度学习相关基础知识点,了解深度学习相关基础知识,经典全连接神经网络、卷积神经网络和对抗神经网络。掌握不同神经网络架构的设计原理,熟悉使用Tensorflow 2.1深度学习框架实现深度学习实验的一般流程。同时对ModelArts自动学习模块、AI市场有初步认识,对Atlas200DK开发板模型部署相关内容有初步了解。

学习怎么定义和训练一个单独的判别模型,用来学习真假图片之间的不同点
学习怎么定义单独的生成模型,并训练同时具备生成和判别的复合模型
学习怎么评估GAN模型的表现,并使用最终得到的单独的生成模型生成图片

4.1.3实验简介

利用MINIST数据集对构建的GAN网络进行训练,最终使得该网络能够脱离数据集自动生成以假乱真的手写体图像。在这里插入图片描述

4.2概要设计

GAN主要包括了两个部分,即生成器generator与判别器discriminator。生成器主要用来学习真实图像分布从而让自身生成的图像更加真实,以骗过判别器。判别器则需要对接收的图片进行真假判别。在整个过程中,生成器努力地让生成的图像更加真实,而判别器则努力地去识别出图像的真假,这个过程相当于一个二人博弈,随着时间的推移,生成器和判别器在不断地进行对抗,最终两个网络达到了一个动态均衡:生成器生成的图像接近于真实图像分布,而判别器识别不出真假图像,对于给定图像的预测为真的概率基本接近0.5(相当于随机猜测类别)。所以:
对于给定的真实图片(real image),判别器要为其打上标签1;
对于给定的生成图片(fake image),判别器要为其打上标签0;
对于生成器传给辨别器的生成图片,生成器希望辨别器打上标签1。

4.3详细设计

4.3.1 实验数据准备

数据集简介:
1). MNIST数据集来自美国国家标准与技术研究所(National Institute of Standards and
Technology ,简称NIST);
2). 该数据集由来自250个不同人手写的数字构成,其中50%是高中学生,50%来自人口普查局
的工组人员;
3). 数据集可在http://yann.lecun.com/exdb/mnist/ 获取, 它包含了四个部分:

  • Training set images: train-images-idx3-ubyte.gz (9.9 MB, 解压后 47 MB, 包含 60,000 个样本)
  • Training set labels: train-labels-idx1-ubyte.gz (29 KB, 解压后 60 KB, 包含 60,000 个标签)
  • Test set images: t10k-images-idx3-ubyte.gz (1.6 MB, 解压后 7.8 MB, 包含 10,000 个样本)
  • Test set labels: t10k-labels-idx1-ubyte.gz (5KB, 解压后 10 KB, 包含 10,000 个标签)
    4). mnist是一个入门级的计算机视觉数据集,它包含各种手写数字图片,下图展示了mnist中的一些图片:在这里插入图片描述

数据集加载:

import numpy as np
# ''中为放置mnist.npz的相对路径,改为自己数据集存放的路径 
path = r'.\datasets\mnist.npz 
f = np.load(path)          #加载数据集
trainX = f['x_train']      #训练集数据获取
trainy = f['y_train']      #训练集数据标签获取
testX = f['x_test']       #测试集数据获取
testy = f['y_test']        #测试集数据标签获取
print("Train", trainX.shape, trainy.shape)     #查看训练集数据形状及标签形状
print("Test", testX.shape, testy.shape)        #查看验证集数据形状及标签形状

输出结果:
Train (60000, 28, 28) (60000,)
Test (10000, 28, 28) (10000,)

可视化训练集前30张图片:
from matplotlib import pyplot   #从matplotlib数据库导入pyplot模块
for i in range(30):              # 使用range()函数产生0到29这30个数,建立for循环
#使用subplot()构建子图,第一个参数5表示每列有5张图,
第二个参数表示每行有6张图,1+i表示第(1+i张图)
    pyplot.subplot(5, 6, 1 + i)    
    pyplot.axis('off')          # 关闭坐标轴("on"为显示坐标轴)
     
抱歉,作为AI语言模型,我无法手写代码或进行图像识别任务。但是,我可以为您提供一个基本的MLP代码框架,您可以使用它来构建一个MINIST手写字体识别MLP模型: ``` import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Define hyperparameters learning_rate = 0.1 num_epochs = 100 batch_size = 100 # Define the number of neurons in each layer input_layer = 784 hidden_layer1 = 256 hidden_layer2 = 256 output_layer = 10 # Define the input and output placeholders X = tf.placeholder(tf.float32, [None, input_layer]) Y = tf.placeholder(tf.float32, [None, output_layer]) # Define the weights and biases for each layer weights = { 'w1': tf.Variable(tf.random_normal([input_layer, hidden_layer1])), 'w2': tf.Variable(tf.random_normal([hidden_layer1, hidden_layer2])), 'out': tf.Variable(tf.random_normal([hidden_layer2, output_layer])) } biases = { 'b1': tf.Variable(tf.random_normal([hidden_layer1])), 'b2': tf.Variable(tf.random_normal([hidden_layer2])), 'out': tf.Variable(tf.random_normal([output_layer])) } # Define the forward propagation hidden_layer1_output = tf.nn.relu(tf.add(tf.matmul(X, weights['w1']), biases['b1'])) hidden_layer2_output = tf.nn.relu(tf.add(tf.matmul(hidden_layer1_output, weights['w2']), biases['b2'])) output = tf.add(tf.matmul(hidden_layer2_output, weights['out']), biases['out']) # Define the loss function and optimizer loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss) # Define the accuracy metric correct_pred = tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initialize the variables init = tf.global_variables_initializer() # Start the session with tf.Session() as sess: sess.run(init) num_batches = int(mnist.train.num_examples/batch_size) # Train the model for epoch in range(num_epochs): avg_loss = 0 for batch in range(num_batches): batch_x, batch_y = mnist.train.next_batch(batch_size) _, l = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y}) avg_loss += l/num_batches if epoch % 10 == 0: print("Epoch:", epoch+1, " Loss:", avg_loss) # Test the model test_accuracy = sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels}) print("Test Accuracy:", test_accuracy) ``` 这个代码框架包含了一个基本的MLP模型,使用MNIST数据集进行训练和测试。您可以根据需要进行调整和修改,以获得更好的性能和准确性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cheney822

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值