卷积神经网络二

下面咱们用tf自带的MNIST数据集来实现一下手写体数字识别
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#加载数据并转换
mnist = input_data.read_data_sets(“MNIST_data_bak/”, one_hot=True)
sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1, 28, 28, 1])

#封装函数
def weight_variable(shape):
inital = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(inital)
def bias_variable(shape):
inital = tf.constant(0.1, shape=shape)
return tf.Variable(inital)
def conv2d(x,W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=“SAME”)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=“SAME”)

#构建卷积和池化逻辑
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
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])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#构建全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1)+ b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

w_fc2 = weight_variable([1024, 256])
b_fc2 = bias_variable([256])
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, w_fc2)+b_fc2)
h_fc1_drop = tf.nn.dropout(h_fc2, keep_prob)

#构建softmax层
w_fc3 = weight_variable([256, 10])
b_fc3 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc3)+ b_fc3)

#定义损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

#定义acc
correct_indection = tf.equal(tf.argmax(y_, 1), tf.argmax(y_conv,1))
accuracy = tf.reduce_mean(tf.cast(correct_indection, tf.float32))

#训练
tf.global_variables_initializer().run()
for i in range(1000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={
x: batch[0], y_: batch[1], keep_prob:0.5
})
print(“step %d, training accuracy %g” % (i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
x_test, y_test = mnist.test.next_batch(500)
print(“test accuracy %g” % accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}))
总体来给大家概括一下本代码的大概逻辑,加载数据集并转换数据———>
———>封装w、bias、卷积核、池化核的———>创建交叉熵损失和acc———>
运行代码并输出准确率(本来对代码有一个非常详细的逻辑阐述,不知道CSDN为什么没有给我保存上,气得我现在还在医院躺着呢)下面咱们来看看MNIST的数据集在tensorflow中真正的样子是什么样子的,不多说直接上图
卷积神经网络二
卷积神经网络二
卷积神经网络二
卷积神经网络二
卷积神经网络二
后面的5到9没有传上来,如果感兴趣的朋友可以上网自己搜一下,大家看看这些咱们人类写的数字,如果将他们都混合在一起那么你能识别对几个呢?反正我想想都觉得愁人,尤其是2那里,你都想象不到有人竟然会这么写2,没上过学吗?也难为神经网络了,咱们上一节的卷积神经网络用的是2个卷积层两个DNN层,识别的准确率是百分之99.2,挺难以想象的,如果是你的话你觉得准确率会有多少呢?
本次的卷积神经网络到此告一段落,同时产生了2个问题,
第一个问题是如果给到我的数据集是彩色图片那么同样的网络架构准确率会是多少?
第二个就是如何看到本次的模型预测的真实y_conv结果。