1. 程式人生 > >使用LSTM實現mnist手寫數字分類識別 TensorFlow

使用LSTM實現mnist手寫數字分類識別 TensorFlow

RNN做影象識別原理:MNIST資料集中一張圖片資料包含28*28的畫素點。RNN是將一張圖片資料的一行作為一個向量總體輸入一個X中。也就是說,RNN有28個輸入X,一個輸入X有28個畫素點。
輸出最後一個結果做為預測值。
 

TensorFlow入門學習程式碼:

# -*- coding: utf-8 -*-
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os.path as ops
import os

# LOG 等級說明
# '1' 這是預設的顯示等級,顯示所有資訊
# '2' 只顯示 warning 和 Error
# '3' 只顯示 Error
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 設定 LOG 輸出等級  

tf.reset_default_graph()  # 清除預設圖形堆疊並重置全域性預設圖形

# 讀取資料
mnist = input_data.read_data_sets('./mnist', one_hot=True)

# 定義超引數
training_iters = 20001
batch_size = 100  

n_inputs = n_steps = 28  # n_inputs是每步輸入值,對應影象列數; n_steps是時間步數,對應影象行數
n_hidden_number = 128  #隱藏層神經元個數
n_outputs = 10  #輸出層神經元個數,對應數字的10個類

x = tf.placeholder(tf.float32,[None,n_steps,n_inputs],name='x')  # 新增一個新的佔位符用於輸入正確值, 使用placeholder()來傳遞一個tensor到session.run()中
Y = tf.placeholder(tf.float32,[None,n_outputs],name='Y')

# 初始化引數
weights = {
        # shape = (28,128)  tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)  shape: 輸出張量的形狀,必選
        'in':tf.Variable(tf.random_normal([n_inputs,n_hidden_number])),  # tf.random_normal從服從指定正太分佈的數值中取出指定個數的值
        # shape = (128,10)
        'out':tf.Variable(tf.random_normal([n_hidden_number,n_outputs]))
        }

biases = {
        # shape = (128,)
        'in':tf.Variable(tf.constant(0.1,shape = [n_hidden_number,])),  # tf.constant生成一個給定值的常量
        # shape = (10,)
        'out':tf.Variable(tf.constant(0.1,shape = [n_outputs,]))
        }

# 模型
def RNN(X, weights, biases):
    ### 輸入層到核運算 ###
    # X shape = (100batch,28steps,28inputs) ==> (100batch*28steps,28inputs)
    X = tf.reshape(X,[-1,n_inputs])  # 將tensor變換為引數shape的形式  -1表示自動計算
    # X_in shape ==> (100batch*28steps,128hidden)
    X_in = tf.matmul(X,weights['in'])+biases['in']  #tf.matmul 矩陣乘法
    # X_in shape ==> (100batch,28steps,128hidden)
    X_in = tf.reshape(X_in,[-1,n_steps,n_hidden_number])
    
    ### cell核內運算 ###
    lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_number,forget_bias = 1.0)  # 選擇的cell是BasicLSTMCell
    # LSTM cell is divided into two parts-->(c_state,m_state)
    # RNN的中間狀態會得到兩部分——一個是當前輸出outputs,另一個是下時刻的記憶states,RNN在init_state中用c_state、m_state分別儲存這兩部分
    init_state = lstm_cell.zero_state(batch_size,dtype=tf.float32)  
    # 用dynamic_rnn的方法,用輸入值X_in進行核內運算,將輸出分別存入相應陣列中
    outputs,states = tf.nn.dynamic_rnn(lstm_cell,X_in,initial_state=init_state,time_major=False)
    
    ### 核內運算到輸出層 ###
    # 在核內以X_in為輸入,得到輸出outputs與states,當所有行都代入計算得到最後的輸出預測值。其中states[1] = outputs[-1],相當於最後一個輸出值。
    result = tf.matmul(states[1],weights['out'])+biases['out']
    return  result

# 儲存模型
saver = tf.train.Saver(max_to_keep=2)
# 儲存模型的路徑
ckpt_file_path = "./models/"  # models是資料夾,mnist是檔案命名使用的
path = os.path.dirname(os.path.abspath(ckpt_file_path))
if os.path.isdir(path) is False:
    os.makedirs(path)

# 代價函式和優化器
prediction = RNN(x,weights,biases)
tf.add_to_collection('predict', prediction)
#二次代價函式:預測值與真實值的誤差
# softmax_cross_entropy_with_logits分為兩步:第一步是先對網路最後一層的輸出做一個softmax,第二步是softmax的輸出向量[Y1,Y2,Y3...]和樣本的實際標籤做一個交叉熵
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction))  # labels:實際的標籤,logits:就是神經網路最後一層的輸出
#梯度下降法:資料龐大,選用AdamOptimizer優化器
train_step = tf.train.AdamOptimizer(1e-3).minimize(loss)

#結果存放在一個布林型列表中
correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(Y,1))
#求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32),name="accuracy")

# 訓練
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    step = 0
    
    while step*batch_size < training_iters:
        batch_xs,batch_ys = mnist.train.next_batch(batch_size)
        # batch_xs shape = [100,28,28]
        batch_xs = batch_xs.reshape([batch_size,n_steps,n_inputs])
#        batch_ys = batch_ys.reshape([batch_size,n_outputs])
    
        train_step.run(feed_dict = {x:batch_xs,Y:batch_ys,})  # 使用feed_dict來傳入tensor
#        sess.run([train_step], feed_dict = {x:batch_xs, Y:batch_ys,})
        
        if step % 50 == 0:
            train_accuracy = accuracy.eval(feed_dict={x:batch_xs,Y:batch_ys,})  # 評估模型,得出訓練的準確率
            print("step", step, "training accuracy", train_accuracy)
            
        if step % 100 == 0:
            model_name = 'mnist_{:s}'.format(str(step+1))
            model_save_path = ops.join(ckpt_file_path, model_name)
            saver.save(sess, model_save_path, write_meta_graph=True)  # 儲存模型 
            
        step += 1       

    # 用測試資料再評估下
    test_len = 100  # 必須跟batch_size相等
    test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_inputs))
    test_label = mnist.test.labels[:test_len]
    print ("Testing Accuracy:", \
           sess.run(accuracy, feed_dict={x: test_data, Y: test_label}))

載入模型程式碼:

# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "3"

mnist = input_data.read_data_sets("./mnist", one_hot=True)

n_input = 28
n_steps = 28
n_classes = 10

with tf.Session() as sess:
    new_saver = tf.train.import_meta_graph('./models/mnist_201.meta')
    new_saver.restore(sess, tf.train.latest_checkpoint('./models'))
    print("model loaded")

    graph = tf.get_default_graph()
    predict = tf.get_collection('predict')[0]
    input_x = graph.get_operation_by_name("x").outputs[0]
    y = graph.get_tensor_by_name("Y:0")
    Accuracy = graph.get_tensor_by_name("accuracy:0")
    print("arg init")

    x = mnist.test.images[0].reshape((-1, n_steps, n_input))
    y = mnist.test.labels[0].reshape(-1, n_classes)  # 轉為one-hot形式
    print("reshape done")   
    
    res = sess.run(predict, feed_dict={input_x: x })
    print("demo run")

    print("Actual class: ", str(sess.run(tf.argmax(y, 1))), \
          ", predict class ",str(sess.run(tf.argmax(res, 1))), \
          ", predict ", str(sess.run(tf.equal(tf.argmax(y, 1), tf.argmax(res, 1))))
          )

相關推薦

使用LSTM實現mnist數字分類識別 TensorFlow

RNN做影象識別原理:MNIST資料集中一張圖片資料包含28*28的畫素點。RNN是將一張圖片資料的一行作為一個向量總體輸入一個X中。也就是說,RNN有28個輸入X,一個輸入X有28個畫素點。 輸出最後一個結果做為預測值。   TensorFlow入門學習程式碼: # -

使用LeNet-5實現mnist數字分類識別 TensorFlow

TensorFlow的學習材料很多,但很少有講得特別詳細,讓小白一看就懂的。我自己總結了cnn實現mnist分類識別的方法,希望能給TensorFlow初學者一些幫助,實測在python3下可以執行。 # -*- coding: utf-8 -*- # 使用LeNet-5實

深度學習之PyTorch —— CNN實現MNIST數字分類

​# 運用CNN分析MNIST手寫數字分類 import torch import numpy as np from torch.utils.data import DataLoader from torchvision.datasets import mnist fro

深度學習系列——AlxeNet實現MNIST數字識別

    本文實現AlexNet,用於識別MNIST手寫數字體。所有程式碼的框架基於tensorflow。看了幾篇論文的原始碼之後,覺得tensorflow 確實很難,學習程式設計還是靠實踐。這篇部落格留著給自己以及學習深度學習道路上的小夥伴們一些參考吧,希望能對大家有所幫助!

OpenCV機器學習:SVM分類實現MNIST數字識別

0. 開發環境 最近機器學習隨著AI人工智慧的興起越來越火,博主想找一些ML的庫來練手。突然想起之前在看Opencv的doc時發現有ML的component,於是心血來潮就開始寫程式碼試試。話不多說,直接進正題。 以下我的開發環境配置: -Windows7

pytorch 利用lstmmnist數字識別分類

程式碼如下,U我認為對於新手來說最重要的是學會rnn讀取資料的格式。 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25 2018 @author: www """ import sys sys.path

MNIST數字圖片識別(線性回歸、CNN方法的手工及框架實現)(未完待續)

shape 初始化 result rect not found pro res edi ise 0-Background 作為Deep Learning中的Hello World 項目無論如何都要做一遍的。 代碼地址:Github 練習過程中將持續更新blog及代碼。 第一

神經網路實現Mnist數字識別筆記

目錄 1.Mnist手寫數字識別介紹         Mnist手寫數字識別是Kaggle上一個很經典的機器學習資料集,裡邊包括55000張訓練資料和10000張圖片的測試資料,每張圖片大小為28*28畫素的單通圖片。該任務為通過機器學習來識別圖片中的

CNN實現MNIST數字識別

關鍵詞:CNN、TensorFlow、卷積、池化、特徵圖 一. 前言 本文用TensorFlow實現了CNN(卷積神經網路)的經典結構LeNet-5, 具體CNN的LeNet-5模型原理見《深度學習(四)卷積神經網路入門學習(1)》,講得還是比較清楚的。

PyTorch基礎入門六:PyTorch搭建卷積神經網路實現MNIST數字識別

1)卷積神經網路(CNN)簡介 關於什麼是卷積神經網路(CNN),請自行查閱資料進行學習。如果是初學者,這裡推薦一下臺灣的李巨集毅的深度學習課程。連結就不給了,這些資料網站上隨處可見。 值得一提的是,CNN雖然在影象處理的領域具有不可阻擋的勢頭,但是它絕對不僅僅只能用來影

基於PyTorch的LSTM長短時記憶網路實現MNIST數字

本篇部落格主要介紹在PyTorch框架下,基於LSTM實現手寫數字的識別。在介紹LSTM長短時記憶網路之前,我先介紹一下RNN(recurrent neural network)迴圈神經網路.RNN是一種用來處理序列資料的神經網路,序列資料包括我們說話的語音、一段文字等等。它

Keras中將LSTM用於mnist數字識別

import keras from keras.layers import LSTM from keras.layers import Dense, Activation from keras.datasets import mnist from keras.models

深度學習入門——利用卷積神經網路實現MNIST數字識別

MNIST(Modified National Institute of Standards and Technology)資料庫是一個大型手寫數字資料庫,通常用於訓練各種影象處理系統。該資料庫還廣泛用於機器學習領域的培訓和測試。它是通過重新打亂來自NIST原始資料集的樣本而

北大人工智慧網課攻略[2]:mnist數字分類,並測試自己的手寫體

個人程式如下: 連結: https://pan.baidu.com/s/1Yy0Dg9AOGntDIdb4VGle4A 提取碼: zwv4 北大人工智慧網課考試一是手寫數字體識別,與常見的入門題目唯一的區別是我們需要再讀入老師手寫的圖片進行識別。編寫一下讀取普通圖片的程式帶入

Keras入門實戰(1):MNIST數字分類

前面的部落格中已經介紹瞭如何在Ubuntu下安裝Keras深度學習框架。 現在我們使用 Keras 庫來學習手寫數字分類。 我們這裡要解決的問題是:將手寫數字的灰度影象(28 畫素×28 畫素)劃分到 10 個類別 中(0~9)。我們將使用 MNIST 資料集,它是機器學

初識GAN之MNIST數字識別

初識GAN,因為剛好在嘗試用純python實現手寫數字的識別,所以在這裡也嘗試了一下。筆者也是根據網上教程一步步來的,不多說了,程式碼如下: from tensorflow.examples.tutorials.mnist import input_data i

Tensorflow卷積神經網路實現MNIST資料集識別

模型建的不好,最終只有85%左右的準確率,後面繼續改進吧   #卷積神經網路API     卷積層:tf.nn.conv2d(input,    #輸入張量,具有[batch, height, width, chann

Tensorflow 實戰Google深度學習框架——學習筆記(六)LeNet-5網路實現MNIST數字集識別

使用LeNet-5模型實現MNIST手寫數字識別,其神經網路架構如下: 一、詳細介紹LeNet-5模型每一層的結構 第一層,卷積層 這一層輸入原始的影象畫素,接受的輸入層大小為32*32*1,第一個卷積層過濾器尺寸為5*5,共6個,不使用全0填

全連線神經網路實現MNIST資料集識別

有目錄,內容大部分從官方教程copy,黑體加粗為對官方教程的補充 TensorFlow,pytorch,cuda,cudnn,anaconda安裝 版本對應關係 Version Python version Compiler Build tools cu

MNIST數字識別——CNN篇

這裡貼一個用nolearn,lasagne訓練CNN的例子,資料集嘛,當然是MNIST咯,keras暫時還沒研究過,但nolearn訓練CNN真的炒雞炒雞方便啊 這裡簡單說下CNN的結構,首先是輸入層,是一個1*28*28的影象矩陣,用32個5*5*1的濾波器去慮,得到3