tensorflow-cnn

須要安裝 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.python


1.CNN是一種帶有卷積結構的深度神經網絡,包括:數組

  • 卷積層
  • pooling layer
  • fullConnection layer

大概過程就是:網絡

圖像->卷積convention變換->pooling池化變換->卷積convention變換->pooling池化變換->fullConnection->output

2.卷積ide

     卷積就是用一個卷積函數去過濾輸入的圖像,這個過程會把和卷積函數類似的那些數據提取出來,變成相應的特徵,咱們能夠用多個卷積函數去卷積,那麼就能夠提取出多個圖像,好比我代碼裏面就從原始的1張圖片,變成32,再變成64...圖像特徵出來。至關於把原始的一張圖片,變高,從1個張變成32張,每一張都是有卷積卷積出來的。 生成的32張可能分別包括了圖像的直線,角,紋理等一些什麼特徵。深度學習本身提取特徵,不用咱們手工來構造這些特徵,像這種圖像,咱們也不必定構造的特徵就有用。函數

3.池化過程,就是下采樣。學習

     每鄰域四個像素求和變爲一個像素,而後經過標量Wx+1加權,再增長偏置bx+1,而後經過一個激活函數,產生一個大概縮小n倍的特徵映射圖,降維,優化

  • 圖像有種「靜態性」的屬性
  • 下降維度

4.權值共享spa

   CNN爲了減小訓練參數,就是有個共享weight的概念,看代碼其實就知道,再卷積的那個過程,其實卷積函數和不一樣位置的圖像的w是同樣的,好比窗口是5*5,有6個卷積核,就是有6*(5*5+1)個訓練參數。code

5.最後面的步驟就是和咱們傳統介紹的ANN同樣,神經元都是全鏈接的。orm

[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))

 
本站公眾號
   歡迎關注本站公眾號,獲取更多信息