1. 程式人生 > >python機器學習算法系列之初識神經網路分類

python機器學習算法系列之初識神經網路分類

下面的例子是區分數字如下圖:


在程式中通過下面語句就可以自動下載資料集

mnist=input_data.read_data_sets('MNIST_data',one_hot=True) 
但是有時候會出錯,那就需要大家手動下載,它包括四個壓縮檔案,下載統一後放在python工作目錄(注意不需要手動解壓,直接放就可以),然後將上面的語句改為
mnist=input_data.read_data_sets('.',one_hot=True)
其中的"."代表當前資料夾,它會自己尋找到檔案並解壓。關於這四個檔案資源和該資料集內部構成,這裡有一篇文章

MNIST 資料下載寫得非常清楚,大家自行觀看。

程式如下:

#tensorflow分類
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#產生資料
mnist=input_data.read_data_sets('.',one_hot=True)     #載入資料

#定義神經層
def add_layer(inputs,in_size,out_size,n_layer,activation_function=None):
    layer_name='layer%s'%n_layer
    with tf.name_scope('ayer_name'):                                                       #視覺化
        with tf.name_scope('weignts'):
            Weignts=tf.Variable(tf.random_normal([in_size,out_size]),name='W')             #權重
            tf.summary.histogram(layer_name+'/weights',Weignts)                            #為了通過瀏覽器觀察每一神經層的權重
        with tf.name_scope('weignts'):                                                     #視覺化
            biases=tf.Variable(tf.zeros([1,out_size])+0.1,name='b')                        #偏移量
            tf.summary.histogram(layer_name+'/biases',biases)
        with tf.name_scope('Input_mut_W_Plus_bia'):                                        #視覺化
            Input_mut_W_Plus_bia=tf.matmul(inputs,Weignts)+biases           
            tf.summary.histogram(layer_name+'/Input_mut_W_Plus_bias',Input_mut_W_Plus_bia) #為了通過瀏覽器觀察每一神經層的權重
        if activation_function is None:                            
            outputs=Input_mut_W_Plus_bia                           
        else:                                                    
            outputs=activation_function(Input_mut_W_Plus_bia)                              #激勵函式
            tf.summary.histogram(layer_name+'/outputs',outputs)                            #為了通過瀏覽器觀察每一神經層的輸出值
        return outputs

#定義準確率:tensorflow定義完了都是要有sess.run來執行的
def compute_accuracy(v_xs,v_ys):
    global prediction                                     #prediction全域性化
    y_pre=sess.run(prediction,feed_dict={xs:v_xs})         #預測值
    correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    accuracy=tf.reduce_mean(tf.cast( correct_prediction,tf.float32))
    result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})          #執行上面定義的accuracy
    return result 
    
#定義給輸入定義placeholder
#None就是代表不管多少例子都可以,784可以理解為樣本中只有一個特徵
with tf.name_scope('inputs'):                                   #視覺化
    xs=tf.placeholder(tf.float32,[None,784],name='x_input')    #28*28 
    ys=tf.placeholder(tf.float32,[None,10],name='y_input')

#新增神經層tf.nn.softmax一般用來分類
prediction=add_layer(xs,784,10,1,activation_function=tf.nn.softmax)

with tf.name_scope('cross_entropy'):                                                                          #視覺化
    cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))              #代價函式,分類用softma和coss_entropy配
    tf.summary.scalar('cross_entropy',cross_entropy)                                                      #為了通過瀏覽器觀察每一神經層的誤差(代價函式)
with tf.name_scope('train_ste'):
    train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)                                 #優化函式

init=tf.global_variables_initializer()                                                               #初始化所有變數
sess=tf.Session()
merged=tf.summary.merge_all()                                                                        #將所有需要在瀏覽器中展現的引數合併在一起                                                                    
writer=tf.summary.FileWriter("logs/",sess.graph)                                                     #將需要視覺化的東西寫到logs檔案下
sess.run(init)


#訓練多次
for i in range(1000):
    batch_xs,batch_ys=mnist.train.next_batch(100)
    sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
    if i%50==0:
        result=sess.run(merged,feed_dict={xs:batch_xs,ys:batch_ys})
        #將需要統計的結果加到writer
        writer.add_summary(result,i)
        print(compute_accuracy(mnist.test.images,mnist.test.labels))  #列印準確度
        

執行結果:

可以看到學習過程中準確率逐漸上升。從最初的0.107上升到0.8764

神經網路圖:從中可以看到資料流向

誤差函式:

神經層內部引數變化:


更多演算法可以參看博主其他文章,或者github:https://github.com/Mryangkaitong/python-Machine-learning