Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Configure Flower Dataset เพื่อ Performance ด้วย TensorFlow (เวอร์ชัน 2)

บทนำ

อีกวิธี configure dataset ให้เร็วขึ้น: ใช้ cache() + prefetch() พร้อมใส่ Rescaling layer เข้าในโมเดลโดยตรง

โค้ดตัวอย่าง

AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

num_classes = 5
print("A sequential model is built")
model = tf.keras.Sequential([
    layers.experimental.preprocessing.Rescaling(1./255),
    layers.Conv2D(32, 3, activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(32, 3, activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(32, 3, activation='relu'),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(num_classes)
])

ผลลัพธ์

A sequential model is built

คำอธิบาย

  • cache(): เก็บข้อมูลใน RAM หลัง epoch แรก (หรือ disk cache) → ไม่ต้องอ่านจาก disk ซ้ำ
  • prefetch(AUTOTUNE): overlap preprocessing และ model execution
  • Rescaling layer ในโมเดล: layers.experimental.preprocessing.Rescaling(1./255) → normalize input เป็นส่วนของโมเดล (deploy ง่าย, กัน mismatch)
  • ไม่ใช้ shuffle() และ batch() ที่นี่ เพราะอาจทำไว้ก่อนหน้านี้ (ดูบทความ 1004103449)

เปรียบเทียบ 2 วิธี

วิธีคำอธิบาย
บทความ 1004103449cache → shuffle → batch → prefetch (full pipeline)
บทความนี้cache → prefetch + Rescaling layer ในโมเดล (simpler)

Best Practice

รวมทั้งสอง: pipeline configure ด้วย tf.data (shuffle, batch, cache, prefetch) + preprocessing layers ในโมเดล (Rescaling, Resizing, Augmentation)