TensorFlow - 卷积神经网络

TensorFlow - 卷积神经网络 首页 / TensorFlow入门教程 / TensorFlow - 卷积神经网络

了解机器学习概念之后,无涯教程现在可以将重点转移到深度学习概念上,深度学习是机器学习的一个分支,被认为是近几十年来研究人员迈出的关键一步。深度学习实现的示例包括图像识别和语音识别等应用。

以下是深度神经网络的两种重要类型-

  • 卷积神经网络
  • 递归神经网络

在本章中,将重点介绍CNN,即卷积神经网络。

链接:https://www.learnfk.comhttps://www.learnfk.com/tensorflow/tensorflow-convolutional-neural-networks.html

来源:LearnFk无涯教程网

卷积神经网络

卷积神经网络旨在通过多层数组处理数据,这种类型的神经网络用于图像识别或面部识别等应用中, CNN与任何其他普通神经网络之间的主要区别在于,CNN将输入作为二维数组,直接在图像上进行操作,而不是像其他神经网络关注的是特征提取。

CNN利用输入数据中存在的空间相关性,神经网络的每个并发层都连接一些输入神经元,该特定区域称为局部感受野,局部感受野集中在隐藏的神经元上,隐藏的神经元在提到的字段内处理输入数据,但未实现特定边界之外的更改。

卷积神经网络

如果观察到以上表示,则每个连接都将学习隐藏神经元的权重,并具有从一层到另一层的运动的关联连接,在这里,单个神经元会执行转换,这个过程称为"卷积"。

从输入层到隐藏要素图的连接映射定义为"共享权重",其中包含的偏差称为"共享偏差"。

CNN或卷积神经网络使用池化层,池化层是在CNN声明后立即定位的层,它将来自用户的输入作为来自卷积网络的特征图,并准备一个压缩的特征图。合并层有助于创建具有先前层神经元的层。

无涯教程网

CNN代码实现

在本部分中,无涯教程将了解CNN的TensorFlow实现。需要执行整个网络并具有适当尺寸的步骤如下所示-

步骤1   - 包括计算CNN模型所需的TensorFlow必要模块和数据集模块。

import tensorflow as tf
import numpy as np
from tensorflow.examples.Learnfk.mnist import input_data

步骤2   - 声明一个名为 run_cnn()的函数,该函数包含各种参数和带有数据占位符声明的优化变量,这些优化变量将声明训练模式。

def run_cnn():
   mnist=input_data.read_data_sets("MNIST_data/", one_hot=True)
   learning_rate=0.0001
   epochs=10
   batch_size=50

步骤3   - 在这一步中,将使用输入参数- 28 x 28= 784像素声明训练数据占位符,这是从 mnist.train提取的扁平化图像数据。

可以根据需要重塑张量,第一个值(-1)告诉函数根据传递给它的数据量动态调整该维度,中间的两个尺寸设置为图像尺寸(即28 x 28)。

x=tf.placeholder(tf.float32, [None, 784])
x_shaped=tf.reshape(x, [-1, 28, 28, 1])
y=tf.placeholder(tf.float32, [None, 10]) 

步骤4   - 现在,重要的是创建一些卷积层-

layer1=create_new_conv_layer(x_shaped, 1, 32, [5, 5], [2, 2], name='layer1')
layer2=create_new_conv_layer(layer1, 32, 64, [5, 5], [2, 2], name='layer2') 

步骤5   - 让无涯教程输出,在将步长2的两层合并为28 x 28的尺寸之后,将其放宽为14 x 14或最小7 x 7  的x ,y坐标,但具有64个输出通道。要创建完全连接的密集层,新形状需要为[-1,7 x 7 x 64],可以为此层设置一些权重和偏差值,然后使用ReLU激活。

flattened = tf.reshape(layer2, [-1, 7 * 7 * 64])

wd1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1000], stddev = 0.03), name = 'wd1')
bd1 = tf.Variable(tf.truncated_normal([1000], stddev = 0.01), name = 'bd1')

dense_layer1 = tf.matmul(flattened, wd1) + bd1
dense_layer1 = tf.nn.relu(dense_layer1)

步骤6   - 另一层具有特定softmax激活并带有所需优化器的层定义了准确性判断,从而进行了初始化运算符的设置。

wd2 = tf.Variable(tf.truncated_normal([1000, 10], stddev = 0.03), name = 'wd2')
bd2 = tf.Variable(tf.truncated_normal([10], stddev = 0.01), name = 'bd2')

dense_layer2 = tf.matmul(dense_layer1, wd2) + bd2
y_ = tf.nn.softmax(dense_layer2)

cross_entropy = tf.reduce_mean(
   tf.nn.softmax_cross_entropy_with_logits(logits = dense_layer2, labels = y))

optimiser = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

init_op = tf.global_variables_initializer()

步骤7   - 应该设置记录变量,这将汇总汇总以存储数据的准确性。

tf.summary.scalar('accuracy', accuracy)
   merged = tf.summary.merge_all()
   writer = tf.summary.FileWriter('E:\TensorFlowProject')
   
   with tf.Session() as sess:
      sess.run(init_op)
      total_batch = int(len(mnist.train.labels)/batch_size)
      
      for epoch in range(epochs):
         avg_cost = 0
      for i in range(total_batch):
         batch_x, batch_y = mnist.train.next_batch(batch_size = batch_size)
            _, c = sess.run([optimiser, cross_entropy], feed_dict = {
            x:batch_x, y: batch_y})
            avg_cost += c/total_batch
         test_acc = sess.run(accuracy, feed_dict = {x: mnist.test.images, y:
            mnist.test.labels})
            summary = sess.run(merged, feed_dict = {x: mnist.test.images, y:
            mnist.test.labels})
         writer.add_summary(summary, epoch)

   print("\nTraining complete!")
   writer.add_graph(sess.graph)
   print(sess.run(accuracy, feed_dict = {x: mnist.test.images, y:
      mnist.test.labels}))

def create_new_conv_layer(
   input_data, num_input_channels, num_filters,filter_shape, pool_shape, name):

   conv_filt_shape = [
      filter_shape[0], filter_shape[1], num_input_channels, num_filters]

   weights = tf.Variable(
      tf.truncated_normal(conv_filt_shape, stddev = 0.03), name = name+'_W')
   bias = tf.Variable(tf.truncated_normal([num_filters]), name = name+'_b')

#Out layer defines the output
   out_layer =
      tf.nn.conv2d(input_data, weights, [1, 1, 1, 1], padding = 'SAME')

   out_layer += bias
   out_layer = tf.nn.relu(out_layer)
   ksize = [1, pool_shape[0], pool_shape[1], 1]
   strides = [1, 2, 2, 1]
   out_layer = tf.nn.max_pool(
      out_layer, ksize = ksize, strides = strides, padding = 'SAME')

   return out_layer

if __name__ == "__main__":
run_cnn()

以下是上述代码生成的输出-

See @{tf.nn.softmax_cross_entropy_with_logits_v2}.

2018-09-19 17:22:58.802268: I
T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140]
Your CPU supports instructions that this TensorFlow binary was not compiled to
use: AVX2

2018-09-19 17:25:41.522845: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 1003520000 exceeds 10% of system memory.

2018-09-19 17:25:44.630941: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 501760000 exceeds 10% of system memory.

Epoch: 1 cost=0.676 test accuracy: 0.940

2018-09-19 17:26:51.987554: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 1003520000 exceeds 10% of system memory.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

说透敏捷 -〔宋宁〕

软件设计之美 -〔郑晔〕

编译原理实战课 -〔宫文学〕

Redis核心技术与实战 -〔蒋德钧〕

说透芯片 -〔邵巍〕

Kubernetes入门实战课 -〔罗剑锋〕

商业思维案例笔记 -〔曹雄峰〕

云原生基础架构实战课 -〔潘野〕

好记忆不如烂笔头。留下您的足迹吧 :)