首页 > 其他 > 详细

cnn

时间:2019-02-28 18:28:55      阅读:249      评论:0      收藏:0      [点我收藏+]

不用找了,这里的注释最详细。

# encoding:utf-8
__author__ = HP
import tensorflow as tf
import input_data

# 自动下载安装数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x=tf.placeholder(float,[None,784])        # None 为样本个数   784=28*28

### 初始化权重和偏置
# 一般来说初始化权重时要加入少量扰动,打破对称性,防止0梯度的问题。
# Relu要用稍大于0的值,避免节点输出恒为0
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)

### 卷积和池化
def conv2d(x, W):
    # 卷积
    # stride [1, x_movement, y_movement, 1]    步长,长度必须是4,还不知道为什么
    # Must have strides[0] = strides[3] = 1
    # padding 取same时卷积后的长宽和原图片一样,此时需要边界填充
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=SAME)

def max_pool_2x2(x):
    # 池化
    # ksize 是池化视野的大小 2x2
    # strides padding 同卷积   取same时池化完在外面补0
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=SAME)

## 第一层卷积
# 卷积
# 权重就是卷积核,前两个维度是patch的大小,接着是输入的通道数目(或者说卷积核的通道数),最后是输出的通道数目(或者说卷积核的个数)
W_conv1 = weight_variable([5, 5, 1, 32])    # 卷积在每个5X5的patch中算出32个特征,权重是一个[5,5,1,32]的张量     卷积核个数一般取2的n次方,n不限
# 输出对应一个同样大小的偏置向量
b_conv1 = bias_variable([32])       # 一个卷积核一个w,一个w一个b,故几个卷积核几个b

# 池化
# 把x变成一个4d向量,第1维是样本个数,-1代表暂时不确定,2 3维代表图片的宽高,最后一维是颜色通道(本例是黑白图片)
x_image = tf.reshape(x, [-1, 28, 28, 1])

# 激活函数
# 把x_image和权值向量进行卷积相乘,加上偏置,使用relu函数激活,最后max pooling
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

# 这层卷积完图片为  28*28*32    长宽不变,深度加深
# 这层池化完图片为 14*14*32     池化视野2x2,步长2,2

## 第二层卷积
# 为了构建更深的网络,我们把几个类似的层堆叠起来
# 第二层中,每个5x5的patch会得到64个特征
W_conv2 = weight_variable([5, 5, 32, 64])       # 32 是第一层卷完的深度(通道数) 64继续加深
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# 这层卷积完图片为 14*14*64
# 这层池化完图片为 7*7*64

## 全连接层
# 这时图片的维度降到7x7, 加入一个有1024个神经元的全连接层,用于处理整个图片
W_fc1 = weight_variable([7 * 7 * 64, 1024])     # 全连接层此时的权重是2维的,即上次神经元个数,下层神经元个数
b_fc1 = bias_variable([1024])

# 我们把池化层输出的张量reshape成一些向量,乘以权重,加上偏置,激活
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])            # 将图片展开(flat)变成1维向量, -1 仍代表样本个数
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

## dropout
# 为了减少过拟合,在输出层之前加上dropout
# 用一个placeholder来代表一个神经元在dropout中被保留的概率。
# 这样可以在训练过程中启用dropout,在测试过程中关闭dropout。
# tf.nn.dropout操作会自动处理神经元输出值的scale。所以用dropout的时候不用考虑scale
keep_prob = tf.placeholder(float)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

## 输出层
# 最后添加softmax层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# 损失函数
y_=tf.placeholder(float,[None,10])     # 10维
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))

# 优化器
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 评估
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 训练
sess = tf.Session()
sess.run(tf.initialize_all_variables())

for i in range(20000):
    batch = mnist.train.next_batch(50)
    if i%100 == 0:
        train_accuracy = sess.run(accuracy, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
        print "step %d, training accuracy %g"%(i, train_accuracy)
    sess.run(train_step, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print "test accuracy %g"%sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})

 

cnn

原文:https://www.cnblogs.com/yanshw/p/10452086.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!