读取数据
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import input_data
import warnings
warnings.filterwarnings('ignore')
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels
print ("MNIST ready")
初始化权重
n_input = 784
n_output = 10#10分类 图片为28*28*1
weights = {
'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)),#第一层卷积层,1是连接的输入深度,64是特征图
'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)),#第一层卷积层,64是连接的输入深度,128是特征图
'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),#第一层卷积层,28*28通过两次池化变为14*14,7*7,1024定义向量维度
'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))#第二层全连接层
}
biases = {
'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),#第一层卷积层
'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),#第一层卷积层
'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),#第一层卷积层
'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))#第二层全连接层
}
建立卷积,池化模型
#卷积
def conv_basic(_input, _w, _b, _keepratio):
# -1为tensor推断第一维的值,h,w都为28,1为通道数(灰度图)
_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])
# 第一层卷积层 _w['wc1']为第一层卷积层的参数 SAME pading在无数据时自动填充0
_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
#创建一个relu函数对卷积层进行非线性变换
_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
#池化
#例如mnist中的输入图像为 28 * 28 的黑白图像,其张量即为[batch,28,28,1],
#1代表黑白,RGB彩色图像的通道则为3,而batch 则为输入的图像数量,一次输入10张图片时,其为10,20张时则为20
_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#dropout层 _keepratio保留比例
_pool_dr1 = tf.nn.dropout(_pool1, _keepratio)
# 第二层卷积层 池化
_conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')
_conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))
_pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
_pool_dr2 = tf.nn.dropout(_pool2, _keepratio)
# 全连接层1 第一个参数是第二层池化层,第二个参数为全连接层的权重数目
_dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
# 全连接层1 激活 _dense1*w1+b
_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))
_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
# 全连接层2
_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
# RETURN
out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out
}
return out
print ("CNN READY")
建立cnn模型(反向传播)
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)
# 模型
#预测值
_pred = conv_basic(x, weights, biases, keepratio)['out']
#loss
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y))
#使用自适应矩估计梯度下降
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
#计算准确率
_corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
#初始化session
init = tf.global_variables_initializer()
# SAVER
print ("GRAPH READY")
迭代,模型求解
sess = tf.Session()
sess.run(init)
training_epochs = 15
batch_size = 16
display_step = 1
for epoch in range(training_epochs):
avg_cost = 0.
#total_batch = int(mnist.train.num_examples/batch_size)
total_batch = 10
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})
# Compute average loss
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})
print (" Training accuracy: %.3f" % (train_acc))
#test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})
#print (" Test accuracy: %.3f" % (test_acc))
print ("OPTIMIZATION FINISHED")
可以发现,卷积神经网络比之逻辑回归准确率更高,比之BP神经网络更容易收敛