需要安裝 python,numpy,tensorflow,運行代碼即可。
tensorflow很好裝,用pip安裝即可。
可以參照http://wiki.jikexueyuan.com/project/tensorflow-zh/get_started/os_setup.htm安裝。
數據集:mnist的,其實就是對數字進行分類。
input:就是圖像數據集
labels:數字從0到9. 輸出格式就是one-hot,一個10維度的向量,比如1就是[0,1,0,0,0,0,0,0,0,0,0].相應位置為1,其它位置為0.
1.CNN是一種帶有卷積結構的深度神經網絡,包括:
- 卷積層
- pooling layer
- fullConnection layer
大概過程就是:
圖像->卷積convention變換->pooling池化變換->卷積convention變換->pooling池化變換->fullConnection->output
2.卷積:
卷積就是用一個卷積函數去過濾輸入的圖像,這個過程會把和卷積函數相似的那些數據提取出來,變成相應的特征,我們可以用多個卷積函數去卷積,那么就可以提取出多個圖像,比如我代碼里面就從原始的1張圖片,變成32,再變成64...圖像特征出來。相當於把原始的一張圖片,變高,從1個張變成32張,每一張都是有卷積卷積出來的。 生成的32張可能分別包括了圖像的直線,角,紋理等一些什么特征。深度學習自己提取特征,不用我們手工來構造這些特征,像這種圖像,我們也不一定構造的特征就有用。
3.池化過程,就是下采樣。
每鄰域四個像素求和變為一個像素,然后通過標量Wx+1加權,再增加偏置bx+1,然后通過一個激活函數,產生一個大概縮小n倍的特征映射圖,降維,
- 圖像有種“靜態性”的屬性
- 降低維度
4.權值共享
CNN為了減少訓練參數,就是有個共享weight的概念,看代碼其實就知道,再卷積的那個過程,其實卷積函數和不同位置的圖像的w是一樣的,比如窗口是5*5,有6個卷積核,就是有6*(5*5+1)個訓練參數。
5.最后面的步驟就是和我們傳統介紹的ANN一樣,神經元都是全連接的。
[code]#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-07-24 12:52:36 # @Link : ${link} # @Version : $Id$ import tensorflow as tf # 引入tensorflow庫 from tensorflow.examples.tutorials.mnist import input_data # 引入tensorflow中的自帶的一個讀取mnist文件 mnist = input_data.read_data_sets('MNIST_data', one_hot=True) #計算每次迭代訓練模型的准確率,在訓練時, #增了額外的參數keep_prob在feed_dict中,以控制dropout的幾率; #最后一步用到了dropout函數將模型數值隨機地置零。如果keep_prob=1則忽略這步操作 #tf.argvmax:Returns the index with the largest value across dimensions of a tensor. def compute_accuracy(v_xs,v_ys): global prediction y_pre = sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1}) correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys,keep_prob:1}) return result #返回指定shape的weight變量,這邊truncated_normal表示正態分布 def weight_variable(shape): initial = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(initial) #返回指定shape的bias,這邊默認為0.1,constant 表示長量 def bias_variable(shape): initial = tf.constant(0.1,shape=shape) return tf.Variable(initial) #使用tensorflow的庫,卷積操作,x是輸入數據,W是權重 #Given an input tensor of shape [batch, in_height, in_width, in_channels] and a filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], #strides 表示那個卷積核移動的步數,這邊是1,並且采用smae,最后卷積的大小和輸入的圖像大小是一致的。 def conv2d(x,W): return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') #經過conv2d后,我們對過濾的圖像進行一個pooling操作 #輸入的x : [batch, height, width, channels] #ksize就是pool的大小 這邊是2*2 #strides 表示pool移動的步數,這邊是2,所以每次會縮小2倍 def max_pool_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') #輸入的784維度的數據,lable是10維度。None這邊表示訓練數據的大小,可以先填none。 #placeholder 表示這個變量沒有值,需要傳入 feed_dic xs = tf.placeholder(tf.float32,[None,784]) ys = tf.placeholder(tf.float32,[None,10]) keep_prob = tf.placeholder(tf.float32) #把輸入的數據轉化為28*28*1的格式,-1表示數據的大小,可以填寫為-1,最后一個1是rgb通道數目,這邊默認為1 #這樣x_image就變成[sample,28,28,1] x_image = tf.reshape(xs,[-1,28,28,1]) ## conv1 layer ## #第一層卷積,5*5的卷積核,輸入為1個圖像,卷積成32個28*28圖像 W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32 b_conv1 = bias_variable([32]) #tf.nn.relu是激勵函數 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32 #pooling縮小2倍,變成32個14*14的圖像 h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32 ## conv2 layer ## #第二層卷積,5*5的卷積核,輸入為32個圖像,卷積成64個28*28圖像 W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64 #pooling縮小2倍,變成64個7*7的圖像 h_pool2 = max_pool_2x2(h_conv2) #接下來就是普通的神經網絡過程 ## func1 layer ## W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64] #把多維數據變為1個維度的數據,就是數組了 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) #避免過擬合 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) ## func2 layer ## W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) #使用softmax預測(0~9) prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #損失函數 cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1])) # loss #優化函數 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) sess = tf.Session() # 初始化變量,一定要有 sess.run(tf.initialize_all_variables()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5}) if i % 50 == 0: print(compute_accuracy( mnist.test.images, mnist.test.labels))