TensorFlow实现多层感知器

来源:互联网 发布:vmware怎么安装mac os 编辑:程序博客网 时间:2024/04/28 06:16

TensorFlow实现多层感知器

1 多层感知器的原理

要讲解多层感知器,首先要讲的是单层感知器。所谓单层感知器,就是最简单的神经网络。它包含输入层和输出层,而输入层和输出层是直接相连的。如下图所示:

如上图所示,整个网络中只有输入层和输出层,并没有隐含层。因此,其输出值为:

使用Python实现单层感知器:

def slp_output(inputNode, weights, num_input, threshold):# inputNode是输入节点的值,可以写成tuple或者list的形式# weights是输入到输出的权重值,也可以写成tuple或者list的形式# num_input是输入节点的数量,threshold是阈值    if len(inputNode) == 0 or len(weights) == 0:        print("Please check your parameters!")        return False    sum = 0.0    for i in range(num_input):        sum += weights[i]*inputNode[i]    if sum >= threshold:        return 1    else:        return 0

这时,我们使用它(单层感知器)解决与或非的问题。
首先,网络结构图,如下:

调用上面已经写好的单层感知器的函数,

if __name__ == '__main__':    print("使用单感知器实现“与”的功能:")    andresult1 = slp_output((0,0),(1,1), num_input=2, threshold=2)    andresult2 = slp_output((0,1), (1,1), num_input=2, threshold=2)    andresult3 = slp_output((1, 0), (1, 1), num_input=2, threshold=2)    andresult4 = slp_output((1, 1), (1, 1), num_input=2, threshold=2)    print("x1: 0  x2: 0 ->", andresult1)    print("x1: 0  x2: 1 ->", andresult2)    print("x1: 1  x2: 0 ->", andresult3)    print("x1: 1  x2: 1 ->", andresult4)    print("----------------------")    print("使用单层感知器实现“或”的功能:")    orresult1 = slp_output((0,0),(1,1),2,1)    orresult2 = slp_output((0, 1), (1, 1), 2, 1)    orresult3 = slp_output((1, 0), (1, 1), 2, 1)    orresult4 = slp_output((1, 1), (1, 1), 2, 1)    print("x1: 0  x2: 0 ->", orresult1)    print("x1: 0  x2: 1 ->", orresult2)    print("x1: 1  x2: 0 ->", orresult3)    print("x1: 1  x2: 1 ->", orresult4)    print("----------------------")    print("使用单层感知器实现“非”的功能:")    notresult1 = slp_output((0,),(-1,),1,0)    notresult2 = slp_output((1,),(-1,),1,0)    print("x:0 ->", notresult1)    print("x:1 ->", notresult2)

运行结果:

至此,我们已经使用单层感知器解决了与或非的问题。然而,单层感知器并不能解决异或额度问题。下面画图简单说明。



显然,不能用一条直线将两个结果分开,而单层感知器,由定义可知,只能解决线性的问题。而要解决类似异或这种非线性的问题,我们需要引入多层感知器。

实际上,多层感知器就是在单层感知器的基础上加上一层或者多层的隐含层。

加入隐含层之后,就引入了非线性,理论上只要隐含层越多,即使只有一个隐含层的神经网络也可以拟合任意函数。同时隐含层越多,越容易拟合复杂的函数。而且层数越多,神经网络的所需要的隐含节点可以越少。然而,在实际应用中,层数较深的神经网络中,会遇到很多问题,比如容易造成过拟合,参数难以调试、梯度弥散等等。针对这些方法,我们采取了很多的措施,比如:Dropout、Adagrad、ReLU等,可参考:

Dropout: http://jmlr.org/papers/v15/srivastava14a.html
Adagrad: http://dl.acm.org/citation.cfm?id=2021068
ReLU: http://xueshu.baidu.com/s?wd=paperuri%3A(b84f8ba85145176b74b953868c19962c)&filter=sc_long_sign&tn=SE_baiduxueshu_c1gjeupa&ie=utf-8&sc_ks_para=q%3Dcorrection%3A%20Digital%20selection%20and%20analogue%20amplification%20coexist%20in%20acortex-inspired%20silicon%20circuit

2 编程实现

# -*- coding:utf-8 -*-from tensorflow.examples.tutorials.mnist import input_dataimport osimport tensorflow as tfos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'mnist = input_data.read_data_sets("./MNIST_data",one_hot=True)sess = tf.InteractiveSession()in_units = 784h1_units = 300w1 = 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 = 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(hidden1_drop,w2)+b2)y_ = tf.placeholder(tf.float32,[None,10])cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)#train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 0.9784#train_step = tf.train.AdadeltaOptimizer(0.7).minimize(cross_entropy) # 0.9544tf.global_variables_initializer().run()for i in range(3000):    batch_xs,batch_ys = mnist.train.next_batch(100)    train_step.run({x:batch_xs,y_:batch_ys,keep_prob:0.75})correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))

3 实验结果



这是使用Adagrad优化的结果。

下面显示梯度下降和Adadelta的结果:

显然,使用多层感知器,识别的效果比之前的没有隐含层的Softmax回归好了很多。

至此,我们完成了Tensoflow多层感知器的构建!