TensorFlow实现简单的卷积网络
生活随笔
收集整理的這篇文章主要介紹了
TensorFlow实现简单的卷积网络
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用的數(shù)據集是MNIST,下載方法見之前的博客
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets(r"D:\PycharmProjects\tensorflow\MNIST_data", one_hot=True) sess = tf.InteractiveSession()# 后面有很多權重和偏置需要創(chuàng)建,所以這里定義創(chuàng)建權重和偏置的函數(shù)以方便重復使用 # 我們需要給權重制造噪聲以打破完全對稱,因為我們使用ReLU,也給偏置加一些小的正值以避免死亡節(jié)點 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)# 卷積層和池化層也是接下來重復使用的,因此也為它們定義創(chuàng)建函數(shù) # x是輸入,W是卷積的參數(shù),比如[5,5,1,32],前面兩個數(shù)字是卷積核的尺寸,第三個數(shù)字代表有多少個channel # 這里我們是灰度單色,所以是1,最后一個數(shù)字代表卷積核的數(shù)量,也就是這個卷積層會提取多少個特征 # 第三個參數(shù)是步長,雖然第三個參數(shù)提供的是一個長度為4的數(shù)組,但是第一維和最后一維的數(shù)字要求一定是 1 # 最后一個參數(shù)是填充的方法,SAME但表示添加全0填充,VALID表示不添加 def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')# 第二個參數(shù)為過濾器的尺寸。雖然是一個長度為4的一維數(shù)組,但是這個數(shù)組的第一個和最后一個數(shù)必須為1。 # 這意味著池化層的過濾器是不可以跨不同輸入樣例或者節(jié)點矩陣深度的。因為x的第一維對應一個batch,第四維是channel數(shù) # 因為希望整體上縮小尺寸,所以strides步長設為2,如果設為1,我們會得到一個尺寸不變的圖片 def max_pool_2x2(x):return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 10]) # 真實標簽 x_image = tf.reshape(x, [-1,28,28,1]) #將1×784轉為28×28,顏色通道只有1,-1代表樣本數(shù)量不確定#定義第一個卷積層,尺寸為5×5,1個顏色通道,32個卷積核 #tf.nn.bias_add提供了一個方便的函數(shù)給每一個節(jié)點加上偏置項,注意這里不能直接使用加法 #因為矩陣上不同位置上的節(jié)點都需要加上同樣的偏置項 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(tf.nn.bias_add(conv2d(x_image, W_conv1), b_conv1)) h_pool1 = max_pool_2x2(h_conv1)#定義第二個卷積層 W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(tf.nn.bias_add(conv2d(h_pool1, W_conv2), b_conv2)) h_pool2 = max_pool_2x2(h_conv2)#因為前面經歷了兩次2×2的池化層,所以邊長只有1/4即圖片變成7×7,因為第二個卷積層的卷積核數(shù)量為64 #所以輸出tensor的尺寸為7×7×64,將其轉成1D向量,再連接一個1024個隱含節(jié)點的全連接層 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)#減輕過擬合 keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)#將dropout輸出層的輸出連接一個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)cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) 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, tf.float32))tf.global_variables_initializer().run() for i in range(20000):batch = mnist.train.next_batch(50)if i%100 == 0: #每100次訓練,對準確率進行一次評測train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})print("step %d, training accuracy %g"%(i, train_accuracy))train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))?
總結
以上是生活随笔為你收集整理的TensorFlow实现简单的卷积网络的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python+OpenCV图像处理(六)
- 下一篇: EPSON 程序