当前位置:   article > 正文

卷积神经网络python代码_python卷积神经网络代码

python卷积神经网络代码

卷积神经网络python代码
仅供学习参考使用 

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. class DataSet(object):
  4. def __init__(self, images, labels, num_examples):
  5. self._images = images
  6. self._labels = labels
  7. self._epochs_completed = 0 # 完成遍历轮数
  8. self._index_in_epochs = 0 # 调用next_batch()函数后记住上一次位置
  9. self._num_examples = num_examples # 训练样本数
  10. def next_batch(self, batch_size, fake_data=False, shuffle=True):
  11. start = self._index_in_epochs
  12. if self._epochs_completed == 0 and start == 0 and shuffle:
  13. index0 = np.arange(self._num_examples)
  14. np.random.shuffle(index0)
  15. self._images = np.array(self._images)[index0]
  16. self._labels = np.array(self._labels)[index0]
  17. if start + batch_size > self._num_examples:
  18. self._epochs_completed += 1
  19. rest_num_examples = self._num_examples - start
  20. images_rest_part = self._images[start:self._num_examples]
  21. labels_rest_part = self._labels[start:self._num_examples]
  22. if shuffle:
  23. index = np.arange(self._num_examples)
  24. np.random.shuffle(index)
  25. self._images = self._images[index]
  26. self._labels = self._labels[index]
  27. start = 0
  28. self._index_in_epochs = batch_size - rest_num_examples
  29. end = self._index_in_epochs
  30. images_new_part = self._images[start:end]
  31. labels_new_part = self._labels[start:end]
  32. return np.concatenate((images_rest_part, images_new_part), axis=0), np.concatenate(
  33. (labels_rest_part, labels_new_part), axis=0)
  34. else:
  35. self._index_in_epochs += batch_size
  36. end = self._index_in_epochs
  37. return self._images[start:end], self._labels[start:end]
  38. import tensorflow as tf
  39. from tensorflow.examples.tutorials.mnist import input_data
  40. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
  41. import time
  42. start_time = time.time()
  43. """
  44. 权重初始化
  45. """
  46. def weight_variable(shape):
  47. initial = tf.truncated_normal(shape, stddev = 0.1)
  48. return tf.Variable(initial)
  49. def bias_variable(shape):
  50. initial = tf.constant(0.1, shape = shape)
  51. return tf.Variable(initial)
  52. def conv2d(x, W):
  53. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = 'SAME')
  54. def max_pool_2x2(x):
  55. return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],
  56. strides = [1, 2, 2, 1], padding = 'SAME')
  57. """
  58. 第一层 卷积层
  59. x_image(batch, 28, 28, 1) -> h_pool1(batch, 14, 14, 32)
  60. """
  61. x = tf.placeholder(tf.float32,[None, 784])
  62. x_image = tf.reshape(x, [-1, 28, 28, 1]) #最后一维代表通道数目,如果是rgb则为3
  63. W_conv1 = weight_variable([5, 5, 1, 32])
  64. b_conv1 = bias_variable([32])
  65. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  66. h_pool1 = max_pool_2x2(h_conv1)
  67. """
  68. 第二层 卷积层
  69. h_pool1(batch, 14, 14, 32) -> h_pool2(batch, 7, 7, 64)
  70. """
  71. W_conv2 = weight_variable([5, 5, 32, 64])
  72. b_conv2 = bias_variable([64])
  73. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  74. h_pool2 = max_pool_2x2(h_conv2)
  75. """
  76. 第三层 全连接层
  77. h_pool2(batch, 7, 7, 64) -> h_fc1(1, 1024)
  78. """
  79. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  80. b_fc1 = bias_variable([1024])
  81. h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
  82. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  83. """
  84. Dropout
  85. h_fc1 -> h_fc1_drop,
  86. """
  87. keep_prob = tf.placeholder("float")
  88. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  89. """
  90. 第四层 Softmax输出层
  91. """
  92. W_fc2 = weight_variable([1024, 10])
  93. b_fc2 = bias_variable([10])
  94. y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  95. y_ = tf.placeholder("float", [None, 10])
  96. cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
  97. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  98. correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
  99. accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
  100. sess = tf.Session()
  101. sess.run(tf.global_variables_initializer())
  102. ds = DataSet(mnist.train.images,mnist.train.labels, 50000)
  103. for i in range(1000):
  104. "batch = mnist.train.next_batch(100)"
  105. image_batch, label_batch = ds.next_batch(100)
  106. train_step.run(session = sess, feed_dict = {x:image_batch, y_:label_batch,
  107. keep_prob:0.5})
  108. print("test accuracy %g" %accuracy.eval(session = sess,
  109. feed_dict = {x:mnist.test.images, y_:mnist.test.labels,
  110. keep_prob:1.0}))
  111. print("running time is %fs!" % (time.time() - start_time))

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

闽ICP备14008679号