TensorFlow 实现卷积神经网络

 
import tensorflow as tf
import numpy as np
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 我们希望输入任意数量的mnist图像及标签,因此用placeholder传入
x_data = tf.placeholder("float",[None, 784])
y_data = tf.placeholder("float",[None, 10])

# 定义权重函数
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)
# tf.truncated_normal(shape, mean, stddev) :
# shape表示生成张量的维度,mean是均值,stddev是标准差
# 这个函数产生正态分布,均值和标准差自己设定

#定义偏置项函数
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

# 定义卷积函数
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides =[1, 1, 1, 1], padding='SAME')
# tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
# 第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]
# 这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数]
# 第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]
# 这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数]
# 第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4
# 第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,为‘SAME’时,表示卷积核可以停留在图像边缘
# 第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
# 结果返回一个Tensor,这个输出,就是我们常说的feature map,shape仍然是[batch, height, width, channels]这种形式

# 定义池化函数
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides =[1, 2, 2, 1], padding='SAME')

# 第一层卷积,我们需要处理我们的x_data,把x_data的形状变成[-1,28,28,1]
# -1代表先不考虑输入的图片例子多少这个维度,后面的1是channel的数量
x_image = tf.reshape(x_data,[-1, 28, 28, 1])

#第一层卷积
#滤波器
W_conv1 = weight_variable([5, 5, 1, 32])  #5*5的单通道 32个滤波器,提取32个特征
b_conv1 = bias_variable([32])  #每个滤波器对应一个偏置项
#开始卷积 + relu
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
#开始池化
h_pool1 = max_pool_2x2(h_conv1)

# 第二层卷积
#滤波器
W_conv2 = weight_variable([5, 5, 32, 64])  #5*5的单通道 64个滤波器,提取64个特征
b_conv2 = bias_variable([64])  #每个滤波器对应一个偏置项
#开始卷积 + relu
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
#开始池化
h_pool2 =max_pool_2x2(h_conv2)

#【reshape】转换维度
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])

#全连接层1
#权重
W_fc1 = weight_variable([7*7*64, 1024])  #类似于定义神经网络权重,相当于一个有1024神经元的hidden layer,输入7*7*64,
b_fc1 = bias_variable([1024])

h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

#如果我们考虑过拟合问题,可以加一个dropout的处理
keep_drop = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_drop)

# 全连接层2
#权重
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

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

#训练和评估阶段
#计算交叉熵
cross_entropy = -tf.reduce_sum(y_data*tf.log(y))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_data, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict = {x_data:batch[0], y_data: batch[1], keep_drop: 1.0})
        print("step %d, training accuracy %g" %(i, train_accuracy))
      train_step.run(feed_dict = {x_data: batch[0], y_data: batch[1], keep_drop: 0.5})

    print("test accuracy %g"%accuracy.eval(feed_dict={x_data: mnist.test.images, y_data: mnist.test.labels, keep_drop:1.0}))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值