1. 程式人生 > 程式設計 >tensorflow使用CNN分析mnist手寫體數字資料集

tensorflow使用CNN分析mnist手寫體數字資料集

本文例項為大家分享了tensorflow使用CNN分析mnist手寫體數字資料集,供大家參考,具體內容如下

import tensorflow as tf
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.examples.tutorials.mnist import input_data
 
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
trX,trY,teX,teY = mnist.train.images,mnist.train.labels,mnist.test.images,mnist.test.labels
#把上述trX和teX的形狀變為[-1,28,1],-1表示不考慮輸入圖片的數量,28×28是圖片的長和寬的畫素數,
# 1是通道(channel)數量,因為MNIST的圖片是黑白的,所以通道是1,如果是RGB彩色影象,通道是3。
trX = trX.reshape(-1,1) # 28x28x1 input img
teX = teX.reshape(-1,1) # 28x28x1 input img
 
X = tf.placeholder("float",[None,1])
Y = tf.placeholder("float",10])
#初始化權重與定義網路結構。
# 這裡,我們將要構建一個擁有3個卷積層和3個池化層,隨後接1個全連線層和1個輸出層的卷積神經網路
def init_weights(shape):
 return tf.Variable(tf.random_normal(shape,stddev=0.01))
 
w = init_weights([3,3,1,32])   # patch大小為3×3,輸入維度為1,輸出維度為32
w2 = init_weights([3,32,64])   # patch大小為3×3,輸入維度為32,輸出維度為64
w3 = init_weights([3,64,128])   # patch大小為3×3,輸入維度為64,輸出維度為128
w4 = init_weights([128 * 4 * 4,625])  # 全連線層,輸入維度為 128 × 4 × 4,是上一層的輸出資料又三維的轉變成一維, 輸出維度為625
w_o = init_weights([625,10]) # 輸出層,輸入維度為 625,輸出維度為10,代表10類(labels)
# 神經網路模型的構建函式,傳入以下引數
# X:輸入資料
# w:每一層的權重
# p_keep_conv,p_keep_hidden:dropout要保留的神經元比例
 
def model(X,w,w2,w3,w4,w_o,p_keep_conv,p_keep_hidden):
 # 第一組卷積層及池化層,最後dropout一些神經元
 l1a = tf.nn.relu(tf.nn.conv2d(X,strides=[1,1],padding='SAME'))
 # l1a shape=(?,32)
 l1 = tf.nn.max_pool(l1a,ksize=[1,2,padding='SAME')
 # l1 shape=(?,14,32)
 l1 = tf.nn.dropout(l1,p_keep_conv)
 
 # 第二組卷積層及池化層,最後dropout一些神經元
 l2a = tf.nn.relu(tf.nn.conv2d(l1,padding='SAME'))
 # l2a shape=(?,64)
 l2 = tf.nn.max_pool(l2a,padding='SAME')
 # l2 shape=(?,7,64)
 l2 = tf.nn.dropout(l2,p_keep_conv)
 # 第三組卷積層及池化層,最後dropout一些神經元
 l3a = tf.nn.relu(tf.nn.conv2d(l2,padding='SAME'))
 # l3a shape=(?,128)
 l3 = tf.nn.max_pool(l3a,padding='SAME')
 # l3 shape=(?,4,128)
 l3 = tf.reshape(l3,[-1,w4.get_shape().as_list()[0]]) # reshape to (?,2048)
 l3 = tf.nn.dropout(l3,p_keep_conv)
 # 全連線層,最後dropout一些神經元
 l4 = tf.nn.relu(tf.matmul(l3,w4))
 l4 = tf.nn.dropout(l4,p_keep_hidden)
 # 輸出層
 pyx = tf.matmul(l4,w_o)
 return pyx #返回預測值
 
#我們定義dropout的佔位符——keep_conv,它表示在一層中有多少比例的神經元被保留下來。生成網路模型,得到預測值
p_keep_conv = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")
py_x = model(X,p_keep_hidden) #得到預測值
#定義損失函式,這裡我們仍然採用tf.nn.softmax_cross_entropy_with_logits來比較預測值和真實值的差異,並做均值處理;
# 定義訓練的操作(train_op),採用實現RMSProp演算法的優化器tf.train.RMSPropOptimizer,學習率為0.001,衰減值為0.9,使損失最小;
# 定義預測的操作(predict_op)
cost = tf.reduce_mean(tf.nn. softmax_cross_entropy_with_logits(logits=py_x,labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001,0.9).minimize(cost)
predict_op = tf.argmax(py_x,1)
#定義訓練時的批次大小和評估時的批次大小
batch_size = 128
test_size = 256
#在一個會話中啟動圖,開始訓練和評估
# Launch the graph in a session
with tf.Session() as sess:
 # you need to initialize all variables
 tf. global_variables_initializer().run()
 for i in range(100):
  training_batch = zip(range(0,len(trX),batch_size),range(batch_size,len(trX)+1,batch_size))
  for start,end in training_batch:
   sess.run(train_op,feed_dict={X: trX[start:end],Y: trY[start:end],p_keep_conv: 0.8,p_keep_hidden: 0.5})
 
  test_indices = np.arange(len(teX)) # Get A Test Batch
  np.random.shuffle(test_indices)
  test_indices = test_indices[0:test_size]
 
  print(i,np.mean(np.argmax(teY[test_indices],axis=1) ==
       sess.run(predict_op,feed_dict={X: teX[test_indices],p_keep_conv: 1.0,p_keep_hidden: 1.0})))

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。