1. 程式人生 > >TensorFlow的目標影象識別

TensorFlow的目標影象識別

 卷積神經網路CNN主要用來識別位移、縮放及其他形式扭曲不變性的二維圖形。由於CNN的特徵檢測層通過訓練資料進行學習,所以在使用CNN時,避免了顯式的特徵抽取,而隱式地從訓練資料中進行學習;再者由於同一特徵對映面上的神經元權值相同,所以網路可以並行學習,這也是卷積網路相對於神經元彼此相連網路的一大優勢。卷積神經網路以其區域性權值共享的特殊結構在語音識別和影象處理方面有著獨特的優越性,其佈局更接近於實際的生物神經網路,權值共享降低了網路的複雜性,特別是多維輸入向量的影象可以直接輸入網路這一特點避免了特徵提取和分類過程中資料重建的複雜度。如下是手寫識別的案例:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import  input_data

#載入資料集
mnist = input_data.read_data_sets("MNIST_data", one_hot = True)

#批次大小
batch_size = 100
#計算一共有多少個批次
n_batch = mnist.train._num_examples // batch_size

#佔位符
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
lr = tf.Variable(0.001, dtype = tf.float32)

#建立神經網路層
def add_layer(inputs, in_size, out_size, activation_function=None):

    W = tf.Variable(tf.truncated_normal([in_size, out_size],stddev = 0.1))
    b = tf.Variable(tf.zeros([1, out_size]))
    Wx_plus_b = tf.matmul(inputs, W) + b

    if(activation_function == None):
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return tf.nn.dropout(outputs, keep_prob)



#建立神經網路
l1 = add_layer(xs, 784,500,tf.nn.tanh)
l2 = add_layer(l1, 500, 300, tf.nn.tanh)
prediction = add_layer(l2, 300, 10, tf.nn.softmax)

#損失函式為 交叉熵
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = ys, logits = prediction))
#使用梯度下降法
# train_op = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
train_op = tf.train.AdamOptimizer(lr).minimize(loss)
#初始化變數
init = tf.global_variables_initializer()
#結果存放在一個布林型變數
correct_prediction = tf.equal(tf.argmax(ys, 1), tf.argmax(prediction, 1))
#求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


with tf.Session() as sess:
    sess.run(init)
    for epoch in range(51):  
        sess.run(tf.assign(lr, 0.001*(0.95**epoch)))
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_op, feed_dict = {xs: batch_xs, ys:batch_ys,keep_prob:1.0})
        test_acc = sess.run(accuracy, feed_dict={xs: mnist.test.images, ys:mnist.test.labels,keep_prob:1.0})
        learing_rate = sess.run(lr)
        print "Iter", epoch, "test_acc: ",test_acc,"learning_rate", learing_rate