深度学习-卷积神经网络-实例及代码1(入门)—利用Tensorflow和mnist数据集训练单层前馈神经网络/感知机实现手写数字识别

系列文章:

深度学习-卷积神经网络-实例及代码0.8—基于最小均方误差的线性判别函数参数拟合训练

深度学习-卷积神经网络-实例及代码0.9—MNIST数据集介绍、下载及基本操作

 

1、实例主要原理

利用Tensorflow和mnist数据集训练单层前馈神经网络/感知机模型

损失函数使用交叉熵

训练方法采用梯度下降

 

2、基础知识准备

(1)机器学习-前馈神经网络/感知机的基本原理

前馈神经网络也称为BP神经网络

采用梯度下降法进行后向传播

从而训练模型的权值参数和阈值参数

(2)Tensorflow基础知识

包括计算图、张量、Session的运行等基本概念等

(3)利用Tensorflow进行训练的相关操作方法

练习Tensorflow的基本使用方法和模型训练的基本过程,可参考文章:

                       深度学习-卷积神经网络-实例及代码0.8—基于最小均方误差的线性判别函数参数拟合训练

 

3、实例实现的主要步骤

(1)下载数据集,mnist数据集,可以直接去Lecun官网下载

      Lecun MNIST数据集网址:

                                 http://yann.lecun.com/exdb/mnist/

      mnist数据集介绍可以参考这篇文章:

                                  深度学习-卷积神经网络-实例及代码0.9—MNIST数据集介绍、下载及基本操作

(2)获取mnist数据集操作的python包,github上有

       Github项目地址:

                               tensorfow操作mnist数据集python包-Github

(3)编写代码

包括建立模型、训练模型和评估模型

利用MNIST训练集mnist.image训练网络模型

利用MNIST测试集mnist.test测试结果进行模型评估

      

4、实例代码分析                                 

本实例项目Github地址(如果对你有所帮助,欢迎关注点赞~):

                        https://github.com/firemonkeygit/DeepLearningTensorflowMNIST

参考MnistTrainBase.py文件,经过调试可用

注意导入操作mnist数据集的python包和配置正确的数据集路径

 

代码执行结果:loss is: 3142.896240234375,acc is:0.9110999703407288

 

主要源代码文件MnistTrainBase.py及说明如下:


import tensorflow from tf
from TensorflowTest.mnist import imput_data

#读取mnist数据集
mnist=input_data.read_data_sets('../../MNIST_data',one_hot=True)

#图像输入,占位符,类似于函数变量
x=tf.placeholder('float',[None,784])
#图像标签,目标输出,占位符,类似于函数变量
yLabel=tf.placeholder('float',[None,10])

#网络权值参数,待训练拟合
w=tf.Variable(tf.zeros([784,10]))
#偏置参数,待训练拟合
b=tf.Variable(tf.zeros([10]))
#根据网络模型实际输出
y=tf.nn.softmax(tf.matmul(x,w)+b)

#损失函数,代价函数,类似机器学习中的准则函数
loss=-tf.reduce_sum(yLabel*tf.log(y))
#优化器采用梯度下降,优化准则为最小化损失函数
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(loss)

#模型预测正确与否的序列
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(yLabel,1))
#模型预测的正确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,'float'))

#tensorflow中的变量初始化,这是基础
init=tf.global_variables_initializer()
with tf.Session() as sess:
	with tf.device("/cpu:0"):
		sess.run(init)
		for i in range(1000):
			batch_xs,batch_ys=mnist.train.next_batch(100)
            #使用训练集的batch执行训练
			sess.run(train_step,feed_dict={x:batch_xs,yLabel:batch_ys})
            #使用测试集计算模型损失值和预测正确率
			lossValue,accuracyValue=sess.run([loss,accuracy],feed_dict={x:mnist.test.images,yLabel:mnist.test.labels})
            #使用测试集计算模型的预测结果
			prediction_result=sess.run(tf.argmax(y,1),feed_dict={x:mnist.test.images})
        
        #打印模型最终的损失值和计算结果
        print("loss is :{0},acc is:{1} ".format(lossValue,accuracyValue))

 

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
下面是一个使用 TensorFlow 实现 MNIST 数据集的两个隐藏层全连接神经网络的示例代码: ``` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 载入 MNIST 数据集 mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # 定义网络参数 n_input = 784 # 输入层神经元数量(28*28) n_hidden_1 = 256 # 第一个隐含层神经元数量 n_hidden_2 = 256 # 第二个隐含层神经元数量 n_classes = 10 # 输出层神经元数量(0~9) # 定义占位符 x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) # 定义权重和偏置项 weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } # 构建模型 def multilayer_perceptron(x): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # 定义损失函数和优化器 pred = multilayer_perceptron(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) # 初始化变量 init = tf.global_variables_initializer() # 训练模型 with tf.Session() as sess: sess.run(init) for epoch in range(100): avg_cost = 0. total_batch = int(mnist.train.num_examples / 100) for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(100) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) avg_cost += c / total_batch if epoch % 10 == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) print("Optimization Finished!") # 测试模型 correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) ``` 这段代码定义了一个包含两个隐含层的全连接神经网络,使用 ReLU 激活函数,交叉熵作为损失函数,Adam 优化器进行优化,最终输出模型的准确率。在训练过程中,每个 epoch 会遍历整个训练集,使用批量梯度下降进行参数更新。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值