TensorFlow的目标图像识别

版权声明:本博客都是作者10多年工作总结 https://blog.csdn.net/Peter_Changyb/article/details/84344449

 卷积神经网络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

猜你喜欢

转载自blog.csdn.net/Peter_Changyb/article/details/84344449