具有一个隐藏层的多层感知机的实现是黄文坚等所著《TensorFlow实战》上的例子。隐含层的输出节点数为300(此模型中隐含层节点数设置为200-1000范围内的结果区别不大)。
训练时的数据没有使用mnist全部数据集,只使用了3000x100个样本。
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
sess = tf.InteractiveSession()
in_units = 784
h1_units = 300
W1 = tf.Variable(tf.truncated_normal([in_units,h1_units],stddev=0.1))
b1 = tf.Variable(tf.zeros([h1_units]))
W2 = tf.Variable(tf.zeros([h1_units,10]))
b2 = tf.Variable(tf.zeros([10]))
x = tf.placeholder(tf.float32,[None,in_units])
#keep_prob参数为保留数据而不置为0的比例,在训练时小于1,用来制造随机性,防止过拟合
#在预测时应该等于1,即使用全部特征来预测样本的类别
keep_prob = tf.placeholder(tf.float32)
#定义算法公式
hidden1 = tf.nn.relu(tf.matmul(x,W1)+b1)
hidden1_drop = tf.nn.dropout(hidden1,keep_prob)
y = tf.nn.softmax(tf.matmul(hidden