这一章我们讲MLP 多层感知器 的使用,多层感知器 ,常用来做分类,效果非常好,比如文本分类,效果比SVM 贝叶斯 好多了,这些以前的机器学习很有名的算法,我现在基本不用它们,现在是深度学习 的AI时代。
多层感知器的介绍
MLP(多层感知器)神经网络是常见的ANN算法,它由一个输入层,一个输出层和一个或多个隐藏层组成。
在MLP中的所有神经元都差不多,每个神经元都有几个输入(连接前一层)神经元和输出(连接后一层)神经元,该神经元会将相同值传递给与之相连的多个输出神经元
一个神经网络训练网将一个特征向量作为输入,将该向量传递到隐藏层,然后通过权重和激励函数来计算结果,并将结果传递给下一层,直到最后传递给输出层才结束
首先我们来
下面是一个2层的多层感知器
其中 relu可以换成 tanh或者sigmoid
比如
tf.nn.sigmoid(tf.matmul(X, w_h)) #WX+B
def multilayer_perceptron(_X, _weights, _biases): layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) #Hidden layer with RELU activation layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) #Hidden layer with RELU activation return tf.matmul(layer_2, _weights['out']) + _biases['out']# Store layers weight & biasweights = { 'h1': tf.Variable(tf.random_normal([n_input, 256])), 'h2': tf.Variable(tf.random_normal([256, 256])), 'out': tf.Variable(tf.random_normal([256, 10]))}biases = { 'b1': tf.Variable(tf.random_normal([256])), 'b2': tf.Variable(tf.random_normal([256])), 'out': tf.Variable(tf.random_normal([10]))}
或者 修改成使用sigmoid
linear----线性感知器
tanh----双曲正切函数
sigmoid----双曲函数
softmax----1/(e(net) * e(wi*xi- shift))
log-softmax---- log(1/(e(net) * e(wi*xi)))
exp----指数函数
softplus----log(1+ e(wi*xi))
def multilayer_perceptron(_X, _weights, _biases): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) #Hidden layer with sigmoid activation layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) #Hidden layer with RELU activation return tf.matmul(layer_2, _weights['out']) + _biases['out']
import input_datamnist = input_data.read_data_sets("/tmp/data/", one_hot=True)import tensorflow as tf# Parameterslearning_rate = 0.001training_epochs = 15batch_size = 100display_step = 1# Network Parametersn_hidden_1 = 256 # 1st layer num featuresn_hidden_2 = 256 # 2nd layer num featuresn_input = 784 # MNIST data input (img shape: 28*28)n_classes = 10 # MNIST total classes (0-9 digits)# tf Graph inputx = tf.placeholder("float", [None, n_input])y = tf.placeholder("float", [None, n_classes])# Create modeldef multilayer_perceptron(_X, _weights, _biases): layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) #Hidden layer with sigmoid activation layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) #Hidden layer with RELU activation return tf.matmul(layer_2, _weights['out']) + _biases['out']# Store layers weight & biasweights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))}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]))}# Construct modelpred = multilayer_perceptron(x, weights, biases)# Define loss and optimizercost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) # Softmax lossoptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer# Initializing the variablesinit = tf.initialize_all_variables()# Launch the graphwith tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) # Fit training using batch data sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys}) # Compute average loss avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch # Display logs per epoch step if epoch % display_step == 0: print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost) print "Optimization Finished!" # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
下面我们运行测试 代码