mnist 全连接单隐层

简介:


'''
sess
input,hidden,output,w,b
hidden:relu,dropout
relu(wx+b)
output:softmax(wx+b)
label y_
cross-entropy
train
initial
accuracy
test
save
restore
'''

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

file = './MNIST/MNIST_data/'
mnist = input_data.read_data_sets(file,one_hot=True)
sess = tf.InteractiveSession()

input_units = 784
hidden_units = 300
x = tf.placeholder(dtype=tf.float32,shape=[None,input_units],name='x')
# W1 = tf.Variable(tf.zeros(shape=[input_units,hidden_units]))
W1 = tf.Variable(tf.truncated_normal(shape=[input_units,hidden_units],stddev=0.1))
b1 = tf.Variable(tf.zeros(shape=[hidden_units]))
W2 = tf.Variable(tf.zeros(shape=[hidden_units,10]))
b2 = tf.Variable(tf.zeros(shape=[10]))
keep_prob = tf.placeholder(tf.float32)

hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1)
hidden1_drop = tf.nn.dropout(hidden1,keep_prob=keep_prob)


y = tf.nn.softmax(tf.matmul(hidden1_drop,W2) + b2)

y_ = tf.placeholder(dtype=tf.float32,shape=[None,10],name='y_')

cross_entropy = tf.reduce_mean(-tf.reduce_sum(input_tensor=y_*tf.log(y),reduction_indices=[1]))

# train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)#0.977
# train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)#0.975
train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)#0.98

saver = tf.train.Saver()

tf.global_variables_initializer().run()

for i in range(3000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run(feed_dict={x:batch_xs, y_:batch_ys, keep_prob:0.75})


correct_prediction = tf.equal(tf.argmax(input=y, axis=1),tf.argmax(input=y_, axis=1))

accuracy = tf.reduce_mean(tf.cast(x=correct_prediction,dtype=tf.float32))
save_path = saver.save(sess=sess, save_path='./model_mnist.ckpt')

test_accuracy = accuracy.eval({x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})
print(test_accuracy)

saver.restore(sess,'./model_mnist.ckpt')
result = accuracy.eval({x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})

print(result)

目录
相关文章
|
3月前
|
机器学习/深度学习 算法 PyTorch
pytorch实现手写数字识别 | MNIST数据集(全连接神经网络)
pytorch实现手写数字识别 | MNIST数据集(全连接神经网络)
|
10月前
|
机器学习/深度学习 PyTorch 算法框架/工具
PyTorch: nn网络层-卷积层
PyTorch: nn网络层-卷积层
73 0
|
9月前
|
机器学习/深度学习 存储 数据可视化
基于 MNIST 数据集的 Pytorch 卷积自动编码器
基于 MNIST 数据集的 Pytorch 卷积自动编码器
|
11月前
|
计算机视觉
使用VGG网络进行MNIST图像分类
使用VGG网络进行MNIST图像分类
108 0
|
11月前
|
计算机视觉
VGG的成功之处在哪
VGG的成功之处在哪
131 0
|
11月前
|
机器学习/深度学习
如何搭建VGG网络,实现Mnist数据集的图像分类
如何搭建VGG网络,实现Mnist数据集的图像分类
85 0
|
11月前
|
机器学习/深度学习 算法 PyTorch
Pytorch全连接神经网络实现手写数字识别
Pytorch全连接神经网络实现手写数字识别
106 0
|
PyTorch 算法框架/工具
ResNet残差网络Pytorch实现——cifar10数据集训练
ResNet残差网络Pytorch实现——cifar10数据集训练
250 0
|
PyTorch 算法框架/工具
ResNet残差网络Pytorch实现——cifar10数据集的预测
ResNet残差网络Pytorch实现——cifar10数据集的预测
160 0
|
PyTorch 算法框架/工具 索引
Pytorch教程[05]torch.nn---卷积、池化、线性、激活函数层
Pytorch教程[05]torch.nn---卷积、池化、线性、激活函数层
Pytorch教程[05]torch.nn---卷积、池化、线性、激活函数层