tensorflow就该这么学--6(多层神经网络)

一、线性问题和非线性问题

1、线性问题

某医院想用神经网络对已经有的病例进行分类,数据样本特征x包括病人的年龄x1和肿瘤的大小x2,(x[x1,x2]),对应的标签为良性或恶性(0、1)

二分类:

(1)生成数据集

  1. import tensorflow as tf  
  2. import matplotlib.pyplot as plt  
  3. import numpy as np  
  4. from sklearn.utils import shuffle  
  5.   
  6.   
  7. #模拟数据点     
  8. def generate(sample_size, mean, cov, diff,regression):     
  9.     num_classes = 2 #len(diff)  
  10.     samples_per_class = int(sample_size/2)  
  11.   
  12.     X0 = np.random.multivariate_normal(mean, cov, samples_per_class)  
  13.     Y0 = np.zeros(samples_per_class)  
  14.       
  15.     for ci, d in enumerate(diff):  
  16.         # ci=0 d=3  
  17.         X1 = np.random.multivariate_normal(mean+d, cov, samples_per_class)  
  18.         Y1 = (ci+1)*np.ones(samples_per_class)  
  19.       
  20.         X0 = np.concatenate((X0,X1))  
  21.         Y0 = np.concatenate((Y0,Y1))  
  22.           
  23.     if regression==False#one-hot  0 into the vector "1 0  
  24.         class_ind = [Y==class_number for class_number in range(num_classes)]  
  25.         Y = np.asarray(np.hstack(class_ind), dtype=np.float32)  
  26.     X, Y = shuffle(X0, Y0)  
  27.       
  28.     return X,Y      
  29.   
  30.   
  31. input_dim = 2                      
  32. np.random.seed(10)  
  33. num_classes =2  
  34. mean = np.random.randn(num_classes)  
  35. cov = np.eye(num_classes)   
  36. X, Y = generate(1000, mean, cov, [3.0],True)  
  37. colors = ['r' if l == 0 else 'b' for l in Y[:]]  
  38. plt.scatter(X[:,0], X[:,1], c=colors)  
  39. plt.xlabel("Scaled age (in yrs)")  
  40. plt.ylabel("Tumor size (in cm)")  
  41. plt.show()  

(2)构建网络模型

  1. lab_dim = 1  
  2. # tf Graph Input  
  3. input_features = tf.placeholder(tf.float32, [None, input_dim])  
  4. input_lables = tf.placeholder(tf.float32, [None, lab_dim])  
  5. # Set model weights  
  6. W = tf.Variable(tf.random_normal([input_dim,lab_dim]), name="weight")  
  7. b = tf.Variable(tf.zeros([lab_dim]), name="bias")  
  8.   
  9. output =tf.nn.sigmoid( tf.matmul(input_features, W) + b)  
  10. cross_entropy = -(input_lables * tf.log(output) + (1 - input_lables) * tf.log(1 - output))  
  11. ser= tf.square(input_lables - output)  
  12. loss = tf.reduce_mean(cross_entropy)  
  13. err = tf.reduce_mean(ser)  
  14. optimizer = tf.train.AdamOptimizer(0.04#尽量用这个--收敛快,会动态调节梯度  
  15. train = optimizer.minimize(loss)  # let the optimizer train  

(3)训练

  1. maxEpochs = 50  
  2. minibatchSize = 25  
  3.   
  4. # 启动session  
  5. with tf.Session() as sess:  
  6.     sess.run(tf.global_variables_initializer())  
  7.   
  8.     for epoch in range(maxEpochs):  
  9.         sumerr=0  
  10.         for i in range(np.int32(len(Y)/minibatchSize)):  
  11.             x1 = X[i*minibatchSize:(i+1)*minibatchSize,:]  
  12.             y1 = np.reshape(Y[i*minibatchSize:(i+1)*minibatchSize],[-1,1])  
  13.             tf.reshape(y1,[-1,1])  
  14.             _,lossval, outputval,errval = sess.run([train,loss,output,err], feed_dict={input_features: x1, input_lables:y1})  
  15.             sumerr =sumerr+errval  
  16.   
  17.         print ("Epoch:"'%04d' % (epoch+1), "cost=","{:.9f}".format(lossval),"err=",sumerr/minibatchSize)  
  18.           

(4)可视化

  1. train_X, train_Y = generate(100, mean, cov, [3.0],True)  
  2.     colors = ['r' if l == 0 else 'b' for l in train_Y[:]]  
  3.     plt.scatter(train_X[:,0], train_X[:,1], c=colors)  
  4.     #plt.scatter(train_X[:, 0], train_X[:, 1], c=train_Y)  
  5.     #plt.colorbar()  
  6.   
  7.   
  8. #    x1w1+x2*w2+b=0  
  9. #    x2=-x1* w1/w2-b/w2  
  10. #     a*x+b*y+c = 0  
  11.       
  12.     x = np.linspace(-1,8,200)   
  13.     y=-x*(sess.run(W)[0]/sess.run(W)[1])-sess.run(b)/sess.run(W)[1]  
  14.     plt.plot(x,y, label='Fitted line')  
  15.     plt.legend()  
  16.     plt.show()   

多分类:

  1. import tensorflow as tf  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4.   
  5. from sklearn.utils import shuffle  
  6. from matplotlib.colors import colorConverter, ListedColormap   
  7.       
  8. # 对于上面的fit可以这么扩展变成动态的  
  9. from sklearn.preprocessing import OneHotEncoder  
  10. def onehot(y,start,end):  
  11.     ohe = OneHotEncoder()  
  12.     a = np.linspace(start,end-1,end-start)  
  13.     b =np.reshape(a,[-1,1]).astype(np.int32)  
  14.     ohe.fit(b)  
  15.     c=ohe.transform(y).toarray()    
  16.     return c       
  17. #  
  18.       
  19. def generate(sample_size, num_classes, diff,regression=False):  
  20.     np.random.seed(10)  
  21.     mean = np.random.randn(2)  
  22.     cov = np.eye(2)    
  23.       
  24.     #len(diff)  
  25.     samples_per_class = int(sample_size/num_classes)  
  26.   
  27.     X0 = np.random.multivariate_normal(mean, cov, samples_per_class)  
  28.     Y0 = np.zeros(samples_per_class)  
  29.       
  30.     for ci, d in enumerate(diff):  
  31.         X1 = np.random.multivariate_normal(mean+d, cov, samples_per_class)  
  32.         Y1 = (ci+1)*np.ones(samples_per_class)  
  33.       
  34.         X0 = np.concatenate((X0,X1))  
  35.         Y0 = np.concatenate((Y0,Y1))  
  36.         #print(X0, Y0)  
  37.       
  38.     
  39.     if regression==False#one-hot  0 into the vector "1 0  
  40.         Y0 = np.reshape(Y0,[-1,1])          
  41.         #print(Y0.astype(np.int32))  
  42.         Y0 = onehot(Y0.astype(np.int32),0,num_classes)  
  43.         #print(Y0)  
  44.     X, Y = shuffle(X0, Y0)  
  45.     #print(X, Y)  
  46.     return X,Y      
  47.   
  48.    
  49. # Ensure we always get the same amount of randomness  
  50. np.random.seed(10)  
  51.   
  52. input_dim = 2  
  53. num_classes =3   
  54. X, Y = generate(2000,num_classes,  [[3.0],[3.0,0]],False)  
  55. aa = [np.argmax(l) for l in Y]  
  56. colors =['r' if l == 0 else 'b' if l==1 else 'y' for l in aa[:]]  
  57.   
  58. plt.scatter(X[:,0], X[:,1], c=colors)  
  59. plt.xlabel("Scaled age (in yrs)")  
  60. plt.ylabel("Tumor size (in cm)")  
  61. plt.show()  
  62.   
  63. lab_dim = num_classes  
  64. # tf Graph Input  
  65. input_features = tf.placeholder(tf.float32, [None, input_dim])  
  66. input_lables = tf.placeholder(tf.float32, [None, lab_dim])  
  67. # Set model weights  
  68. W = tf.Variable(tf.random_normal([input_dim,lab_dim]), name="weight")  
  69. b = tf.Variable(tf.zeros([lab_dim]), name="bias")  
  70. output = tf.matmul(input_features, W) + b  
  71.   
  72. z = tf.nn.softmax( output )  
  73.   
  74. a1 = tf.argmax(tf.nn.softmax( output ), axis=1)#按行找出最大索引,生成数组  
  75. b1 = tf.argmax(input_lables, axis=1)  
  76. err = tf.count_nonzero(a1-b1) #两个数组相减,不为0的就是错误个数  
  77.   
  78. cross_entropy = tf.nn.softmax_cross_entropy_with_logits( labels=input_lables,logits=output)  
  79. loss = tf.reduce_mean(cross_entropy)#对交叉熵取均值很有必要  
  80.   
  81.   
  82.   
  83. optimizer = tf.train.AdamOptimizer(0.04#尽量用这个--收敛快,会动态调节梯度  
  84. train = optimizer.minimize(loss)  # let the optimizer train  
  85.   
  86. maxEpochs = 50  
  87. minibatchSize = 25  
  88.   
  89. # 启动session  
  90. with tf.Session() as sess:  
  91.     sess.run(tf.global_variables_initializer())  
  92.       
  93.     for epoch in range(maxEpochs):  
  94.         sumerr=0  
  95.         for i in range(np.int32(len(Y)/minibatchSize)):  
  96.             x1 = X[i*minibatchSize:(i+1)*minibatchSize,:]  
  97.             y1 = Y[i*minibatchSize:(i+1)*minibatchSize,:]  
  98.   
  99.             _,lossval, outputval,errval = sess.run([train,loss,output,err], feed_dict={input_features: x1, input_lables:y1})  
  100.             sumerr =sumerr+(errval/minibatchSize)  
  101.   
  102.         print ("Epoch:"'%04d' % (epoch+1), "cost=","{:.9f}".format(lossval),"err=",sumerr/minibatchSize)  
  103.    
  104.     train_X, train_Y = generate(200,num_classes,  [[3.0],[3.0,0]],False)  
  105.     aa = [np.argmax(l) for l in train_Y]          
  106.     colors =['r' if l == 0 else 'b' if l==1 else 'y' for l in aa[:]]  
  107.     plt.scatter(train_X[:,0], train_X[:,1], c=colors)  
  108.       
  109.     x = np.linspace(-1,8,200)   
  110.   
  111.     y=-x*(sess.run(W)[0][0]/sess.run(W)[1][0])-sess.run(b)[0]/sess.run(W)[1][0]  
  112.     plt.plot(x,y, label='first line',lw=3)  
  113.   
  114.     y=-x*(sess.run(W)[0][1]/sess.run(W)[1][1])-sess.run(b)[1]/sess.run(W)[1][1]  
  115.     plt.plot(x,y, label='second line',lw=2)  
  116.   
  117.     y=-x*(sess.run(W)[0][2]/sess.run(W)[1][2])-sess.run(b)[2]/sess.run(W)[1][2]  
  118.     plt.plot(x,y, label='third line',lw=1)  
  119.       
  120.     plt.legend()  
  121.     plt.show()   
  122.     print(sess.run(W),sess.run(b))  
  123.       
  124.   
  125.     train_X, train_Y = generate(200,num_classes,  [[3.0],[3.0,0]],False)  
  126.     aa = [np.argmax(l) for l in train_Y]          
  127.     colors =['r' if l == 0 else 'b' if l==1 else 'y' for l in aa[:]]  
  128.     plt.scatter(train_X[:,0], train_X[:,1], c=colors)      
  129.       
  130.     nb_of_xs = 200  
  131.     xs1 = np.linspace(-18, num=nb_of_xs)  
  132.     xs2 = np.linspace(-18, num=nb_of_xs)  
  133.     xx, yy = np.meshgrid(xs1, xs2) # create the grid  
  134.     # Initialize and fill the classification plane  
  135.     classification_plane = np.zeros((nb_of_xs, nb_of_xs))  
  136.     for i in range(nb_of_xs):  
  137.         for j in range(nb_of_xs):  
  138.             #classification_plane[i,j] = nn_predict(xx[i,j], yy[i,j])  
  139.             classification_plane[i,j] = sess.run(a1, feed_dict={input_features: [[ xx[i,j], yy[i,j] ]]} )  
  140.       
  141.       
  142.     # Create a color map to show the classification colors of each grid point  
  143.     cmap = ListedColormap([  
  144.             colorConverter.to_rgba('r', alpha=0.30),  
  145.             colorConverter.to_rgba('b', alpha=0.30),  
  146.             colorConverter.to_rgba('y', alpha=0.30)])  
  147.     # Plot the classification plane with decision boundary and input samples  
  148.     plt.contourf(xx, yy, classification_plane, cmap=cmap)  
  149.     plt.show()      
  150.       




2、非线性问题:利用隐藏层的神经网络拟合操作

  1. import tensorflow as tf  
  2. import numpy as np  
  3.   
  4. # 网络结构:2维输入 --> 2维隐藏层 --> 1维输出  
  5.   
  6. learning_rate = 1e-4  
  7. n_input  = 2  
  8. n_label  = 1  
  9. n_hidden = 2  
  10.   
  11.   
  12. x = tf.placeholder(tf.float32, [None,n_input])  
  13. y = tf.placeholder(tf.float32, [None, n_label])  
  14.   
  15. weights = {  
  16.     'h1': tf.Variable(tf.truncated_normal([n_input, n_hidden], stddev=0.1)),  
  17.     'h2': tf.Variable(tf.random_normal([n_hidden, n_label], stddev=0.1))  
  18.     }   
  19. biases = {  
  20.     'h1': tf.Variable(tf.zeros([n_hidden])),  
  21.     'h2': tf.Variable(tf.zeros([n_label]))  
  22.     }      
  23.   
  24.   
  25. layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['h1']))  
  26. #y_pred = tf.nn.tanh(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))  
  27. #y_pred = tf.nn.relu(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))#局部最优解  
  28.   
  29. #y_pred = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['h2']),biases['h2']))  
  30.   
  31. #Leaky relus  40000次 ok  
  32. layer2 =tf.add(tf.matmul(layer_1, weights['h2']),biases['h2'])  
  33. y_pred = tf.maximum(layer2,0.01*layer2)  
  34.     
  35. loss=tf.reduce_mean((y_pred-y)**2)  
  36. train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)  
  37.   
  38. #生成数据  
  39. X=[[0,0],[0,1],[1,0],[1,1]]  
  40. Y=[[0],[1],[1],[0]]  
  41. X=np.array(X).astype('float32')  
  42. Y=np.array(Y).astype('int16')  
  43.   
  44. #加载  
  45. sess = tf.InteractiveSession()  
  46. sess.run(tf.global_variables_initializer())  
  47.   
  48. #训练  
  49. for i in range(10000):  
  50.     sess.run(train_step,feed_dict={x:X,y:Y} )  
  51.   
  52.        
  53. #计算预测值  
  54. print(sess.run(y_pred,feed_dict={x:X}))  
  55. #输出:已训练100000次  
  56.   
  57.          
  58. #查看隐藏层的输出  
  59. print(sess.run(layer_1,feed_dict={x:X}))  

二、网络模型训练过程中可能存在的问题

1、欠拟合

拟合效果没有完全拟合到想要得到的真实数据情况

解决办法:增加节点或增加神经层

2、过拟合

拟合程度过优

解决办法:early stopping 数据集扩增、正则化、dropout


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值