最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實戰(zhàn)之MNIST手寫數(shù)字識別詳解

 更新時間:2022年01月05日 15:46:00   作者:跨考上浙大  
MNIST數(shù)據(jù)集是機器學(xué)習(xí)領(lǐng)域中非常經(jīng)典的一個數(shù)據(jù)集,由60000個訓(xùn)練樣本和10000個測試樣本組成,每個樣本都是一張28 * 28像素的灰度手寫數(shù)字圖片。本文主要介紹了通過 MNIST實現(xiàn)手寫數(shù)字識別,需要的可以參考一下

數(shù)據(jù)集介紹

MNIST數(shù)據(jù)集是機器學(xué)習(xí)領(lǐng)域中非常經(jīng)典的一個數(shù)據(jù)集,由60000個訓(xùn)練樣本和10000個測試樣本組成,每個樣本都是一張28 * 28像素的灰度手寫數(shù)字圖片,且內(nèi)置于keras。本文采用Tensorflow下Keras(Keras中文文檔)神經(jīng)網(wǎng)絡(luò)API進行網(wǎng)絡(luò)搭建。

開始之前,先回憶下機器學(xué)習(xí)的通用工作流程( √表示本文用到,×表示本文沒有用到 )

1.定義問題,收集數(shù)據(jù)集(√)

2.選擇衡量成功的指標(biāo)(√)

3.確定評估的方法(√)

4.準(zhǔn)備數(shù)據(jù)(√)

5.開發(fā)比基準(zhǔn)更好的模型(×)

6.擴大模型規(guī)模(×)

7.模型正則化與調(diào)節(jié)參數(shù)(×)

關(guān)于最后一層激活函數(shù)與損失函數(shù)的選擇

下面開始正文~

1.數(shù)據(jù)預(yù)處理

首先導(dǎo)入數(shù)據(jù),要使用mnist.load()函數(shù)

我們來看看它的源碼聲明:

def load_data(path='mnist.npz'):
  """Loads the [MNIST dataset](http://yann.lecun.com/exdb/mnist/).

  This is a dataset of 60,000 28x28 grayscale images of the 10 digits,
  along with a test set of 10,000 images.
  More info can be found at the
  [MNIST homepage](http://yann.lecun.com/exdb/mnist/).


  Arguments:
      path: path where to cache the dataset locally
          (relative to `~/.keras/datasets`).

  Returns:
      Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
      **x_train, x_test**: uint8 arrays of grayscale image data with shapes
        (num_samples, 28, 28).

      **y_train, y_test**: uint8 arrays of digit labels (integers in range 0-9)
        with shapes (num_samples,).
  """

可以看到,里面包含了數(shù)據(jù)集的下載鏈接,以及數(shù)據(jù)集規(guī)模、尺寸以及數(shù)據(jù)類型的聲明,且函數(shù)返回的是四個numpy array組成的兩個元組。

導(dǎo)入數(shù)據(jù)集并reshape至想要形狀,再標(biāo)準(zhǔn)化處理。

其中內(nèi)置于keras的to_categorical()就是one-hot編碼——將每個標(biāo)簽表示為全零向量,只有標(biāo)簽索引對應(yīng)的元素為1.

eg: col=10

[0,1,9]-------->[ [1,0,0,0,0,0,0,0,0,0],
                  [0,1,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,1] ]        

我們可以手動實現(xiàn)它:

def one_hot(sequences,col):
        resuts=np.zeros((len(sequences),col))
        # for i,sequence in enumerate(sequences):
        #         resuts[i,sequence]=1
        for i in range(len(sequences)):
                for j in range(len(sequences[i])):
                        resuts[i,sequences[i][j]]=1
        return resuts

下面是預(yù)處理過程

def data_preprocess():
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
    train_images = train_images.reshape((60000, 28, 28, 1))
    train_images = train_images.astype('float32') / 255
    #print(train_images[0])
    test_images = test_images.reshape((10000, 28, 28, 1))
    test_images = test_images.astype('float32') / 255

    train_labels = to_categorical(train_labels)
    test_labels = to_categorical(test_labels)
    return train_images,train_labels,test_images,test_labels

2.網(wǎng)絡(luò)搭建

這里我們搭建的是卷積神經(jīng)網(wǎng)絡(luò),就是包含一些卷積、池化、全連接的簡單線性堆積。我們知道多個線性層堆疊實現(xiàn)的仍然是線性運算,添加層數(shù)并不會擴展假設(shè)空間(從輸入數(shù)據(jù)到輸出數(shù)據(jù)的所有可能的線性變換集合),因此需要添加非線性或激活函數(shù)。relu是最常用的激活函數(shù),也可以用prelu、elu

def build_module():
    model = models.Sequential()
    #第一層卷積層,首層需要指出input_shape形狀
    model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))
    #第二層最大池化層
    model.add(layers.MaxPooling2D((2,2)))
    #第三層卷積層
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    #第四層最大池化層
    model.add(layers.MaxPooling2D((2,2)))
    #第五層卷積層
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    #第六層Flatten層,將3D張量平鋪為向量
    model.add(layers.Flatten())
    #第七層全連接層
    model.add(layers.Dense(64, activation='relu'))
    #第八層softmax層,進行分類
    model.add(layers.Dense(10, activation='softmax'))
    return model

使用model.summary()查看搭建的網(wǎng)路結(jié)構(gòu):

3.網(wǎng)絡(luò)配置

網(wǎng)絡(luò)搭建好之后還需要關(guān)鍵的一步設(shè)置配置。比如:優(yōu)化器——網(wǎng)絡(luò)梯度下降進行參數(shù)更新的具體方法、損失函數(shù)——衡量生成值與目標(biāo)值之間的距離、評估指標(biāo)等。配置這些可以通過 model.compile() 參數(shù)傳遞做到。

我們來看看model.compile()的源碼分析下:

  def compile(self,
              optimizer='rmsprop',
              loss=None,
              metrics=None,
              loss_weights=None,
              weighted_metrics=None,
              run_eagerly=None,
              steps_per_execution=None,
              **kwargs):
    """Configures the model for training.

關(guān)于優(yōu)化器

優(yōu)化器:字符串(優(yōu)化器名稱)或優(yōu)化器實例。

字符串格式:比如使用優(yōu)化器的默認(rèn)參數(shù)

實例優(yōu)化器進行參數(shù)傳入:

keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)
model.compile(optimizer='rmsprop',loss='mean_squared_error')

建議使用優(yōu)化器的默認(rèn)參數(shù) (除了學(xué)習(xí)率 lr,它可以被自由調(diào)節(jié))

參數(shù):

lr: float >= 0. 學(xué)習(xí)率。
rho: float >= 0. RMSProp梯度平方的移動均值的衰減率.
epsilon: float >= 0. 模糊因子. 若為 None, 默認(rèn)為 K.epsilon()。
decay: float >= 0. 每次參數(shù)更新后學(xué)習(xí)率衰減值。

類似還有好多優(yōu)化器,比如SGD、Adagrad、Adadelta、Adam、Adamax、Nadam等

關(guān)于損失函數(shù)

取決于具體任務(wù),一般來說損失函數(shù)要能夠很好的刻畫任務(wù)。比如

1.回歸問題

希望神經(jīng)網(wǎng)絡(luò)輸出的值與ground-truth的距離更近,選取能刻畫距離的loss應(yīng)該會更合適,比如L1 Loss、MSE Loss等

2.分類問題

希望神經(jīng)網(wǎng)絡(luò)輸出的類別與ground-truth的類別一致,選取能刻畫類別分布的loss應(yīng)該會更合適,比如cross_entropy

具體常見選擇可查看文章開始處關(guān)于損失函數(shù)的選擇

關(guān)于指標(biāo)

常規(guī)使用查看上述列表即可。下面說說自定義評價函數(shù):它應(yīng)該在編譯的時候(compile)傳遞進去。該函數(shù)需要以 (y_true, y_pred) 作為輸入?yún)?shù),并返回一個張量作為輸出結(jié)果。

import keras.backend as K
def mean_pred(y_true, y_pred):
    return K.mean(y_pred)

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy', mean_pred])

4.網(wǎng)絡(luò)訓(xùn)練與測試

1.訓(xùn)練(擬合)

使用model.fit(),它可以接受的參數(shù)列表

def fit(self,
          x=None,
          y=None,
          batch_size=None,
          epochs=1,
          verbose=1,
          callbacks=None,
          validation_split=0.,
          validation_data=None,
          shuffle=True,
          class_weight=None,
          sample_weight=None,
          initial_epoch=0,
          steps_per_epoch=None,
          validation_steps=None,
          validation_batch_size=None,
          validation_freq=1,
          max_queue_size=10,
          workers=1,
          use_multiprocessing=False):

這個源碼有300多行長,具體的解讀放在下次。

我們對訓(xùn)練數(shù)據(jù)進行劃分,以64個樣本為小批量進行網(wǎng)絡(luò)傳遞,對所有數(shù)據(jù)迭代5次

model.fit(train_images, train_labels, epochs = 5, batch_size=64)

2.測試

 

使用model.evaluates()函數(shù)
 

test_loss, test_acc = model.evaluate(test_images, test_labels)

關(guān)于測試函數(shù)的返回聲明:

Returns:
        Scalar test loss (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

5.繪制loss和accuracy隨著epochs的變化圖

model.fit()返回一個History對象,它包含一個history成員,記錄了訓(xùn)練過程的所有數(shù)據(jù)。

我們采用matplotlib.pyplot進行繪圖,具體見后面完整代碼。

Returns:
        A `History` object. Its `History.history` attribute is
        a record of training loss values and metrics values
        at successive epochs, as well as validation loss values
        and validation metrics values (if applicable).
def draw_loss(history):
    loss=history.history['loss']
    epochs=range(1,len(loss)+1)
    plt.subplot(1,2,1)#第一張圖
    plt.plot(epochs,loss,'bo',label='Training loss')
    plt.title("Training loss")
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()

    plt.subplot(1,2,2)#第二張圖
    accuracy=history.history['accuracy']
    plt.plot(epochs,accuracy,'bo',label='Training accuracy')
    plt.title("Training accuracy")
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.suptitle("Train data")
    plt.legend()
    plt.show()

6.完整代碼

from tensorflow.keras.datasets import mnist
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
def data_preprocess():
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
    train_images = train_images.reshape((60000, 28, 28, 1))
    train_images = train_images.astype('float32') / 255
    #print(train_images[0])
    test_images = test_images.reshape((10000, 28, 28, 1))
    test_images = test_images.astype('float32') / 255

    train_labels = to_categorical(train_labels)
    test_labels = to_categorical(test_labels)
    return train_images,train_labels,test_images,test_labels

#搭建網(wǎng)絡(luò)
def build_module():
    model = models.Sequential()
    #第一層卷積層
    model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))
    #第二層最大池化層
    model.add(layers.MaxPooling2D((2,2)))
    #第三層卷積層
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    #第四層最大池化層
    model.add(layers.MaxPooling2D((2,2)))
    #第五層卷積層
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    #第六層Flatten層,將3D張量平鋪為向量
    model.add(layers.Flatten())
    #第七層全連接層
    model.add(layers.Dense(64, activation='relu'))
    #第八層softmax層,進行分類
    model.add(layers.Dense(10, activation='softmax'))
    return model
def draw_loss(history):
    loss=history.history['loss']
    epochs=range(1,len(loss)+1)
    plt.subplot(1,2,1)#第一張圖
    plt.plot(epochs,loss,'bo',label='Training loss')
    plt.title("Training loss")
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()

    plt.subplot(1,2,2)#第二張圖
    accuracy=history.history['accuracy']
    plt.plot(epochs,accuracy,'bo',label='Training accuracy')
    plt.title("Training accuracy")
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.suptitle("Train data")
    plt.legend()
    plt.show()
if __name__=='__main__':
    train_images,train_labels,test_images,test_labels=data_preprocess()
    model=build_module()
    print(model.summary())
    model.compile(optimizer='rmsprop', loss = 'categorical_crossentropy', metrics=['accuracy'])
    history=model.fit(train_images, train_labels, epochs = 5, batch_size=64)
    draw_loss(history)
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print('test_loss=',test_loss,'  test_acc = ', test_acc)


迭代訓(xùn)練過程中l(wèi)oss和accuracy的變化

由于數(shù)據(jù)集比較簡單,隨便的神經(jīng)網(wǎng)絡(luò)設(shè)計在測試集的準(zhǔn)確率可達到99.2%

以上就是Python實戰(zhàn)之MNIST手寫數(shù)字識別詳解的詳細內(nèi)容,更多關(guān)于Python MNIST手寫數(shù)字識別的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python中實現(xiàn)常量(Const)功能

    Python中實現(xiàn)常量(Const)功能

    這篇文章主要介紹了Python中實現(xiàn)常量(Const)功能,python語言本身沒有提供const,本文使用一個類來實現(xiàn)常量定義功能,并介紹了使用方法,需要的朋友可以參考下
    2015-01-01
  • selenium python 實現(xiàn)基本自動化測試的示例代碼

    selenium python 實現(xiàn)基本自動化測試的示例代碼

    這篇文章主要介紹了selenium python 實現(xiàn)基本自動化測試的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • python pandas dataframe多列篩選方式

    python pandas dataframe多列篩選方式

    這篇文章主要介紹了python pandas dataframe多列篩選方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • python--字典(dict)和集合(set)詳解

    python--字典(dict)和集合(set)詳解

    本文通過實例給大家介紹了python中字典和集合的知識小結(jié),非常不錯,具有參考借鑒價值,需要的的朋友參考下吧,希望能夠給你帶來幫助
    2021-09-09
  • tensorflow實現(xiàn)在函數(shù)中用tf.Print輸出中間值

    tensorflow實現(xiàn)在函數(shù)中用tf.Print輸出中間值

    今天小編就為大家分享一篇tensorflow實現(xiàn)在函數(shù)中用tf.Print輸出中間值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python人臉識別第三方庫face_recognition接口說明文檔

    Python人臉識別第三方庫face_recognition接口說明文檔

    Python人臉識別第三方庫face_recognition接口簡單說明,及簡單使用方法
    2019-05-05
  • Django 狀態(tài)保持搭配與存儲的實現(xiàn)

    Django 狀態(tài)保持搭配與存儲的實現(xiàn)

    本文主要介紹了Django 狀態(tài)保持搭配與存儲的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • 國產(chǎn)麒麟系統(tǒng)kylin部署python項目詳細步驟

    國產(chǎn)麒麟系統(tǒng)kylin部署python項目詳細步驟

    這篇文章主要給大家介紹了關(guān)于國產(chǎn)麒麟系統(tǒng)kylin部署python項目的相關(guān)資料,文中通過代碼示例介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • slearn缺失值處理器之Imputer詳析

    slearn缺失值處理器之Imputer詳析

    這篇文章主要給大家介紹了關(guān)于slearn缺失值處理器之Imputer的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-08-08
  • Python OpenCV實現(xiàn)邊緣檢測

    Python OpenCV實現(xiàn)邊緣檢測

    這篇文章主要為大家詳細介紹了Python OpenCV實現(xiàn)邊緣檢測,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08

最新評論

丁青县| 仙桃市| 长丰县| 同德县| 东乡族自治县| 封开县| 湖北省| 曲麻莱县| 拉萨市| 荣成市| 保靖县| 饶平县| 弥勒县| 香港| 康乐县| 扎鲁特旗| 文水县| 凌海市| 临汾市| 天津市| 吴忠市| 鄯善县| 罗定市| 鹤岗市| 九龙城区| 开阳县| 英山县| 福清市| 泗阳县| 芜湖市| 都匀市| 鲁山县| 珲春市| 泰宁县| 金平| 左贡县| 丹阳市| 浦北县| 探索| 高安市| 聂拉木县|