Kaggle神經網路實戰:CNN實現手寫數字辨識
簡要介紹
- 本文是基於Kaggle入門專案Digit Recognizer的處理方案,在MINST資料集上訓練可以識別手寫數字的模型。專案連結
- 程式碼來自專案Kernels,使用tensorflow實現CNN網路,完整圖文及程式碼請參照Kernel原文
程式碼實現
庫的匯入和常量定義
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import tensorflow as tf
LEARNING_RATE = 1e-4 #學習率
TRAINING_ITERATIONS = 2500 #訓練次數
DROPOUT = 0.5 #dropout防止過擬合
BATCH_SIZE = 50 #每個訓練批次大小
VALIDATION_SIZE = 2000
IMAGE_TO_DISPLAY = 10 #顯示第10張影象
資料預處理
通過CSV檔案匯入資料,資料格式為42000X785的矩陣,每行表示一條記錄,一共42000張圖片,每張圖片採用28X28畫素表示,第一列為延伸
data = pd.read_csv('../input/train.csv')
圖片處理
讀入的資料以DataFrame格式儲存,其中第一列為標籤(stretched array),對其去掉第一列並去索引
images = data.iloc[:,1:].values
images = images.astype(np.float) #轉換為浮點型
images = np.multiply(images,1.0/255.0) #壓縮灰度值
初始化圖片相關屬性變數
image_size = images.shape[1] #圖片大小
image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)
#圖片寬度和高度
定義影象視覺化函式
def display(img):
#(784) => (28X28)
one_image = img.reshape(image_width,image_height)
#不顯示座標軸
plt.axis('off')
#arg2:預設黑白影象
plt.imshow(one_image,cmap=cm.binary)
#函式測試
display(images[IMAGE_TO_DISPLAY])
獲得了4200X784的影象陣列
標籤處理
這裡對原始碼做了修改
取data的第一列即標籤,展平,統計標籤種類數
labels_flat = data.iloc[:,0].values
labels_count = np.unique(labels_flat).shape[0]
#np.unique(array)保留引數陣列中不同的值,返回兩個值
#1:不同的值組成的陣列 2:這些值首次出現位置組成的陣列
編寫函式,將標籤轉用獨熱碼(one-hot)表示
# 0 => [1 0 0 0 0 0 0 0 0 0]
# 1 => [0 1 0 0 0 0 0 0 0 0]
# ...
# 9 => [0 0 0 0 0 0 0 0 0 1]
def dense_to_one_hot(labels_dense, num_classes):
#arg1:標籤陣列 arg2:去重標籤陣列
num_labels = labels_dense.shape[0]
#統計標籤數量
index_offset = np.arange(num_labels) * num_classes
#確定大小
labels_one_hot = np.zeros((num_labels, num_classes))
#初始化0矩陣(42000X10)
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
#完成賦值
return labels_one_hot
labels = dense_to_one_hot(labels_flat, labels_count)
labels = labels.astype(np.uint8)
獲得了42000X10的標籤陣列
劃分訓練集與測試集
對影象和標籤採用最簡單的方法劃分訓練集與測試集
前2000份為測試集,後40000份為訓練集
validation_images = images[:VALIDATION_SIZE]
validation_labels = labels[:VALIDATION_SIZE]
train_images = images[VALIDATION_SIZE:]
train_labels = labels[VALIDATION_SIZE:]
網路架構
激勵函式使用ReLU,因為其易於訓練,初始化為極小的正數避免神經元死亡的現象發生。
變數定義
權重和偏置變數
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)
卷積層
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#採用邊緣補0的方法做卷積,步長為1
池化層
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#2X2劃分大小,步長為2
網路的輸入和輸出
x = tf.placeholder('float',shape=[None,imagesize])
#784維向量
y = tf.placeholder('float',shape=[None,labels_count])
#10維向量
具體實現
網路採用2組卷積-池化層
第一組卷積層使用32個5X5的filter提取特徵,池化層採用2X2的分割
28X28X1 => 28X28X32 =>14X14X32
#第一組卷積-池化層
W_conv1 = weight_variable([5, 5, 1, 32])
#[width,height,channels,features]
b_conv1 = bias_variable([32])
image = tf.reshape(x, [-1,image_width , image_height,1]
# (40000,784) => (40000,28,28,1)
h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)
#print (h_conv1.get_shape()) # => (40000, 28, 28, 32)
h_pool1 = max_pool_2x2(h_conv1)
#print (h_pool1.get_shape()) # => (40000, 14, 14, 32)
第二組卷積層使用64個5X5的filter提取特徵,池化層採用2X2的分割
14X14X32 => 14X14X64 =>7X7X64
# second convolutional layer
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
#print (h_conv2.get_shape()) # => (40000, 14,14, 64)
h_pool2 = max_pool_2x2(h_conv2)
#print (h_pool2.get_shape()) # => (40000, 7, 7, 64)
全連線層部分
對第二級池化層的輸出做展平操作,與隱層神經元連線
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
#1024個隱層神經元
# (40000, 7, 7, 64) => (40000, 3136)
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)
#print (h_fc1.get_shape()) # => (40000, 1024)
dropout防止過擬合
# dropout
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
隱層神經元連線輸出層神經元,這裡的啟用函式使用softmax函式,輸出網路判定最合適的分類
# 輸出層
W_fc2 = weight_variable([1024, labels_count])
b_fc2 = bias_variable([labels_count])
y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
訓練與測試
- 損失函式採用交叉熵(cross-entropy)
- 梯度下降優化法選用ADAM
# 損失函式
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
# 優化函式
train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)
# 準確度評估函式
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
predict = tf.argmax(y,1)
設定訓練引數
epochs_completed = 0
index_in_epoch = 0
num_examples = train_images.shape[0]
# 按小批次(batch)處理資料
def next_batch(batch_size):
global train_images
global train_labels
global index_in_epoch
global epochs_completed
start = index_in_epoch
index_in_epoch += batch_size
# when all trainig data have been already used, it is reorder randomly
if index_in_epoch > num_examples:
# finished epoch
epochs_completed += 1
# shuffle the data
perm = np.arange(num_examples)
np.random.shuffle(perm)
train_images = train_images[perm]
train_labels = train_labels[perm]
# start next epoch
start = 0
index_in_epoch = batch_size
assert batch_size <= num_examples
end = index_in_epoch
return train_images[start:end], train_labels[start:end]
# start TensorFlow session
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
# visualisation variables
train_accuracies = []
validation_accuracies = []
x_range = []
display_step=1
在訓練過程中追蹤準確率
for i in range(TRAINING_ITERATIONS):
#get new batch
batch_xs, batch_ys = next_batch(BATCH_SIZE)
# check progress on every 1st,2nd,...,10th,20th,...,100th... step
if i%display_step == 0 or (i+1) == TRAINING_ITERATIONS:
train_accuracy = accuracy.eval(feed_dict={x:batch_xs,
y_: batch_ys,
keep_prob: 1.0})
if(VALIDATION_SIZE):
validation_accuracy = accuracy.eval(feed_dict={ x: validation_images[0:BATCH_SIZE],
y_: validation_labels[0:BATCH_SIZE],
keep_prob: 1.0})
print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i))
validation_accuracies.append(validation_accuracy)
else:
print('training_accuracy => %.4f for step %d'%(train_accuracy, i))
train_accuracies.append(train_accuracy)
x_range.append(i)
# increase display_step
if i%(display_step*10) == 0 and i:
display_step *= 10
# train on batch
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: DROPOUT})
在測試集上計算誤差,同時對兩個準確度做視覺化
# check final accuracy on validation set
if(VALIDATION_SIZE):
validation_accuracy = accuracy.eval(feed_dict={x: validation_images,
y_: validation_labels,
keep_prob: 1.0})
print('validation_accuracy => %.4f'%validation_accuracy)
plt.plot(x_range, train_accuracies,'-b', label='Training')
plt.plot(x_range, validation_accuracies,'-g', label='Validation')
plt.legend(loc='lower right', frameon=False)
plt.ylim(ymax = 1.1, ymin = 0.7)
plt.ylabel('accuracy')
plt.xlabel('step')
plt.show()
相關推薦
Kaggle神經網路實戰:CNN實現手寫數字辨識
簡要介紹 本文是基於Kaggle入門專案Digit Recognizer的處理方案,在MINST資料集上訓練可以識別手寫數字的模型。專案連結 程式碼來自專案Kernels,使用tensorflow實現CNN網路,完整圖文及程式碼請參照Kernel原文
python-積卷神經網路全面理解-tensorflow實現手寫數字識別
首先,關於神經網路,其實是一個結合很多知識點的一個演算法,關於cnn(積卷神經網路)大家需要了解: 下面給出我之前總結的這兩個知識點(基於吳恩達的機器學習) 代價函式: 代價函式 代價函式(Cost Function )是
用pytorch實現多層感知機(MLP)(全連線神經網路FC)分類MNIST手寫數字體的識別
1.匯入必備的包 1 import torch 2 import numpy as np 3 from torchvision.datasets import mnist 4 from torch import nn 5 from torch.autograd import Variable 6
第三節,TensorFlow 使用CNN實現手寫數字識別
啟用 out min 灰度 HA 打破 gre 大量 gray 上一節,我們已經講解了使用全連接網絡實現手寫數字識別,其正確率大概能達到98%,著一節我們使用卷積神經網絡來實現手寫數字識別, 其準確率可以超過99%,程序主要包括以下幾塊內容 [1]: 導入數據,即測試集和
python神經網路(五)輸入手寫數字進行識別
一、斷點續訓 為防止突然斷電、引數白跑的情況發生,在backward中加入類似於之前test中載入ckpt的操作,給所有w和b賦儲存在ckpt中的值: (1) 如果儲存斷點檔案的目錄資料夾中,包含有效斷點狀態檔案,則返回該檔案: 引數說明 checkpoint_dir: 表示
python tensorflow 基於cnn實現手寫數字識別
感覺剛才的程式碼不夠給力,所以再儲存一份基於cnn的手寫數字自識別的程式碼 # -*- coding: utf-8 -*- import tensorflow as tf from tensorflow.examples.tutorials.mnist
C++使用matlab卷積神經網路庫MatConvNet來進行手寫數字識別
環境:WIN10(64 bit)+VS2010(64 bit)+Matlab2015b(64 bit) 我們的目的是將MatConvNet自帶的手寫數字識別DEMO移植到一個簡單的WIN32 DEMO中使用,主要過程有以下幾個步驟: (1)配置MatConvNet
【深度學習】3:BP神經網路與MNIST資料集實現手寫數字識別
前言:這是一篇基於tensorflow框架,建立的只有一層隱藏層的BP神經網路,做的圖片識別,內容也比較簡單,全當是自己的學習筆記了。 –—-—-—-—-—-—-—-—-—-—-—-—–—-—-—-—-—-—-—-——-—-—-—-—-—-—-—-—-—-—-
用python的numpy實現神經網路 實現 手寫數字識別
首先是讀取檔案,train-images-idx3-ubyte等四個檔案是mnist資料集裡的資料。放在MNIST資料夾裡。MNIST資料夾和這個.py檔案放在同一個資料夾裡。 import numpy as np import struct train_images
邏輯迴歸softmax神經網路實現手寫數字識別(cs)
邏輯迴歸softmax神經網路實現手寫數字識別全過程 1 - 匯入模組 import numpy as np import matplotlib.pyplot as plt from ld_mnist import load_digits
TensorFlow(九):卷積神經網絡實現手寫數字識別以及可視化
writer orm true 交叉 lar write 執行 one 界面 上代碼: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist =
TensorFlow(十二):使用RNN實現手寫數字識別
rop mea pre rnn ext ini tro truncate tutorial 上代碼: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #
kreas搭建神經網路預測波士頓房價(手寫K折交叉驗證)
1、程式說明 所有注意事項均寫入註釋 from keras.datasets import boston_housing import numpy as np from keras import models from keras import layers from keras.o
6 TensorFlow實現cnn識別手寫數字
———————————————————————————————————— 寫在開頭:此文參照莫煩python教程(牆裂推薦!!!) ———————————————————————————————————— 這個實驗的內容是:基於TensorFlow,實現
Android+TensorFlow+CNN+MNIST 手寫數字識別實現
SkySeraph 2018 Overview 本文系“SkySeraph AI 實踐到理論系列”第一篇,咱以AI界的HelloWord 經典MNIST資料集為基礎,在Android平臺,基於TensorFlow,實現CNN的手寫數字識別。Code here~ Practice Env
DL之NN:(sklearn自帶資料集為1797個樣本*64個特徵)利用NN之sklearn、NeuralNetwor.py實現手寫數字圖片識別95%準確率
先檢視sklearn自帶digits手寫資料集(1797*64)import numpy as np from sklearn.datasets import load_digits from skl
機器學習筆記 -吳恩達(第七章:邏輯迴歸-手寫數字識別,python實現 附原始碼)
(1)資料集描述 使用邏輯迴歸來識別手寫數字(0到9)。 將我們之前的邏輯迴歸的實現,擴充套件到多分類的實現。 資料集是MATLAB的本機格式,要載入它到Python,我們需要使用一個SciPy工具。影象在martix X中表示為400維向量(其中有5,000個), 400
tensorflow實現CNN識別手寫數字
上一篇使用TensorFlow識別手寫數字,是直接採用了softmax進行多分類,直接將28*28的圖片轉換成為了784維的向量作為輸入,然後通過一個(784,10)的權重,將輸入轉換成一個10維的向量,最後再將對每一個數字預測一個概率,概率最大的數字就是預測的結果。因為,
[052]TensorFlow Layers指南:基於CNN的手寫數字識別
TensorFlow Layers module 為容易的建立一個神經網路提供了高水平的API介面。它提供了很多方法幫助建立dense(全連線)層和卷積層,增加啟用函式和應用dropout做歸一化。在這個教程中,你會學到如何用layers構建一個卷積神經網路用於
第二節,TensorFlow 使用前饋神經網絡實現手寫數字識別
com net config return pyplot dataset 運行 算法 但是 一 感知器 感知器學習筆記:https://blog.csdn.net/liyuanbhu/article/details/51622695 感知器(Percep