使用多层神经网络进行分类实验
使用多层神经网络进行分类实验
孟飞阳 发表于8个月前
使用多层神经网络进行分类实验
  • 发表于 8个月前
  • 阅读 4
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

已经学到这篇教程的第十章啦!教程的数学背景清晰、讲述深浅适宜,实在是居家必备: 
http://mooc.guokr.com/note/16274/

神经网络的非线性能力

在线性回归模型中,可以引入特征量的非线性映射来得到非线性的拟合效果。比如,使用线性模型可以拟合y=Ax2+Bx+C 中的参数 A,B,C,只要人为引入第二特征x2即可。 然而,当特征很多时,产生额外的高次项的个数为O(n2),往往超过计算能力。 此外,很多非线性的场景用多项式很难稳定拟合。为此,神经网络被提出来了。 
神经网络使用一个非线性的核函数来获得非线性能力。通过突触的权,使得特征在各层传递。

设计一个三类分类器

在下面的例子里,我们来设计2个圆形边界,把2维平面分为3个区域,0区域在两个圆外;1区域属于圆1,2区域属于圆2. 通过圆心与半径,控制两圆不重叠。

from __future__ import print_function
import tensorflow as tf
import numpy as np
n = 2      # 2 features
m = 20000  #  data  sets
K = 3      #3 output classes
#generate a circle region at center and size is R
center1 = np.random.rand(2).astype(np.float32)/4 + 0.5
center2 = -1 * np.random.rand(2).astype(np.float32)/4 - 0.5
r1 = np.random.rand(1).astype(np.float32) * 0.1 + 0.4
r2 = np.random.rand(1).astype(np.float32) * 0.1 + 0.4

print ("center1 = ",center1,",r1 = ", r1)            
print ("center2 = ",center2,",r2 = ", r2,"\n")            
print ("training...")
#--------------------------------------------------------------
#create graph
s1 = n
a1 = tf.placeholder(tf.float32,[None,s1]) 

s2 = 17
W1 = tf.Variable(tf.random_uniform([s1,s2],-1,1))
b1 = tf.Variable(tf.random_uniform([1],-1,1)) 
z1 = tf.matmul(a1,W1) + b1*tf.ones([1,s2])
a2 = tf.nn.sigmoid(z1)

s3 = 17
W2 = tf.Variable(tf.random_uniform([s2,s3],-1,1))
b2 = tf.Variable(tf.random_uniform([1],-1,1)) 
z2 = tf.matmul(a2,W2) + b2*tf.ones([1,s3])
a3 = tf.nn.sigmoid(z2)

s4 = 17
W3 = tf.Variable(tf.random_uniform([s3,s4],-1,1))
b3 = tf.Variable(tf.random_uniform([1],-1,1)) 
z3 = tf.matmul(a3,W3) + b3*tf.ones([1,s4])
a4 = tf.nn.sigmoid(z3)

s5 = 17
W4 = tf.Variable(tf.random_uniform([s4,s5],-1,1))
b4 = tf.Variable(tf.random_uniform([1],-1,1)) 
z4 = tf.matmul(a4,W4) + b4*tf.ones([1,s5])
a5 = tf.nn.sigmoid(z4)


##output
s6 = 3
W5 = tf.Variable(tf.random_uniform([s5,s6],-1,1))
b5 = tf.Variable(tf.random_uniform([1],-1,1)) 
z5 = tf.matmul(a5,W5) + b5*tf.ones([1,s6])
a6 = tf.nn.sigmoid(z5)
#--------------------------------------------------------------
y_ = tf.placeholder(tf.float32,[None,K])
loss = tf.reduce_mean(tf.square(a6-y_))
optimizer = tf.train.AdamOptimizer()
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
#--------------------------------------------------------------
### create tensorflow structure end ###
sess = tf.Session()
sess.run(init)          # Very important

#generate trainning data between (-1,1)
x_data = np.random.rand(m,n).astype(np.float32) * 2 - 1
#calc the y for each training sets
y_data = np.zeros([m,K]).astype(np.float32)
for idx in range(m):
    if (x_data[idx,0] - center1[0])**2 + (x_data[idx,1] - center1[1])**2 <= r1**2:
        y_data[idx,1] = 1
    elif (x_data[idx,0] - center2[0])**2 + (x_data[idx,1] - center2[1])**2 <= r2**2:
        y_data[idx,2] = 1
    else:
        y_data[idx,0] = 1


for step in range(10000):
    sess.run(train,feed_dict={a1:x_data,y_:y_data})
    if step % 1000 == 0:
        print(step, sess.run(loss,feed_dict={a1:x_data,y_:y_data}))
        #generate trainning data between (-1,1)
        x_data = np.random.rand(m,n).astype(np.float32) * 2 - 1
        #calc the y for each training sets
        y_data = np.zeros([m,K]).astype(np.float32)
        for idx in range(m):
            if (x_data[idx,0] - center1[0])**2 + (x_data[idx,1] - center1[1])**2 <= r1**2:
                y_data[idx,1] = 1
            elif (x_data[idx,0] - center2[0])**2 + (x_data[idx,1] - center2[1])**2 <= r2**2:
                y_data[idx,2] = 1
            else:
                y_data[idx,0] = 1

#--------------------------------------------------------------
print ("Testing...")
#testing
t = 10000
x_test = np.random.rand(t,n).astype(np.float32) * 2 - 1
#calc the y for each training sets
y_test = np.zeros([t,K]).astype(np.float32)
for idx in range(t):
    if (x_test[idx,0] - center1[0])**2 + (x_test[idx,1] - center1[1])**2 <= r1**2:
        y_test[idx,1] = 1
    elif (x_test[idx,0] - center2[0])**2 + (x_test[idx,1] - center2[1])**2 <= r2**2:
        y_test[idx,2] = 1
    else:
        y_test[idx,0] = 1
#classification
result = sess.run(a6,feed_dict={a1:x_test,y_:y_test})

good = 0
#check
for idx in range(t):
    col_u = np.where(result[idx,:]==np.amax(result[idx,:]))[0][0]
    if (y_test[idx,col_u]==1):
        good = good + 1

rates = good * 100.0 /t
print ("OK rates = ",rates,"%\n")

运行结果如下:

center1 =  [ 0.5108884   0.50474548] ,r1 =  [ 0.46310282]
center2 =  [-0.55810225 -0.70666814] ,r2 =  [ 0.48871851] 

training...
0 0.545082
1000 0.114368
2000 0.040274
3000 0.0257151
4000 0.0227888
5000 0.0210803
6000 0.0192277
7000 0.0148897
8000 0.00719382
9000 0.00347398
Testing...
OK rates =  99.74 %

 

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 191
博文 851
码字总数 523174
作品 5
×
孟飞阳
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: