卷积神经网络

卷积层的零填充

卷积层在提取特征映射时的动作称为Padding,由于移动步长不一定能整除整张图的像素宽度。其中有两种方式,same和valid

1.same:不越过边缘取样,取样的面积和输入图像的像素宽度一致。

2.valid:越过边缘取样,取样的面积小于输入人的图像的像素宽度。

卷积网络API介绍

tf.nn.conv2d(input, filter, strides=, padding=, name=None)

计算给定4-D input和filter张量的2维卷积

input:给定的输入张量,具有[batch,heigth,width,channel],类型为float32,64

filter:指定过滤器的大小,[filter_height, filter_width, in_channels, out_channels]

strides:strides = [1, stride, stride, 1],步长

padding:“SAME”, “VALID”,使用的填充算法的类型,

使用“SAME”。其中”VALID”表示滑动超出部分舍弃,

“SAME”表示填充,使得变化后height,width一样大

第一,采用sigmoid等函数,反向传播求误差梯度时,计算量相对大,而采用Relu激活函数,整个过程的计算量节省很多

第二,对于深层网络,sigmoid函数反向传播时,很容易就会出现梯度消失的情况(求不出权重和偏置)

激活函数:

tf.nn.relu(features, name=None)

features:卷积后加上偏置的结果

return:结果

Pooling层主要的作用是特征提取,通过去掉Feature Map中不重要的样本,进一步减少参数数量。Pooling的方法很多,最常用的是Max Pooling。

前面的卷积和池化相当于做特征工程,后面的全连接相当于做特征加权。最后的全连接层在整个卷积神经网络中起到“分类器”的作用。

import tensorflow as tf
import os
os.environ[‘TF_CPP_MIN_LOG_LEVEL’] = ‘2’
from tensorflow.examples.tutorials.mnist import input_data

#定义一个初始化权重的函数
def weight_variable(shape):
w = tf.Variable(tf.random_normal(shape = shape,mean = 0.0,stddev = 1.0))
return w

#定义一个初始化偏置的函数
def bias_variable(shape):
b = tf.Variable(tf.constant(0.0,shape=shape))
return b

def model():
“”“自定义卷积模型”""
#准备数据占位符
#1.建立数据占位符 x=[None,784] y_true [None,10]
with tf.variable_scope(“data”):
x = tf.placeholder(tf.float32,[None,784])
y_true = tf.placeholder(tf.int32,[None,10])

#1.一卷积层
with tf.variable_scope(“conv1”):
##初始化权重
w_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
#对x进行形状的改变
x_reshape = tf.reshape(x,[-1,28,28,1])

    x_rule1 = tf.nn.relu(tf.nn.conv2d(x_reshape,w_conv1,strides = [1,1,1,1],padding = "SAME")+b_conv1)
    
    x_pool1 = tf.nn.max_pool(x_rule1,ksize = [1,2,2,1],strides =[1,2,2,1],padding="SAME")

#1.二卷积层
with tf.variable_scope(“conv2”):
##初始化权重
w_conv2 = weight_variable([5,5,1,64])
b_conv2 = bias_variable([64])
#对x进行形状的改变
x_reshape = tf.reshape(x,[-1,28,28,1])

    x_rule2 = tf.nn.relu(tf.nn.conv2d(x_pool1,w_conv2,strides = [1,1,1,1],padding = "SAME")+b_conv2)
    
    x_pool2 = tf.nn.max_pool(x_rule2,ksize = [1,2,2,1],strides =[1,2,2,1],padding="SAME")
    
#全连接层
with tf.variable_scope("conv2"):
    #随机初始化权重和偏置
    w_fc = weight_variable([7*7*64,10])
    b_fc = bias_variable([10])
    
    ##修改形状
    x_fc_reshape = tf.reshape(x_pool2,[-1,7*7*64])
    
    #进行矩阵运算得出每个样本的10个结果
    y_predict = tf.matmul(x_fc_reshape,w_fc)+b_fc
return x,y_true,y_predict

def conv_fc():
#获取真实的数据
mmist = input_data.read_data_sets(r’F:\BaiduNetdiskDownload\mnist\data’,one_hot = True)
#定义函数,得出模型
x,y_true,y_predict = model()
#进行交叉熵损失计算
with tf.variable_scope(“soft_cross”):
#求平均交叉熵损失
loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))

#4.梯度下降求出损失
with tf.variable_scope("optimizer"):
    train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

 #5.计算准确率
with tf.variable_scope("accuracy"):
    equal_list = tf.equal(tf.argmax(y_true,1),tf.argmax(y_predict,1))
    accuracy = tf.reduce_mean(tf.cast(equal_list,tf.float32))

#定义一个初始化变量的op
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
     #迭代步数去训练,更新参数预测
    for i in range(2000):
        #取出真实存在的特征值和目标值
        mmist_x,mmist_y = mmist.train.next_batch(50)
        #运行train_op
        sess.run(train_op,feed_dict={x:mmist_x,y_true:mmist_y})
        print("训练第%d步,准确率为:%f"%(i,sess.run(accuracy,feed_dict={x:mmist_x,y_true:mmist_y})))
conv_fc()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值