三维卷积神经网络预测MNIST数字详解
生活随笔
收集整理的這篇文章主要介紹了
三维卷积神经网络预测MNIST数字详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from __future__ import division,print_function
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
#導入mnist數據集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)'''
設置batch_size等超參數
'''
learning_rate = 0.001
training_iters = 500
batch_size = 128
'''
display_step :控制報告的粒度
例如:若display_step = 2,則將每訓練2個樣本輸出依次損失粒度,
與超參數不同,修改display_step 不會改變模型學習的規律通俗的說就是每隔10個訓練樣本打印輸出一次
'''
display_step = 10
#網絡參數
n_input = 784 #28*28
n_classes = 10
'''
dropout:意為拋棄,取值為0-1之間,表示隱藏層中的節點在每次迭代中
被遺棄的概率,通過在迭代中遺棄部分節點來使更多的節點都能取到比較是合適的值
'''
dropout = 0.85#聲明占位符
'''
[None,n_input]中的None表示一維值
'''
x = tf.placeholder(tf.float32,[None,n_input])
y = tf.placeholder(tf.float32,[None,n_classes])
'''
keep-prob 是一個具體數字,上個示例
中它是 0.5,而本例中它是 0.8,它表示保留某個隱藏單元的概率,
此處 keep-prob 等于 0.8,
它意味著消除任意一個隱藏單元的概率是 0.2
'''
keep_prob = tf.placeholder(tf.float32)'''
定義一個輸入為x,權值為W,偏置為b,給定步幅的卷積層,激活函數是ReLu,padding
設置為Same模式
strides:步長,
strides參數表示的是滑窗在輸入張量各個維度上的移動步長
而且一般要求 strides的參數,strides[0] = strides[3] = 1
具體什么含義呢?
一般而言,對于輸入張量(input tensor)有四維信息:[batch, height, width, channels](分別表示 batch_size,
也即樣本的數目,單個樣本的行數和列數,樣本的頻道數,
rgb圖像就是三維的,灰度圖像則是一維),
對于一個二維卷積操作而言,其主要作用在 height, width上。
strides參數確定了滑動窗口在各個維度上移動的步數。
一種常用的經典設置就是要求,strides[0]=strides[3]=1。
strides[0] = 1,也即在 batch 維度上的移動為 1,也就是不跳過任何一個樣本,否則當初也不該把它們作為輸入(input)
strides[3] = 1,也即在 channels 維度上的移動為 1,也就是不跳過任何一個顏色通道;padding設置same模式
padding一般有兩種模式 same ,valid
same模式:在卷積核做卷積的過程中(假如卷積核是2*2 但后續不足2*2的話,
same模式會給空缺值補0,從而使得特征圖大小不發生改變)
valid模式:在卷積過程中如果后續不足卷積核大小,則后續的值將會被舍棄
這種方法的特征圖一般來說會變小
'''
def conv2d(x,W,b,strides=1):x = tf.nn.conv2d(x,W,strides=[1,strides,strides,1],padding='SAME')'''
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
除去name參數用以指定該操作的name,與方法有關的一共五個參數:
第一個參數input:指需要做卷積的輸入圖像,它要求是一個Tensor,
具有[batch, in_height, in_width, in_channels]這樣的shape,
具體含義是[訓練時一個batch的圖片數量, 圖片高度, 圖片寬度, 圖像通道數],
注意這是一個4維的Tensor,要求類型為float32和float64其中之一
第二個參數filter:相當于CNN中的卷積核,
它要求是一個Tensor,具有[filter_height, filter_width, in_channels, out_channels]這樣的shape,
具體含義是[卷積核的高度,卷積核的寬度,圖像通道數,卷積核個數],
要求類型與參數input相同,
有一個地方需要注意,第三維in_channels,就是參數input的第四維
第三個參數strides:卷積時在圖像每一維的步長,這是一個一維的向量,長度4
第四個參數padding:string類型的量,只能是"SAME","VALID"其中之一,
這個值決定了不同的卷積方式
第五個參數:use_cudnn_on_gpu:bool類型,
是否使用cudnn加速,默認為true'''x=tf.nn.bias_add(x,b)'''tf.nn.bias_add(): 通俗解釋:一個叫bias的向量加到一個叫value的矩陣上,是向量與矩陣的每一行進行相加,得到的結果和value矩陣大小相同。'''return tf.nn.relu(x)
'''
定義一個輸入是X的maxpool層,卷積核為ksize并且padding為SAME:
'''
def maxpool2d(x,k=2):return tf.nn.max_pool(x,ksize=[1,k,k,1],strides=[1,k,k,1],padding='SAME')
'''
定義convnet,其構成是兩個卷積層,然后是全連接層,一個dropout層,最后是輸出層
'''
def conv_net(x,weights,biases,dropout):#reshape the input picturex = tf.reshape(x,shape=[-1,28,28,1])#first convolution layerconv1 = conv2d(x,weights['wc1'],biases['bc1'])conv1 = maxpool2d(conv1,k=2)conv2 = conv2d(conv1,weights['wc2'],biases['bc2'])conv2 = maxpool2d(conv2,k=2)fc1 = tf.reshape(conv2,[-1,weights['wd1'].get_shape().as_list()[0]])fc1 = tf.add(tf.matmul(fc1,weights['wd1']),biases['bd1'])fc1 = tf.nn.relu(fc1)fc1 = tf.nn.dropout(fc1,dropout)out = tf.add(tf.matmul(fc1,weights['out']),biases['out'])return out
'''
定義網絡層的權重和偏置。
第一個 conv 層有一個 5×5 的卷積核,
1 個輸入和 32 個輸出。
第二個 conv 層有一個 5×5 的卷積核,
32 個輸入和 64 個輸出。
全連接層有 7×7×64 個輸入和 1024 個輸出,
而第二層有 1024 個輸入和 10 個輸出對應于最后的數字數目。
所有的權重和偏置用 randon_normal 分布完成初始化:
'''weights = {'wc1':tf.Variable(tf.random_normal([5,5,1,32])),'wc2':tf.Variable(tf.random_normal([5,5,32,64])),'wd1':tf.Variable(tf.random_normal([7*7*64,1024])),'out':tf.Variable(tf.random_normal([1024,n_classes]))
}biaese = {'bc1':tf.Variable(tf.random_normal([32])),'bc2':tf.Variable(tf.random_normal([64])),'bd1':tf.Variable(tf.random_normal([1024])),'out':tf.Variable(tf.random_normal([n_classes]))
}'''
建立一個給定權重和偏置的 convnet。
定義基于 cross_entropy_with_logits 的損失函數,
并使用 Adam 優化器進行損失最小化。優化后,計算精度:
'''
pred = conv_net(x,weights,biaese,keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
init = tf.global_variables_initializer()'''
啟動計算圖并迭代 training_iterats次
,其中每次輸入 batch_size 個數據進行優化。
請注意,用從 mnist 數據集分離出的 mnist.train 數據進行訓練。
每進行 display_step 次迭代,
會計算當前的精度。
最后,在 2048 個測試圖片上計算精度,此時無 dropout
'''
train_loss = []
train_acc = []
test_acc = []with tf.Session() as sess:sess.run(init)step = 1while step<=training_iters:batch_x,batch_y = mnist.train.next_batch(batch_size)sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})if step % display_step==0:loss_train,acc_train = sess.run([cost,accuracy],feed_dict={x:batch_x,y:batch_y,keep_prob:1.})print("Iter"+str(step)+",Minibatch Loss = "+"{:.2f}".format(loss_train)+",Training Accuracy="+"{:.2f}".format(acc_train))#calculate accuracy for 2048 mnist test images#Note that in this case no dropoutacc_test = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.})print("Testing Accuracy:"+"{:.2f}".format(acc_train))train_loss.append(loss_train)train_acc.append(acc_train)test_acc.append(acc_test)step+=1eval_indices =range(0,training_iters,display_step)plt.plot(eval_indices,train_loss,'k-')plt.title('Softmax Loss Per iteration')plt.xlabel('Iteration')plt.ylabel('Softmax Loss')plt.show()plt.plot(eval_indices,train_acc,'k-',label='Train Set Accuracy')plt.plot(eval_indices,test_acc,'r--',label='Test Set Accuracy')plt.xlabel('Generation')plt.ylabel('Accuracy')plt.legend(loc='lower right')plt.show()
總結
以上是生活随笔為你收集整理的三维卷积神经网络预测MNIST数字详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: libevent的vs2013的源码工程
- 下一篇: 如何使用 Jenkins、GitHub