TFboy养成记 CNN

时间:2023-12-31 10:40:38

1/先解释下CNN的过程:

首先对一张图片进行卷积,可以有多个卷积核,卷积过后,对每一卷积核对应一个chanel,也就是一张新的图片,图片尺寸可能会变小也可能会不变,然后对这个chanel进行一些pooling操作。

最后pooling输出完成,这个算作一个卷积层。

最后对最后一个pooling结果进行一个简单的MLP的判别其就好了

2.代码分步:

2.1 W and bias:注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到

 #注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到
def getWeights(shape):
return tf.Variable(tf.truncated_normal(shape,stddev= 0.1))
def getBias(shape):
return tf.Variable(tf.constant(0.1))

2.2 卷积层操作:

首先说下tf.nn.conv2d这个函数:

TFboy养成记 CNN

其中官方解释:

TFboy养成记 CNN

这里主要需要了解的是strides的含义:其shape表示的是[batch, in_height, in_width, in_channels]。需要注意的是,看我们在Weights初始化时的shape,我们自己定义的shape格式是[h,w,inchanel,outchanel]   --->chanel也就是我们理解的厚度。

 def conv2d(x,W):
return tf.nn.conv2d(x,W,strides = [1,1,1,1],padding="SAME")
#ksize
def maxpooling(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides = [1,2,2,1],padding= "SAME")

关于data_format

TFboy养成记 CNN

padding也有两种方式:

TFboy养成记 CNN

其他地方其实也没有什么新操作所有代码在下面:

 # -*- coding: utf-8 -*-
"""
Spyder Editor This is a temporary script file.
"""
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
#注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到
def getWeights(shape):
return tf.Variable(tf.truncated_normal(shape,stddev= 0.1))
def getBias(shape):
return tf.Variable(tf.constant(0.1))
#构造卷积层 strides前一个跟最后后一个为1,其他表示方向,padding一般是有两种方式 ,一个是SAME还有一个是VALID
#前者卷积后不改变大小后一个卷积后一般会变小
#strides--->data_format:data_format: An optional string from: "NHWC", "NCHW". Defaults to "NHWC". Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, height, width, channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, channels, height, width].
#
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides = [1,1,1,1],padding="SAME")
#ksize
def maxpooling(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides = [1,2,2,1],padding= "SAME")
def compute_acc(v_xs,v_ys):
global predict
y_pre = sess.run(predict,feed_dict = {xs:v_xs,keep_prob:1})
tmp = tf.equal(tf.arg_max(y_pre,1),tf.arg_max(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(tmp,tf.float32))
return sess.run(accuracy,feed_dict = {xs:v_xs,ys:v_ys,keep_prob:1}) mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
xs = tf.placeholder(tf.float32,[None,28*28])
ys = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32) x_images = tf.reshape(xs,[-1,28,28,1]) W_c1 = getWeights([5,5,1,32])
b_c1 = getBias([32])
h_c1 = tf.nn.relu(conv2d(x_images,W_c1)+b_c1)
h_p1 = maxpooling(h_c1) W_c2 = getWeights([5,5,32,64])
b_c2 = getBias([64])
h_c2 = tf.nn.relu(conv2d(h_p1,W_c2)+b_c2)
h_p2 = maxpooling(h_c2) W_fc1 = getWeights([7*7*64,1024])
b_fc1 = getBias([1024])
h_flat = tf.reshape(h_p2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_flat,W_fc1)+b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) W_fc2 = getWeights([1024,10])
b_fc2 = getBias([10])
predict = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) loss = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(predict),
reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(0.001).minimize(loss) sess = tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
print (compute_acc(mnist.test.images,mnist.test.labels))

需要注意的是nn.dropout()