TensorFlow 2 初學者快速入門

在 TensorFlow.org 上檢視 在 Google Colab 中執行 在 GitHub 上檢視原始碼 下載筆記本

這份簡短的簡介使用 Keras

  1. 載入預先建立的資料集。
  2. 建構可分類圖片的神經網路機器學習模型。
  3. 訓練這個神經網路。
  4. 評估模型的準確度。

本教學課程是 Google Colaboratory 筆記本。Python 程式直接在瀏覽器中執行,是學習和使用 TensorFlow 的絕佳方式。若要按照本教學課程操作,請按一下本頁頂端的按鈕,在 Google Colab 中執行筆記本。

  1. 在 Colab 中,連線至 Python 執行階段:在功能表列的右上角,選取「連線」。
  2. 若要執行筆記本中的所有程式碼,請選取「執行階段」>「全部執行」。若要一次執行一個程式碼儲存格,請將滑鼠游標懸停在每個儲存格上,然後選取「執行儲存格」圖示。

Run cell icon

設定 TensorFlow

將 TensorFlow 匯入您的程式以開始使用

import tensorflow as tf
print("TensorFlow version:", tf.__version__)
2024-07-13 06:52:18.998540: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:479] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-07-13 06:52:19.024905: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:10575] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-07-13 06:52:19.024943: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1442] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
TensorFlow version: 2.16.2

如果您是在自己的開發環境中 (而非 Colab) 按照操作說明進行,請參閱安裝指南,瞭解如何設定 TensorFlow 以進行開發。

載入資料集

載入並準備 MNIST 資料集。圖片的像素值範圍為 0 到 255。將這些值縮放至 0 到 1 的範圍,方法是將值除以 255.0。這也會將範例資料從整數轉換為浮點數

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

建構機器學習模型

建構 tf.keras.Sequential 模型

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/layers/reshaping/flatten.py:37: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
  super().__init__(**kwargs)

Sequential 適用於堆疊層,其中每一層都有一個輸入 張量 和一個輸出張量。層是具有已知數學結構的函式,可以重複使用並具有可訓練的變數。大多數 TensorFlow 模型都由層組成。此模型使用 FlattenDenseDropout 層。

對於每個範例,模型都會傳回一個 logitslog-odds 分數向量,每個類別各一個。

predictions = model(x_train[:1]).numpy()
predictions
array([[-0.16857487, -0.01702446, -0.18800262, -0.29049426, -0.1497654 ,
         0.01135813, -0.13169414,  0.28695202,  0.37672728,  0.13688533]],
      dtype=float32)

tf.nn.softmax 函式會將這些 logits 轉換為每個類別的機率

tf.nn.softmax(predictions).numpy()
array([[0.08373321, 0.09743506, 0.08212215, 0.07412229, 0.08532309,
        0.10024013, 0.086879  , 0.13204761, 0.14445063, 0.11364685]],
      dtype=float32)

使用 losses.SparseCategoricalCrossentropy 定義用於訓練的損失函式

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

損失函式會採用真實值向量和 logits 向量,並針對每個範例傳回純量損失。此損失等於真實類別的負對數機率:如果模型確定正確的類別,則損失為零。

這個未經訓練的模型提供的機率接近隨機 (每個類別 1/10),因此初始損失應接近 -tf.math.log(1/10) ~= 2.3

loss_fn(y_train[:1], predictions).numpy()
2.3001866

在開始訓練之前,請使用 Keras Model.compile 設定並編譯模型。將 optimizer 類別設定為 adam,將 loss 設定為您先前定義的 loss_fn 函式,並指定要針對模型評估的指標,方法是將 metrics 參數設定為 accuracy

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

訓練和評估您的模型

使用 Model.fit 方法調整模型參數並盡可能減少損失

model.fit(x_train, y_train, epochs=5)
Epoch 1/5
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1720853545.131188  523089 service.cc:145] XLA service 0x7fb588008030 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1720853545.131230  523089 service.cc:153]   StreamExecutor device (0): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131234  523089 service.cc:153]   StreamExecutor device (1): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131237  523089 service.cc:153]   StreamExecutor device (2): Tesla T4, Compute Capability 7.5
I0000 00:00:1720853545.131240  523089 service.cc:153]   StreamExecutor device (3): Tesla T4, Compute Capability 7.5
116/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.5960 - loss: 1.3751
I0000 00:00:1720853546.834081  523089 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 5s 1ms/step - accuracy: 0.8633 - loss: 0.4777
Epoch 2/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9561 - loss: 0.1461
Epoch 3/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9682 - loss: 0.1073
Epoch 4/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9744 - loss: 0.0848
Epoch 5/5
1875/1875 ━━━━━━━━━━━━━━━━━━━━ 2s 1ms/step - accuracy: 0.9772 - loss: 0.0711
<keras.src.callbacks.history.History at 0x7fb750d4bc40>

Model.evaluate 方法會檢查模型的效能,通常在驗證集測試集上進行。

model.evaluate(x_test,  y_test, verbose=2)
313/313 - 1s - 3ms/step - accuracy: 0.9766 - loss: 0.0709
[0.07090681046247482, 0.9765999913215637]

圖片分類器現在已針對此資料集訓練至約 98% 的準確度。若要瞭解詳情,請參閱 TensorFlow 教學課程

如果您希望模型傳回機率,您可以封裝已訓練的模型,並將 softmax 附加至模型

probability_model = tf.keras.Sequential([
  model,
  tf.keras.layers.Softmax()
])
probability_model(x_test[:5])
<tf.Tensor: shape=(5, 10), dtype=float32, numpy=
array([[1.2273183e-07, 8.7016083e-09, 5.6712506e-06, 1.6725733e-04,
        3.8532035e-11, 3.1167556e-07, 3.1886015e-13, 9.9981803e-01,
        6.9700377e-08, 8.4526291e-06],
       [3.8318063e-10, 5.3196814e-05, 9.9994433e-01, 1.2887319e-06,
        6.4013896e-16, 1.0868150e-06, 1.7267263e-09, 9.1941645e-14,
        1.7351501e-07, 1.2004752e-16],
       [8.1174614e-09, 9.9988675e-01, 2.9579714e-05, 1.9076538e-06,
        5.8524206e-06, 1.8120238e-06, 8.6344735e-06, 3.9572973e-05,
        2.5875805e-05, 3.4755587e-08],
       [9.9995661e-01, 1.8822339e-09, 1.1518332e-06, 4.0551839e-08,
        1.0557898e-08, 3.4465447e-07, 2.8761485e-06, 3.4590674e-05,
        1.2326135e-09, 4.4350991e-06],
       [2.7767928e-07, 4.2751531e-09, 3.1395750e-06, 3.2061170e-08,
        9.9942112e-01, 1.6970212e-07, 1.6067910e-06, 8.6861517e-05,
        7.6640458e-07, 4.8607125e-04]], dtype=float32)>

結論

恭喜!您已使用預先建立的資料集,透過 Keras API 訓練機器學習模型。

如需使用 Keras 的更多範例,請查看教學課程。若要進一步瞭解如何使用 Keras 建構模型,請閱讀指南。如果您想進一步瞭解如何載入和準備資料,請參閱關於圖片資料載入CSV 資料載入的教學課程。