tensorfllow实现两层MLP对mnist分类,第一层256个神经元,第二层128个神经元,输入784,输出10分类 #! /usr/bin/python # -*-coding:utf-8 -*- __author__ = "chunming" import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist= input_data.read_data_sets('data/', one_hot=True) trainimg = mnist.train.images trainlabel = mnist.train.labels testimg = mnist.test.images testlabel = mnist.test.labels print (trainimg.shape) print (trainlabel.shape) print (testimg.shape) print (testlabel.shape) print (trainimg) print (trainlabel[0]) n_hidden_1 = 256 n_hidden_2 = 128 n_input = 784 n_classes = 10 x = tf.placeholder("float", [None, n_input]) y = tf.placeholder("float", [None, n_classes]) stddev = 0.1 weights = { 'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),#正太分布的标准差为0.1 '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.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, _weights, _biases): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1'])) layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2'])) return (tf.matmul(layer_2, _weights['out']) + _biases['out']) pred = multilayer_perceptron(x, weights, biases) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=pred,name="loss")) optm = tf.train.GradientDescentOptimizer(0.001) train=optm.minimize(loss) corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accr = tf.reduce_mean(tf.cast(corr, "float")) init = tf.global_variables_initializer() training_epochs = 500 batch_size = 100 display_step = 5 sess = tf.Session() sess.run(init) for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) feeds = {x: batch_xs, y: batch_ys} sess.run(train, feed_dict=feeds) avg_cost += sess.run(loss, feed_dict=feeds) avg_cost = avg_cost / total_batch if epoch % display_step == 0: print("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost)) feeds = {x: batch_xs, y: batch_ys} train_acc = sess.run(accr, feed_dict=feeds) print("TRAIN ACCURACY: %.3f" % (train_acc)) feedstest = {x: mnist.test.images, y: mnist.test.labels} test_acc = sess.run(accr, feed_dict=feedstest) print("TEST ACCURACY: %.3f" % (test_acc))