关于tensorflow:TensorFlowCNN实战AI图像处理入行计算机视觉无密

4次阅读

共计 2444 个字符,预计需要花费 7 分钟才能阅读完成。

TensorFlow+CNN实战 AI 图像处理,入行计算机视觉

download:https://www.sisuoit.com/itkecheng/shizhankecheng

TensorFlow+CNN实战 AI 图像处理随着人工智能技术的一直倒退,AI 图像处理曾经成为一个热门畛域。在泛滥的 AI 图像处理技术中,卷积神经网络 (Convolutional Neural Network,CNN) 曾经成为了最为风行和广泛应用的一种技术。而 TensorFlow 作为目前最为风行的深度学习框架之一,也被广泛应用于 CNN 的实现。本文将介绍如何应用 TensorFlow 实现 CNN 进行图像处理,并以手写数字辨认为例进行实战解说。数据集筹备首先咱们须要筹备一个适合的数据集。在这里咱们应用 MNIST 手写数字数据集,该数据集蕴含 60000 个训练样本和 10000 个测试样本。能够应用 TensorFlow 自带的 mnist 库进行导入。网络架构设计咱们应用的是 LeNet- 5 网络架构,它是一个比拟根底并且易于了解的 CNN 网络结构。它由两个卷积层、两个池化层和三个全连贯层组成。具体构造如下:

模型构建咱们应用 TensorFlow 进行模型的搭建。首先,咱们须要定义输出和输入:

输出

x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y_ = tf.placeholder(tf.float32, [None, 10])
接着,咱们依照 LeNet- 5 网络结构,顺次增加卷积层、池化层和全连贯层:# 第一卷积层
W_conv1 = weight_variable([5, 5, 1, 6])
b_conv1 = bias_variable([6])
h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

# 第二卷积层
W_conv2 = weight_variable([5, 5, 6, 16])
b_conv2 = bias_variable([16])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# 全连贯层 1
W_fc1 = weight_variable([7 * 7 * 16, 120])
b_fc1 = bias_variable([120])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*16])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# 全连贯层 2
W_fc2 = weight_variable([120, 84])
b_fc2 = bias_variable([84])
h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc2)

# 输入层
W_fc3 = weight_variable([84, 10])
b_fc3 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc2, W_fc3) + b_fc3)
其中,weight_variable 和 bias_variable 是辅助函数,用于生成权重和偏移量的变量:# 权重变量
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

# 偏移量变量
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
conv2d 和 max_pool_2x2 别离是卷积和池化的操作函数:# 卷积操作
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

# 池化操作
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')

训练模型接下来咱们须要进行模型的训练和测试。首先须要定义损失函数和优化器:# 损失函数

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))

优化器

train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
而后咱们应用训练集对模型进行训练:with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(20000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print("step %d, training accuracy %g"%(i, train_accuracy))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

后果剖析经过训练,咱们失去了一个手写数字辨认模型。在测试集上的准确率能够达到 99% 以上。本文介绍了如何应用 TensorFlow 实现 CNN 进行图像处理,并以手写数字辨认为例进行了实战演示。当然,CNN 还有很多其余利用,如图像分类、指标检测等。心愿这篇文章可能给你带来一些启发,也欢送大家在实践中摸索更多的利用场景。

正文完
 0