TensorFlow多层感知机实现MINIST分类
生活随笔
收集整理的這篇文章主要介紹了
TensorFlow多层感知机实现MINIST分类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import tensorflow as tf
import tensorflow.contrib.layers as layers
from tensorflow.python import debug as tf_debug#1:網(wǎng)絡(luò)參數(shù)
n_hidden = 30 #隱藏層的神經(jīng)元數(shù)
n_classes = 10 #mnist類別(0-9)
n_input = 784 #mnist尺寸(28*28)
#2:超參數(shù)
batch_size = 200 #每批訓(xùn)練批量大小
eta = 0.001 # 學(xué)習(xí)率
max_epoch = 10 #迭代數(shù)#3:加載mnist數(shù)據(jù)集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
#全連接層,與輸入相乘產(chǎn)生隱藏單元的張量
#隱藏層使用ReLU激活函數(shù)
def multilayer_perceptron(x):fc1 = layers.fully_connected(x,n_hidden,activation_fn=tf.nn.relu,scope='fc1')out = layers.fully_connected(fc1,n_classes,activation_fn=None,scope='out')return out#4:建立模型,損失函數(shù) ,開展訓(xùn)練操作
#輸入x
x = tf.compat.v1.placeholder(tf.float32,[None,n_input],name='placeholder_x')
#標(biāo)簽y
y = tf.compat.v1.placeholder(tf.float32,[None,n_classes],name='placeholder_y')
#多層感知機
y_hat = multilayer_perceptron(x)loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_hat,labels=y))
#Adam梯度優(yōu)化算法
train = tf.train.AdamOptimizer(learning_rate=eta).minimize(loss)#訓(xùn)練
init = tf.global_variables_initializer()
with tf.compat.v1.Session() as sess:sess.run(init)for epoch in range(10):epoch_loss = 0.0batch_step = int(mnist.train.num_examples/batch_size)for i in range(batch_step):batch_x,batch_y = mnist.train.next_batch(batch_size)_, c = sess.run([train,loss],feed_dict={x:batch_x,y:batch_y})epoch_loss +=float(c / batch_step)print("epoch %02d,Loss = %.6f" % (epoch,epoch_loss))#測試模型,評估correct_prediction = tf.equal(tf.argmax(y_hat,1),tf.argmax(y,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))print("Accuracy:{0}".format(accuracy.eval({x:mnist.test.images,y:mnist.test.labels})))
總結(jié)
以上是生活随笔為你收集整理的TensorFlow多层感知机实现MINIST分类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: L1-013. 计算阶乘和
- 下一篇: Python 3 集合基础和概念!