欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

tensorflow学习笔记——卷积神经网络的简单应用

程序员文章站 2022-07-06 16:22:38
...

本文用卷积神经网络实现MNIST数据集分类。可在这个网站下载MNIST数据集。下载后的数据如下图所示:

tensorflow学习笔记——卷积神经网络的简单应用

代码如下:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#载入数据
mnist = input_data.read_data_sets("E:/mnist",one_hot=True)
#每个批次大小
batch_size = 200
#计算一共有多少个批次
n_batch = mnist.train.num_examples//batch_size #整除

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):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#步长4个值分别表示图片步长(一个批次多张图片),向右移动步长,向下移动步长,层数移动步长,SAME表示边缘补0

def max_pool(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

#第一维:每个批次图片数,第二三维:图像宽高,第四维:图像层数
x_image = tf.reshape(x,[-1,28,28,1])
#第一层卷积
W_conv1 = weight_variable([5,5,1,32])#5×5的卷积核,图像层数为1,卷积核32个
b_conv1 = bias_variable([32])

conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
pool1 = max_pool(conv1)

#第二层卷积
W_conv2 = weight_variable([5,5,32,64])#5×5的卷积核,图像层数为32,卷积核64个
b_conv2 = bias_variable([64])

conv2 = tf.nn.relu(conv2d(pool1,W_conv2)+b_conv2)
pool2 = max_pool(conv2)

pool2_flat = tf.reshape(pool2,[-1,7*7*64])#将64张7×7的图片拉平

# 第一层全连接
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])

fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1)+b_fc1)
keep_prob = tf.placeholder(tf.float32)
fc1_drop = tf.nn.dropout(fc1,keep_prob)

#第二层全连接
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])

prediction = tf.nn.softmax(tf.matmul(fc1_drop,W_fc2)+b_fc2)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=prediction))
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#equl判断是否相等,argmax返回张量最大值的索引
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #将布尔型转换为浮点型

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})
        
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
        print("Iter " + str(epoch) + " Accuracy" + str(acc)) 

运行结果如下:

tensorflow学习笔记——卷积神经网络的简单应用

 

相关标签: tensorflow