Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chuẩn hóa tập flower dataset với TensorFlow

Chuẩn hóa dữ liệu (standardization) = scale dataset để tất cả feature dùng đơn vị tương đương. Layer Rescaling xây dựng bằng tf.keras.layers.experimental.preprocessing.Rescaling. Áp dụng cho toàn dataset bằng map().

Mã ví dụ

from tensorflow.keras import layers
print("Chuẩn hóa dữ liệu bằng rescaling layer")
normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)
print("Áp dụng layer bằng map trên dataset")
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
print(np.min(first_image), np.max(first_image))

Nguồn mã: TensorFlow Images Tutorial

Đầu ra

Chuẩn hóa dữ liệu bằng rescaling layer
Áp dụng layer bằng map trên dataset
0.0 0.96902645

Giải thích

  • Giá trị kênh RGB trong [0, 255] – không tốt cho neural network.
  • Mục tiêu: làm nhỏ đầu vào nhất có thể.
  • Chuẩn hóa giá trị ảnh về [0, 1] bằng rescaling layer.
  • Thay thế: đưa rescaling layer vào định nghĩa model → đơn giản hóa deployment.