神经网络和卷积神经网络的精度对比——以手写字体识别案例为例

关于神经网络和卷积神经网络,有一篇整理的很好的博客可供学习:https://blog.csdn.net/u014789266/article/details/53516861

这里利用tensorflow库自带的mnist手写字体数据集作为例子,来分别看神经网络和卷积神经网络的识别精度。tensorflow的安装方法在我的另一篇博客里(我的环境是win10+Anaconda3.6)

一、BP神经网络

导入需要的库和数据:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
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

该手写字体图像数据训练集共55000个样本,每个图像h=28,w=28,由于是黑白图,图像channel=1,因此每幅图像素点为28*28*1=784

trainlabel由十维组成的,有标签的维度上标为1,其余维度上标为0,比如如果该样本属于第三类,那么其label为[0,0,1,0,0,0,0,0,0,0],最后的得出的y的预测值实际上是在各个维度上的概率值,比如[0.1,0.3,0.9,0.02,0.1,0.1,0.2,0.3,0.15,0.2],那么这就表示第三个维度是1的可能性最高。

可以简单查看以下图像的编码是什么样子的:

np.reshape(trainimg[0, :], (28, 28)) #这就是训练集第一幅图像的编码
下面随机抽取5个样本查看其图像和标签:
nsample = 5
randidx = np.random.randint(trainimg.shape[0], size=nsample) #设定随机抽样的抽出来的标签

for i in randidx:
    curr_img   = np.reshape(trainimg[i, :], (28, 28)) # 28 by 28 matrix 
    curr_label = np.argmax(trainlabel[i, :] ) # Label
    plt.matshow(curr_img, cmap=plt.get_cmap('gray'))
    plt.title("" + str(i) + "th Training Data " 
              + "Label is " + str(curr_label))
    print ("" + str(i) + "th Training Data " 
           + "Label is " + str(curr_label))
    plt.show()
下面设置好隐层神经元的数目和input以及output的维度:
#设置两个隐层神经元的个数
n_hidden_1 = 256 
n_hidden_2 = 128 
#input和output的维度
n_input    = 784 
n_classes  = 10  
由于要一个batch一个batch地往里传入数据,因此下面要用tf里面的placeholder来先设定好变量类型和大小,而不直接用等于号给变量赋值:
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

下面设置权重参数W1,W2,W3,  W1是从input层传到hidden1层的权重矩阵,是一个784*256维的矩阵,同理W2,W3

weights和biases这两个分别是得分函数里的参数:得分函数=weights*X+biases,传入该变量时只需要指定好变量的维度,刚开始传入时传入的是random_normal(高斯分布)的

stddev = 0.1
#得分函数=weights*X+biases
weights = {
    'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),
    'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
下面定义激活函数:
def multilayer_perceptron(_X, _weights, _biases):
    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1']))
    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))
    return (tf.matmul(layer_2, _weights['out']) + _biases['out'])
括号里的含义:tf.matmul(_X, _weights['w1'])表示W1*X,再用tf.add(W1*X, _biases['b1'])表示W1*X+b,再将得分函数的值传入sigmoid函数,前两层都是有激活函数的,最后hidden2传到output时是没有激活函数的,直接返回【W_out * hidden2层的得分函数 + b_out】
下面输出预测值,计算loss值,再反向带回到前面去优化各层的权重函数
pred = multilayer_perceptron(x, weights, biases)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) #softmax型的loss
optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost) #以0.001为学习率去最小化loss
corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    
accr = tf.reduce_mean(tf.cast(corr, "float"))

# INITIALIZER
init = tf.global_variables_initializer()#全局变量初始化 
下面开始进行迭代(梯度下降的优化):
training_epochs = 20 
#epoch值的含义:如果有50000张图片,每次一个batch=100,那么epoch的个数=50000/100=500,每个epoch表示把数据完整地跑了一遍
batch_size      = 100
display_step    = 4
#每隔一个epoch或者一个batch打印一次当前的精度
sess = tf.Session()
sess.run(init)

for epoch in range(training_epochs):
    avg_cost = 0. #每次最初损失=0
    total_batch = int(mnist.train.num_examples/batch_size) #计算一个epoch里面有多少个batch
    # ITERATION
    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size) #传入每个batch的具体数据
        feeds = {x: batch_xs, y: batch_ys} #实际传进来的值
        sess.run(optm, feed_dict=feeds)
        #optm是梯度下降的优化器 = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost),每次传入的值是feeds
        avg_cost += sess.run(cost, feed_dict=feeds)
    avg_cost = avg_cost / total_batch #每个epoch的平均损失
    
    #下面展示精度
    if (epoch+1) % display_step == 0:
        print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
        feeds = {x: batch_xs, y: batch_ys}
        train_acc = sess.run(accr, feed_dict=feeds)
        print ("TRAIN ACCURACY: %.3f" % (train_acc))
        feeds = {x: mnist.test.images, y: mnist.test.labels}
        test_acc = sess.run(accr, feed_dict=feeds)
        print ("TEST ACCURACY: %.3f" % (test_acc))
最后的结果,5次epoch的精度分别如下:
    
Epoch: 003/020 cost: 2.276256993
TRAIN ACCURACY: 0.190
TEST ACCURACY: 0.188
Epoch: 007/020 cost: 2.241732514
TRAIN ACCURACY: 0.330
TEST ACCURACY: 0.328
Epoch: 011/020 cost: 2.203899798
TRAIN ACCURACY: 0.430
TEST ACCURACY: 0.414
Epoch: 015/020 cost: 2.160647209
TRAIN ACCURACY: 0.400
TEST ACCURACY: 0.498
Epoch: 019/020 cost: 2.109717269
TRAIN ACCURACY: 0.600
TEST ACCURACY: 0.571
可以看到损失值loss在逐渐减小,而精度在不断提高,但精度最高也就57%,这样的精度并不可观。

二、卷积神经网络

首先做一些预处理(由于读进来的不是图像文件而是csv文件,因此需要这样的处理)
data = pd.read_csv('train.csv')
images = data.iloc[:,1:].values
images = images.astype(np.float) #将数据转换为float类型

images = np.multiply(images, 1.0 / 255.0) #数据本来在0-255区间内,这里做除法变成在0-1区间内

image_size = images.shape[1]
image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)
本来每个图像都是784个像素点,每个点上的数值在一行中显示,现在要从input矩阵中选择一小块区域去乘上filter(一个特征提取的矩阵),因此要将input矩阵reshape成28*28矩阵形式:
def display(img):
   
    one_image = img.reshape(image_width,image_height) #将每行像素点数据变成矩阵形式
    
    plt.axis('off')
    plt.imshow(one_image, cmap=cm.binary)

# output image     
display(images[IMAGE_TO_DISPLAY])
由于现在的label值是0,1,2,3,......这种类型的,需要将它们转化为[0,0,1,0,0,0,0,0,0,0]这种类型的label,也就是说,现在label是一维的,下面把它转化为10维的:
labels_flat=data.iloc[:,0].values.ravel() #先提取labels
print('labels_flat({0})'.format(len(labels_flat)))

def dense_to_one_hot(labels_dense, num_classes):
    num_labels = labels_dense.shape[0] #表示labels的数量,这里num_labels是42000
    index_offset = np.arange(num_labels) * num_classes
    #[  0,   1,   2, ..., 41997, 41998, 41999] * 10= [  0,  10,  20, ..., 419970, 419980, 419990]
    labels_one_hot = np.zeros((num_labels, num_classes))
    #即np.zeros((42000, 10)) => 42000个10维的0向量(组成的列表)
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

labels = dense_to_one_hot(labels_flat, labels_count)
labels = labels.astype(np.uint8)
将数据集拆分成训练集40000个和验证集2000个:
VALIDATION_SIZE = 2000 #验证样本数量
validation_images = images[:VALIDATION_SIZE]
validation_labels = labels[:VALIDATION_SIZE]

train_images = images[VALIDATION_SIZE:]
train_labels = labels[VALIDATION_SIZE:]
得分函数为:input * Weight +Bias,下面做weight权重参数和bias(b)的随机高斯分布的初始化:
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')
tf.nn.conv2d函数的参数:
x是input矩阵,W是权重参数矩阵,padding='SAME'保证了每个像素的信息被利用相同多的次数,strides=[1, 1, 1, 1]中第1,4个值一般默认1,中间两个为每次横向、纵向移动的步数,pooling层各参数的含义与卷积层类似。
下面定义输入和输出的x和y:
# images
x = tf.placeholder('float', shape=[None, image_size]) #image_size=784,表示X的维度是784维
# labels
y_ = tf.placeholder('float', shape=[None, labels_count]) #labels_count=10,表示y的维度是10维
定义第一个卷积层并进行卷积:
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
image = tf.reshape(x, [-1,image_width , image_height,1]) 
print (image.get_shape()) #(40000,28,28,1)

#下面进行卷积
h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)
print (h_conv1.get_shape()) #(40000, 28, 28, 32)
【注】:
1、在上面这一段中,weight_variable和bias_variable分别是之前定义的初始化的函数,weight_variable()中的5个参数: filter是5*5的大小,1表示原始input数据只有1个channel(如果是彩图,channel是3),32是filter的个数,这里产生了32个filter,因此卷积一次结果是32张特征图。
2、tensorflow里面的数据都是4维的,reshape时,40000不动,将784转化为28*28*1,image_width , image_height都是28这里的-1是让python自己计算,即第一维的值为40000/(image_width*image_height*1)=40000
3、卷积的时候不改变输出的大小,因此输出的也是28*28的大小,但卷积会改变特征图的个数,这里从1变成了32

下面进行池化操作,注意池化是会改变输出的大小的:
h_pool1 = max_pool_2x2(h_conv1)
print (h_pool1.get_shape()) # => (40000, 14, 14, 32)
同样的道理,定义好第二个卷积层和第二次pooling:
W_conv2 = weight_variable([5, 5, 32, 64])
#第一层卷积层是32张特征图,因此这里的channel值必须为32,64是本轮的filter的个数
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
#print (h_conv2.get_shape()) # => (40000, 14,14, 64)

#第二次pooling
h_pool2 = max_pool_2x2(h_conv2)
#print (h_pool2.get_shape()) # => (40000, 7, 7, 64)
#卷积层中是784=28*28,全连接层就要变成是
接下来进入全连接层(FC),是将之前的三维立体的数据转化维一维的向量。卷积神经网络是立体的(3维的),而一般的神经网络是平面的(2维的)。因此下面将卷积神经网络的数据转变为一般神经网络的2维的数据:
W_fc1 = weight_variable([7 * 7 * 64, 1024]) #这里的W是两维的,所以只有7 * 7 * 64和1024这两个参数
b_fc1 = bias_variable([1024])

# (40000, 7, 7, 64) => (40000, 3136)
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])

#第一个全连接层的计算结果:W*X+b
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
卷积层不加dropout,只有在全连接层之后再加dropout:
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
一个卷积神经网络通常有2-3个全连接层,前面的全连接层相当于做特征的提取,最后一个全连接层相当于做的是分类的任务
W_fc2 = weight_variable([1024, labels_count])
b_fc2 = bias_variable([labels_count])

#最终的输出:
y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
重头戏终于来了,计算损失函数、进行最小化损失函数的梯度下降算法
#损失函数有两类,一种是softmax,一种是SVM,这里使用前者
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

#梯度下降算法——最小化损失函数
train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy)

#正确预测的个数
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

#预测精度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))

#定义最终的预测结果维概率最大的那一类
predict=tf.argmax(y,1)

设定好每一个batch怎么传入:

epochs_completed = 0
index_in_epoch = 0
num_examples = train_images.shape[0]

# serve data by batches
def next_batch(batch_size):
    
    global train_images
    global train_labels
    global index_in_epoch
    global epochs_completed
    
    start = index_in_epoch
    index_in_epoch += batch_size
    
    # when all trainig data have been already used, it is reorder randomly    
    if index_in_epoch > num_examples:
        # finished epoch
        epochs_completed += 1
        # shuffle the data
        perm = np.arange(num_examples)
        np.random.shuffle(perm)
        train_images = train_images[perm]
        train_labels = train_labels[perm]
        # start next epoch
        start = 0
        index_in_epoch = batch_size
        assert batch_size <= num_examples
    end = index_in_epoch
    return train_images[start:end], train_labels[start:end]
初始化这个session:
init = tf.global_variables_initializer()
sess = tf.InteractiveSession()

sess.run(init)
传入数据并进行迭代:
train_accuracies = []
validation_accuracies = []
x_range = []

display_step=1

for i in range(TRAINING_ITERATIONS):

    #get new batch
    batch_xs, batch_ys = next_batch(BATCH_SIZE) #传入每个batch的数据       

    # check progress on every 1st,2nd,...,10th,20th,...,100th... step
    if i%display_step == 0 or (i+1) == TRAINING_ITERATIONS:
        
        train_accuracy = accuracy.eval(feed_dict={x:batch_xs, 
                                                  y_: batch_ys, 
                                                  keep_prob: 1.0})       
        if(VALIDATION_SIZE):
            validation_accuracy = accuracy.eval(feed_dict={ x: validation_images[0:BATCH_SIZE], 
                                                            y_: validation_labels[0:BATCH_SIZE], 
                                                            keep_prob: 1.0})                                  
            print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i))
            
            validation_accuracies.append(validation_accuracy)
            
        else:
             print('training_accuracy => %.4f for step %d'%(train_accuracy, i))
        train_accuracies.append(train_accuracy)
        x_range.append(i)
        
        # increase display_step
        if i%(display_step*10) == 0 and i:
            display_step *= 10
    # train on batch
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: DROPOUT})
    #train_step是之前定义好的函数:train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy)
输出训练精度/验证精度:
training_accuracy / validation_accuracy => 0.10 / 0.06 for step 0
training_accuracy / validation_accuracy => 0.14 / 0.14 for step 1
training_accuracy / validation_accuracy => 0.14 / 0.24 for step 2
training_accuracy / validation_accuracy => 0.12 / 0.28 for step 3
training_accuracy / validation_accuracy => 0.34 / 0.32 for step 4
training_accuracy / validation_accuracy => 0.26 / 0.24 for step 5
training_accuracy / validation_accuracy => 0.24 / 0.40 for step 6
training_accuracy / validation_accuracy => 0.34 / 0.34 for step 7
training_accuracy / validation_accuracy => 0.30 / 0.36 for step 8
training_accuracy / validation_accuracy => 0.28 / 0.30 for step 9
training_accuracy / validation_accuracy => 0.48 / 0.42 for step 10
training_accuracy / validation_accuracy => 0.46 / 0.44 for step 20
training_accuracy / validation_accuracy => 0.66 / 0.68 for step 30
training_accuracy / validation_accuracy => 0.58 / 0.70 for step 40
training_accuracy / validation_accuracy => 0.74 / 0.72 for step 50
training_accuracy / validation_accuracy => 0.64 / 0.76 for step 60
training_accuracy / validation_accuracy => 0.86 / 0.74 for step 70
training_accuracy / validation_accuracy => 0.86 / 0.82 for step 80
training_accuracy / validation_accuracy => 0.82 / 0.86 for step 90
training_accuracy / validation_accuracy => 0.82 / 0.84 for step 100
training_accuracy / validation_accuracy => 0.90 / 0.88 for step 200
training_accuracy / validation_accuracy => 0.88 / 0.86 for step 300
training_accuracy / validation_accuracy => 0.88 / 0.96 for step 400
training_accuracy / validation_accuracy => 1.00 / 0.90 for step 500
training_accuracy / validation_accuracy => 0.92 / 0.92 for step 600
training_accuracy / validation_accuracy => 0.84 / 0.94 for step 700
training_accuracy / validation_accuracy => 0.94 / 0.94 for step 800
training_accuracy / validation_accuracy => 0.88 / 0.92 for step 900
training_accuracy / validation_accuracy => 0.96 / 0.92 for step 1000
training_accuracy / validation_accuracy => 1.00 / 0.94 for step 2000
training_accuracy / validation_accuracy => 0.98 / 0.94 for step 2499
第0次迭代的时候,初始精度为0.1,验证集上的精度只有0.06,通过2500次迭代,精度几乎稳定在了0.9以上,显然,卷积神经网络的识别精度远远好于一般的神经网络。



























  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值