二隐层的神经网络实现MNIST数据集分类
生活随笔
收集整理的這篇文章主要介紹了
二隐层的神经网络实现MNIST数据集分类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?二隱層的神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)MNIST數(shù)據(jù)集分類
傳統(tǒng)的人工神經(jīng)網(wǎng)絡(luò)包含三部分,輸入層、隱藏層和輸出層。對(duì)于一個(gè)神經(jīng)網(wǎng)絡(luò)模型的確定需要考慮以下幾個(gè)方面:
- 隱藏層的層數(shù)以及各層的神經(jīng)元數(shù)量
- 各層激活函數(shù)的選擇
- 輸入層輸入數(shù)據(jù)的shape
- 輸出層神經(jīng)元的數(shù)量
以上神經(jīng)網(wǎng)絡(luò)的骨架確定之后,則相應(yīng)的權(quán)重和偏置所對(duì)應(yīng)的shape也隨之確定,即網(wǎng)絡(luò)結(jié)構(gòu)的確定。
下面的代碼是通過二隱層的神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)MNIST手寫數(shù)字的分類,下圖為該神經(jīng)網(wǎng)絡(luò)的網(wǎng)絡(luò)結(jié)構(gòu):
?
# 用兩隱層神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)手寫數(shù)字(mnist)分類 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as pltmnist = input_data.read_data_sets('D:\MNIST_data', one_hot=True)n_hidden_1 = 256 n_hidden_2 = 128 n_input = 784 n_classes = 10# INPUT AND OUTPUT x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes])# NETWORK PARAMETERS stddev = 0.1 weights = {"w1": tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),"w2": tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),"out": tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev)) } biases = {"b1": tf.Variable(tf.zeros([n_hidden_1], tf.float32)),"b2": tf.Variable(tf.zeros([n_hidden_2], tf.float32)),"out": tf.Variable(tf.zeros([n_classes], tf.float32)) }def network(inputs, weights, biases):layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(inputs, weights['w1']), biases['b1']))layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['w2']), biases['b2']))pre = tf.matmul(layer_2, weights['out']) + biases['out']return prepred = network(x, weights, biases)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) train = tf.train.GradientDescentOptimizer(0.001).minimize(cost) acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(acc, tf.float32))init = tf.global_variables_initializer()train_step = 500 batch_size = 100 display_step = 10with tf.Session() as sess:sess.run(init)for k in range(train_step):loss = 0num_batch = int(mnist.train.num_examples/batch_size)for L in range(num_batch):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(train, feed_dict={x: batch_xs, y: batch_ys})_loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})loss += _lossif k % display_step == 0:_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})print('loss:%2f' % loss, ' accuracy:%2f' % _accuracy)訓(xùn)練500次之后,測(cè)試精度為:
loss:167.206619 accuracy:0.916900
?
總結(jié)
以上是生活随笔為你收集整理的二隐层的神经网络实现MNIST数据集分类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字符集和编码规范:ASCII,Unico
- 下一篇: 混淆矩阵及分类性能评估方法