优达学城深度学习之六——TensorFlow实现卷积神经网络

简介: 优达学城深度学习之六——TensorFlow实现卷积神经网络

TensorFlow卷积层


TensorFlow提供了tf.nn.conv2d() 和tf.nn.bias_add() 函数来创建你自己的卷积层。

# Output depthk_output=64# Image Propertiesimage_width=10image_height=10color_channels=3# Convolution filterfilter_size_width=5filter_size_height=5# Input/Imageinput=tf.placeholder(
tf.float32,
shape=[None, image_height, image_width, color_channels])
# Weight and biasweight=tf.Variable(tf.truncated_normal(
    [filter_size_height, filter_size_width, color_channels, k_output]))
bias=tf.Variable(tf.zeros(k_output))
# Apply Convolutionconv_layer=tf.nn.conv2d(input, weight, strides=[1, 2, 2, 1], padding='SAME')
# Add biasconv_layer=tf.nn.bias_add(conv_layer, bias)
# Apply activation functionconv_layer=tf.nn.relu(conv_layer)

TensorFlow最大池化提供函数:tf.nn.max_pool()


conv_layer=tf.nn.conv2d(input, weight, strides=[1, 2, 2, 1], padding='SAME')
conv_layer=tf.nn.bias_add(conv_layer, bias)
conv_layer=tf.nn.relu(conv_layer)
# Apply Max Poolingconv_layer=tf.nn.max_pool(
conv_layer,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME')

    tf.nn.max_pool() 函数实现最大池化时, ksize参数是滤波器大小,strides参数是步长。2x2 的滤波器配合 2x2 的步长是常用设定。


       ksize 和 strides 参数也被构建为四个元素的列表,每个元素对应 input tensor 的一个维度 ([batch, height, width, channels]),对 ksize 和 strides 来说,batch 和 channel 通常都设置成 1。


注意:池化层的输出深度与输入的深度相同。另外池化操作是分别应用到每一个深度切片层。

池化对应的代码:


input=tf.placeholder(tf.float32, (None, 4, 4, 5))
filter_shape= [1, 2, 2, 1]
strides= [1, 2, 2, 1]
padding='VALID'pool=tf.nn.max_pool(input, filter_shape, strides, padding)

 pool 的输出维度是 [1, 2, 2, 5],即使把 padding 改成 'SAME' 也是一样。

TensorFlow中的卷积神经网络


       这里我们导入 MNIST 数据集,用一个方便的函数完成对数据集的 batch,scale 和 One-Hot编码。

fromtensorflow.examples.tutorials.mnistimportinput_datamnist=input_data.read_data_sets(".", one_hot=True, reshape=False)
importtensorflowastf# Parameters# 参数learning_rate=0.00001epochs=10batch_size=128# Number of samples to calculate validation and accuracy# Decrease this if you're running out of memory to calculate accuracy# 用来验证和计算准确率的样本数# 如果内存不够,可以调小这个数字test_valid_size=256# Network Parameters# 神经网络参数n_classes=10#MNISTtotalclasses (0-9digits)
dropout=0.75#Dropout, probabilitytokeepunitsWeightsandBiases# Store layers weight & biasweights= {
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
'out': tf.Variable(tf.random_normal([1024, n_classes]))}
biases= {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bd1': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))}
defconv2d(x,w,b,strides=1):
x=tf.nn.conv2d(tf.Variable(x,w,strides=[1, strides, strides, 1], padding='SAME')
x=tf.nn.add_add(x,b)
returntf.nn.relu(x)

 在 TensorFlow 中,strides 是一个4个元素的序列;第一个位置表示 stride 的 batch 参数,最后一个位置表示 stride 的特征(feature)参数。最好的移除 batch 和特征(feature)的方法是你直接在数据集中把他们忽略,而不是使用 stride。要使用所有的 batch 和特征(feature),你可以把第一个和最后一个元素设成1。


     中间两个元素指纵向(height)和横向(width)的 stride,之前也提到过 stride 通常是正方形,height = width。当别人说 stride 是 3 的时候,他们意思是 tf.nn.conv2d(x, W, strides=[1, 3, 3, 1])。


为了更简洁,这里的代码用了tf.nn.bias_add() 来添加偏置。tf.add() 这里不能使用,因为 tensors 的维度不同。

模型建立


defconv_net(x, weights, biases, dropout):
# Layer 1 - 28*28*1 to 14*14*32conv1=conv2d(x, weights['wc1'], biases['bc1'])
conv1=maxpool2d(conv1, k=2)
# Layer 2 - 14*14*32 to 7*7*64conv2=conv2d(conv1, weights['wc2'], biases['bc2'])
conv2=maxpool2d(conv2, k=2)
# Fully connected layer - 7*7*64 to 1024fc1=tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1=tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1=tf.nn.relu(fc1)
fc1=tf.nn.dropout(fc1, dropout)
# Output Layer - class prediction - 1024 to 10out=tf.add(tf.matmul(fc1, weights['out']), biases['out'])
returnout

session运行


# tf Graph inputx=tf.placeholder(tf.float32, [None, 28, 28, 1])
y=tf.placeholder(tf.float32, [None, n_classes])
keep_prob=tf.placeholder(tf.float32)
# Modellogits=conv_net(x, weights, biases, keep_prob)
# Define loss and optimizercost=tf.reduce_mean(\tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\    .minimize(cost)
# Accuracycorrect_pred=tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy=tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initializing the variablesinit=tf. global_variables_initializer()
# Launch the graphwithtf.Session() assess:
sess.run(init)
forepochinrange(epochs):
forbatchinrange(mnist.train.num_examples//batch_size):batch_x, batch_y=mnist.train.next_batch(batch_size)
sess.run(optimizer, feed_dict={
x: batch_x,
y: batch_y,
keep_prob: dropout})
# Calculate batch loss and accuracyloss=sess.run(cost, feed_dict={
x: batch_x,
y: batch_y,
keep_prob: 1.})
valid_acc=sess.run(accuracy, feed_dict={
x: mnist.validation.images[:test_valid_size],
y: mnist.validation.labels[:test_valid_size],
keep_prob: 1.})
print('Epoch {:>2}, Batch {:>3} -''Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(
epoch+1,
batch+1,
loss,
valid_acc))
# Calculate Test Accuracytest_acc=sess.run(accuracy, feed_dict={
x: mnist.test.images[:test_valid_size],
y: mnist.test.labels[:test_valid_size],
keep_prob: 1.})
print('Testing Accuracy: {}'.format(test_acc))

使用tensor做卷积


     让我们用所学知识在 TensorFlow 里构建真的 CNNs。在下面的练习中,你需要设定卷积核滤波器(filters)的维度,weight,bias。这在很大程度上来说是 TensorFlow CNNs 最难的部分。一旦你知道如何设置这些属性的大小,应用 CNNs 会很方便。


这些也是需要你回顾的:


  • TensorFlow 变量。
  • Truncated 正态分布 - 在 TensorFlow 中你需要在一个正态分布的区间中初始化你的权值。
  • 根据输入大小、滤波器大小,来决定输出维度(如下所示)。你用这个来决定滤波器应该是什么样:
new_height= (input_height-filter_height+2*P)/S+1new_width= (input_width-filter_width+2*P)/S+1"""Setupthestrides, paddingandfilterweight/biassuchthattheoutputshapeis (1, 2, 2, 3).
"""importtensorflowastfimportnumpyasnp# `tf.nn.conv2d` requires the input be 4D (batch_size, height, width, depth)# (1, 4, 4, 1)x=np.array([
    [0, 1, 0.5, 10],
    [2, 2.5, 1, -8],
    [4, 0, 5, 6],
    [15, 1, 2, 3]], dtype=np.float32).reshape((1, 4, 4, 1))
X=tf.constant(x)
defconv2d(input):
# Filter (weights and bias)# The shape of the filter weight is (height, width, input_depth, output_depth)# The shape of the filter bias is (output_depth,)# TODO: Define the filter weights `F_W` and filter bias `F_b`.# NOTE: Remember to wrap them in `tf.Variable`, they are trainable parameters after all.F_W=tf.Variable(tf.truncated_normal((2,2,1,3)))
F_b=tf.Variable(tf.zeros(3))
# TODO: Set the stride for each dimension (batch_size, height, width, depth)strides= [1, 2, 2, 1]
# TODO: set the padding, either 'VALID' or 'SAME'.padding='VALID'# https://www.tensorflow.org/versions/r0.11/api_docs/python/nn.html#conv2d# `tf.nn.conv2d` does not include the bias computation so we have to add it ourselves after.returntf.nn.conv2d(input, F_W, strides, padding) +F_bout=conv2d(X)

在TensorFlow使用池化层


"""Setthevaluesto`strides`and`ksize`suchthattheoutputshapeafterpoolingis (1, 2, 2, 1).
"""importtensorflowastfimportnumpyasnp# `tf.nn.max_pool` requires the input be 4D (batch_size, height, width, depth)# (1, 4, 4, 1)x=np.array([
    [0, 1, 0.5, 10],
    [2, 2.5, 1, -8],
    [4, 0, 5, 6],
    [15, 1, 2, 3]], dtype=np.float32).reshape((1, 4, 4, 1))
X=tf.constant(x)
defmaxpool(input):
# TODO: Set the ksize (filter size) for each dimension (batch_size, height, width, depth)ksize= [1, 2, 2, 1]
# TODO: Set the stride for each dimension (batch_size, height, width, depth)strides= [1, 2, 2, 1]
# TODO: set the padding, either 'VALID' or 'SAME'.padding='SAME'# https://www.tensorflow.org/versions/r0.11/api_docs/python/nn.html#max_poolreturntf.nn.max_pool(input, ksize, strides, padding)
out=maxpool(X)

自编码器


     自编码器是一种执行数据压缩的网络架构。其中压缩和解压功能是从数据本身学习来,而非人工设计的。一般思路如下:

4551ce978a0869a3188671d797efd06c.jpg

编码器一般用在图像降噪、JPG等文件中。

目录
打赏
0
0
0
0
6
分享
相关文章
RT-DETR改进策略【模型轻量化】| 替换骨干网络为MoblieNetV1,用于移动视觉应用的高效卷积神经网络
RT-DETR改进策略【模型轻量化】| 替换骨干网络为MoblieNetV1,用于移动视觉应用的高效卷积神经网络
49 3
RT-DETR改进策略【模型轻量化】| 替换骨干网络为MoblieNetV1,用于移动视觉应用的高效卷积神经网络
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
害虫识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了12种常见的害虫种类数据集【"蚂蚁(ants)", "蜜蜂(bees)", "甲虫(beetle)", "毛虫(catterpillar)", "蚯蚓(earthworms)", "蜚蠊(earwig)", "蚱蜢(grasshopper)", "飞蛾(moth)", "鼻涕虫(slug)", "蜗牛(snail)", "黄蜂(wasp)", "象鼻虫(weevil)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Djan
76 1
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
蘑菇识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了9种常见的蘑菇种类数据集【"香菇(Agaricus)", "毒鹅膏菌(Amanita)", "牛肝菌(Boletus)", "网状菌(Cortinarius)", "毒镰孢(Entoloma)", "湿孢菌(Hygrocybe)", "乳菇(Lactarius)", "红菇(Russula)", "松茸(Suillus)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,
121 11
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
基于GA遗传优化TCN-LSTM时间卷积神经网络时间序列预测算法matlab仿真
本项目基于MATLAB 2022a实现了一种结合遗传算法(GA)优化的时间卷积神经网络(TCN)时间序列预测算法。通过GA全局搜索能力优化TCN超参数(如卷积核大小、层数等),显著提升模型性能,优于传统GA遗传优化TCN方法。项目提供完整代码(含详细中文注释)及操作视频,运行后无水印效果预览。 核心内容包括:1) 时间序列预测理论概述;2) TCN结构(因果卷积层与残差连接);3) GA优化流程(染色体编码、适应度评估等)。最终模型在金融、气象等领域具备广泛应用价值,可实现更精准可靠的预测结果。
RT-DETR改进策略【Neck】| GSConv+Slim Neck:混合深度可分离卷积和标准卷积的轻量化网络设计
RT-DETR改进策略【Neck】| GSConv+Slim Neck:混合深度可分离卷积和标准卷积的轻量化网络设计
76 11
RT-DETR改进策略【模型轻量化】| PP-LCNet:轻量级的CPU卷积神经网络
RT-DETR改进策略【模型轻量化】| PP-LCNet:轻量级的CPU卷积神经网络
61 0
RT-DETR改进策略【模型轻量化】| PP-LCNet:轻量级的CPU卷积神经网络
猫狗宠物识别系统Python+TensorFlow+人工智能+深度学习+卷积网络算法
宠物识别系统使用Python和TensorFlow搭建卷积神经网络,基于37种常见猫狗数据集训练高精度模型,并保存为h5格式。通过Django框架搭建Web平台,用户上传宠物图片即可识别其名称,提供便捷的宠物识别服务。
471 55
TensorFlow,一款由谷歌开发的开源深度学习框架,详细讲解了使用 TensorFlow 构建深度学习模型的步骤
本文介绍了 TensorFlow,一款由谷歌开发的开源深度学习框架,详细讲解了使用 TensorFlow 构建深度学习模型的步骤,包括数据准备、模型定义、损失函数与优化器选择、模型训练与评估、模型保存与部署,并展示了构建全连接神经网络的具体示例。此外,还探讨了 TensorFlow 的高级特性,如自动微分、模型可视化和分布式训练,以及其在未来的发展前景。
511 5
基于TensorFlow的深度学习模型训练与优化实战
基于TensorFlow的深度学习模型训练与优化实战
208 3
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
垃圾识别分类系统。本系统采用Python作为主要编程语言,通过收集了5种常见的垃圾数据集('塑料', '玻璃', '纸张', '纸板', '金属'),然后基于TensorFlow搭建卷积神经网络算法模型,通过对图像数据集进行多轮迭代训练,最后得到一个识别精度较高的模型文件。然后使用Django搭建Web网页端可视化操作界面,实现用户在网页端上传一张垃圾图片识别其名称。
221 0
基于Python深度学习的【垃圾识别系统】实现~TensorFlow+人工智能+算法网络
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等