ข้อมูลภาพ (RGB) มีค่า 0-255 ควรปรับให้อยู่ในช่วง 0-1 ก่อนฝึกโมเดล (Standardization) โดยใช้ Rescaling layer
โค้ดตัวอย่าง
print("สร้าง Normalization layer...")
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
print("นำไปใช้กับ dataset ด้วย map function...")
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("ค่าต่ำสุดและสูงสุดหลัง normalize:", np.min(first_image), np.max(first_image))
ผลลัพธ์
สร้าง Normalization layer...
นำไปใช้กับ dataset ด้วย map function...
0.0 1.0
คำอธิบาย
- Rescaling(1./255): คูณค่า pixel ด้วย 1/255 แปลง 0-255 -> 0-1
- map(lambda x, y: (normalization_layer(x), y)): ใช้ layer กับทุก batch ใน dataset
- วิธีนี้ทำ preprocessing บน GPU (เร็ว) และเป็นส่วนหนึ่งของ graph
- วิธีอื่น: ใส่ Rescaling layer เข้าไปในโมเดลโดยตรง (deploy ง่ายกว่า)
- Neural network ทำงานดีกว่าเมื่อ input มีค่าเล็ก ใกล้ 0 (ช่วย gradient descent)