卷积神经网络python代码
仅供学习参考使用
# -*- coding: utf-8 -*-
import numpy as np
class DataSet(object):
def __init__(self, images, labels, num_examples):
self._images = images
self._labels = labels
self._epochs_completed = 0 # 完成遍历轮数
self._index_in_epochs = 0 # 调用next_batch()函数后记住上一次位置
self._num_examples = num_examples # 训练样本数
def next_batch(self, batch_size, fake_data=False, shuffle=True):
start = self._index_in_epochs
if self._epochs_completed == 0 and start == 0 and shuffle:
index0 = np.arange(self._num_examples)
np.random.shuffle(index0)
self._images = np.array(self._images)[index0]
self._labels = np.array(self._labels)[index0]
if start + batch_size > self._num_examples:
self._epochs_completed += 1
rest_num_examples = self._num_examples - start
images_rest_part = self._images[start:self._num_examples]
labels_rest_part = self._labels[start:self._num_examples]
if shuffle:
index = np.arange(self._num_examples)
np.random.shuffle(index)
self._images = self._images[index]
self._labels = self._labels[index]
start = 0
self._index_in_epochs = batch_size - rest_num_examples
end = self._index_in_epochs
images_new_part = self._images[start:end]
labels_new_part = self._labels[start:end]
return np.concatenate((images_rest_part, images_new_part), axis=0), np.concatenate(
(labels_rest_part, labels_new_part), axis=0)
else:
self._index_in_epochs += batch_size
end = self._index_in_epochs
return self._images[start:end], self._labels[start:end]
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import time
start_time = time.time()
"""
权重初始化
"""
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')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],
strides = [1, 2, 2, 1], padding = 'SAME')
"""
第一层 卷积层
x_image(batch, 28, 28, 1) -> h_pool1(batch, 14, 14, 32)
"""
x = tf.placeholder(tf.float32,[None, 784])
x_image = tf.reshape(x, [-1, 28, 28, 1]) #最后一维代表通道数目,如果是rgb则为3
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)
"""
第二层 卷积层
h_pool1(batch, 14, 14, 32) -> h_pool2(batch, 7, 7, 64)
"""
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)
"""
第三层 全连接层
h_pool2(batch, 7, 7, 64) -> h_fc1(1, 1024)
"""
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)
"""
Dropout
h_fc1 -> h_fc1_drop,
"""
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
"""
第四层 Softmax输出层
"""
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
ds = DataSet(mnist.train.images,mnist.train.labels, 50000)
for i in range(1000):
"batch = mnist.train.next_batch(100)"
image_batch, label_batch = ds.next_batch(100)
train_step.run(session = sess, feed_dict = {x:image_batch, y_:label_batch,
keep_prob:0.5})
print("test accuracy %g" %accuracy.eval(session = sess,
feed_dict = {x:mnist.test.images, y_:mnist.test.labels,
keep_prob:1.0}))
print("running time is %fs!" % (time.time() - start_time))