当前位置:   article > 正文

Tensorflow CNN(两层卷积+全连接+softmax)_全连接层加卷积层代码

全连接层加卷积层代码
由于卷积用于分类的方法非常固定,因此直接贴上源码以及链接,有需要的直接稍加修改就可以了。 
传送门  
简单写一下心得体会 

卷积层+pooling层

  1. #定义变量,初始化为截断正态分布的变量
  2. def weight_variable(shape):
  3. initial = tf.truncated_normal(shape, stddev=0.1)
  4. return tf.Variable(initial)
  5. #定义变量,初始化为常量
  6. def bias_variable(shape):
  7. initial = tf.constant(0.1, shape=shape)
  8. return tf.Variable(initial)
  9. # W为核函数,strides为步长,strides=[1, 1, 1, 1],中间两个为x方向的步长和y方向的步长
  10. # padding='SAME'表示输出的大小和输入的大小一样
  11. def conv2d(x, W):
  12. # stride [1, x_movement, y_movement, 1]
  13. # Must have strides[0] = strides[3] = 1
  14. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  15. #2x2的pooling,虽然这里padding也是same,但是下采样了。
  16. def max_pool_2x2(x):
  17. # stride [1, x_movement, y_movement, 1]
  18. return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
  19. #定义卷积核的值,设置初始值。其中[5,5, 1,32]为卷积核的shape
  20. W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
  21. b_conv1 = bias_variable([32])
  22. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
  23. h_pool1 = max_pool_2x2(h_conv1)

原始代码如下

  1. # View more python tutorial on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. """
  5. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
  6. """
  7. from __future__ import print_function
  8. import tensorflow as tf
  9. from tensorflow.examples.tutorials.mnist import input_data
  10. # number 1 to 10 data
  11. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
  12. def compute_accuracy(v_xs, v_ys):
  13. global prediction
  14. y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
  15. correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
  16. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  17. result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
  18. return result
  19. def weight_variable(shape):
  20. initial = tf.truncated_normal(shape, stddev=0.1)
  21. return tf.Variable(initial)
  22. def bias_variable(shape):
  23. initial = tf.constant(0.1, shape=shape)
  24. return tf.Variable(initial)
  25. def conv2d(x, W):
  26. # stride [1, x_movement, y_movement, 1]
  27. # Must have strides[0] = strides[3] = 1
  28. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  29. def max_pool_2x2(x):
  30. # stride [1, x_movement, y_movement, 1]
  31. return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
  32. # define placeholder for inputs to network
  33. xs = tf.placeholder(tf.float32, [None, 784])/255. # 28x28
  34. ys = tf.placeholder(tf.float32, [None, 10])
  35. keep_prob = tf.placeholder(tf.float32)
  1. # print(x_image.shape) # [n_samples, 28,28,1]
  2. ## conv1 layer ##
  3. W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
  4. b_conv1 = bias_variable([32])
  5. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
  6. h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32
  7. ## conv2 layer ##
  8. W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64
  9. b_conv2 = bias_variable([64])
  10. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
  11. h_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64
  12. ## fc1 layer ##
  13. W_fc1 = weight_variable([7*7*64, 1024])
  14. b_fc1 = bias_variable([1024])
  15. # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]
  16. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
  17. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  18. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  19. ## fc2 layer ##
  20. W_fc2 = weight_variable([1024, 10])
  21. b_fc2 = bias_variable([10])
  22. prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  23. # the error between prediction and real data
  24. cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
  25. reduction_indices=[1])) # loss
  26. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  27. sess = tf.Session()
  28. # important step
  29. # tf.initialize_all_variables() no long valid from
  30. # 2017-03-02 if using tensorflow >= 0.12
  31. if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
  32. init = tf.initialize_all_variables()
  33. else:
  34. init = tf.global_variables_initializer()
  35. sess.run(init)
  36. for i in range(1000):
  37. batch_xs, batch_ys = mnist.train.next_batch(100)
  38. sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
  39. if i % 50 == 0:
  40. print(compute_accuracy(
  41. mnist.test.images, mnist.test.labels))
从红色部分可推断:神经网络输入层的个数是由输入的图片的像素个数,对组成的指定的矩阵(如上面xs = tf.placeholder(tf.float32, [None, 784])/255.   # 28x28所示),对该矩阵进行指定像素大小的图片分割(28*28)得到矩阵,x_image = tf.reshape(xs, [-1, 28, 28, 1]),该矩阵与W_conv1连接的反推,可与确定输入层神经元个数相关,需要进一步实验解决h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
 
 

                
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/194304
推荐阅读
相关标签
  

闽ICP备14008679号