TensorFlow - Keras



Keras 是一個簡潔易學、高階的 Python 庫,執行在 TensorFlow 框架之上。它專注於理解深度學習技術,例如建立神經網路的層,同時保持形狀和數學細節的概念。框架的建立可以分為以下兩種型別:

  • 順序式 API
  • 函式式 API

考慮以下八個步驟來在 Keras 中建立深度學習模型:

  • 載入資料
  • 預處理載入的資料
  • 定義模型
  • 編譯模型
  • 擬合指定的模型
  • 評估模型
  • 做出必要的預測
  • 儲存模型

我們將使用 Jupyter Notebook 來執行並顯示輸出,如下所示:

步驟 1 - 首先實現載入資料和預處理載入的資料,以執行深度學習模型。

import warnings
warnings.filterwarnings('ignore')

import numpy as np
np.random.seed(123) # for reproducibility

from keras.models import Sequential
from keras.layers import Flatten, MaxPool2D, Conv2D, Dense, Reshape, Dropout
from keras.utils import np_utils
Using TensorFlow backend.
from keras.datasets import mnist

# Load pre-shuffled MNIST data into train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

此步驟可以定義為“匯入庫和模組”,這意味著所有庫和模組都作為初始步驟匯入。

步驟 2 - 在此步驟中,我們將定義模型架構:

model = Sequential()
model.add(Conv2D(32, 3, 3, activation = 'relu', input_shape = (28,28,1)))
model.add(Conv2D(32, 3, 3, activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation = 'softmax'))

步驟 3 - 現在讓我們編譯指定的模型:

model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

步驟 4 - 我們現在將使用訓練資料擬合模型:

model.fit(X_train, Y_train, batch_size = 32, epochs = 10, verbose = 1)

生成的迭代輸出如下:

Epoch 1/10 60000/60000 [==============================] - 65s - 
loss: 0.2124 - 
acc: 0.9345 
Epoch 2/10 60000/60000 [==============================] - 62s - 
loss: 0.0893 - 
acc: 0.9740 
Epoch 3/10 60000/60000 [==============================] - 58s - 
loss: 0.0665 - 
acc: 0.9802 
Epoch 4/10 60000/60000 [==============================] - 62s - 
loss: 0.0571 - 
acc: 0.9830 
Epoch 5/10 60000/60000 [==============================] - 62s - 
loss: 0.0474 - 
acc: 0.9855 
Epoch 6/10 60000/60000 [==============================] - 59s -
loss: 0.0416 - 
acc: 0.9871 
Epoch 7/10 60000/60000 [==============================] - 61s - 
loss: 0.0380 - 
acc: 0.9877 
Epoch 8/10 60000/60000 [==============================] - 63s - 
loss: 0.0333 - 
acc: 0.9895 
Epoch 9/10 60000/60000 [==============================] - 64s - 
loss: 0.0325 - 
acc: 0.9898 
Epoch 10/10 60000/60000 [==============================] - 60s - 
loss: 0.0284 - 
acc: 0.9910
廣告
© . All rights reserved.