应用TensorFlow构建卷积神经网络

应用TensorFlow构建卷积神经网络

  • 两个卷积层,两个全连接层

  • 输入 [sample * 28 * 28 * 1 ] (灰度图)

  • [ 28 * 28 1 ] --> (32个卷积核,每个大小551,sample方式卷积) --> [ 28 * 28 * 32] --> (池化 22 ,步长2)–> [14 *14 *32]

  • [ 14 * 14 32] --> (64个卷积核,每个大小55*32,sample方式卷积) --> [14 * 14 64] --> (池化 22 ,步长2)–> [7 * 7 *64]

  • [ 7 * 7 * 64] --> reshape 成列向量 --> (7 * 7 * 64)

  • [sample * (7764)] 全连接层1 weights:[7764 , 1024] --> [sample * 1024]

  • [sample * 1024] 全连接层2 weights:[1024,10] --> [sample *10]

  • 输出:10个分类

https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/convolutional_network_raw.ipynb

"""
卷积神经网络
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# 训练参数
learning_rate = 0.001
num_steps = 500
batch_size = 128
display_step = 10

# 网络参数
num_input = 784
num_classes = 10
dropout = 0.75

# tf图输入
X = tf.placeholder(tf.float32, [None, num_input])
Y = tf.placeholder(tf.float32, [None, num_classes])
keep_prob = tf.placeholder(tf.float32)

# 卷积
def conv2d(x, W, b, strides=1):
    # stride [1, x_movement, y_movement, 1]
    # 必须 strides[0] = strides[3] = 1
    # output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    # 批标准化
    # _mean, _var = tf.nn.moments(x, [0, 1, 2])
    # x = tf.nn.batch_normalization(x, _mean, _var, 0, 1, 0.0001)
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)
# 池化
def maxpool2d(x, k=2):
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
# 卷积网络模型
def conv_net(x, weights, biases, dropout):
    # 4-D: [Batch Size, Height, Width, Channel]
    # -1代表先不考虑输入的图片例子多少
    x = tf.reshape(x, shape=[-1,28,28,1])
    
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    conv1 = maxpool2d(conv1, k=2)
    
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    conv2 = maxpool2d(conv2, k=2)
    
    fc1 = 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)
    
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# 权重
weights = {
        '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, num_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(num_classes))
        }

# 构建模型
logits = conv_net(X, weights, biases, keep_prob)
prediction = tf.nn.softmax(logits)
# 损失及优化器
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# 评价模型
correct_pred = tf.equal(tf.argmax(prediction,1), tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))  
# 参数初始化
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    
    for step in range(1, num_steps+1):
        batch_x,batch_y = mnist.train.next_batch(batch_size)
        sess.run(train_op,feed_dic={X:batch_x, Y:batch_y, keep_prob:dropout})
        
        if step % display_step == 0 or step == 1:
            # 计算批损失及准确率
            loss, acc = sess.run([loss_op, accuracy], feed_dict={X:batch_x, Y:batch_y, keep_prob:1.})
            print("Step " + str(step) + ", Minibatch Loss= " + \
                  "{:.4f}".format(loss) + ", Training Accuracy= " + \
                  "{:.3f}".format(acc))
    print("Optimization Finished!")

    # 计算测试集准确度
    print("Testing Accuracy:", \
        sess.run(accuracy, feed_dict={X: mnist.test.images[:256],
                                      Y: mnist.test.labels[:256],
                                      keep_prob: 1.0}))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值