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

วิธี Configure Flower Dataset เพื่อ Performance ด้วย TensorFlow

บทนำ

เพื่อให้ training เร็วและไม่ bottleneck ที่ I/O ใช้ tf.data API configure dataset: cache, shuffle, batch, prefetch

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

print("A function is defined that configures the dataset for performance")
def configure_for_performance(ds):
    ds = ds.cache()
    ds = ds.shuffle(buffer_size=1000)
    ds = ds.batch(batch_size)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds

print("The function is called on training dataset")
train_ds = configure_for_performance(train_ds)
print("The function is called on validation dataset")
val_ds = configure_for_performance(val_ds)

ผลลัพธ์

A function is defined that configures the dataset for performance
The function is called on training dataset
The function is called on validation dataset

คำอธิบาย

  • cache(): เก็บข้อมูลใน memory หลัง epoch แรก (หรือ on-disk cache ถ้าใหญ่เกิน) → epoch ต่อๆ ไปเร็วขึ้น
  • shuffle(buffer_size): สลับข้อมูลใน buffer เพื่อความสุ่ม (buffer ใหญ่ = สุ่มดีกว่า แต่ใช้ RAM มากขึ้น)
  • batch(batch_size): จัดกลุ่มเป็น batch
  • prefetch(AUTOTUNE): overlap preprocessing และ model execution (เตรียม batch ถัดไปขณะ GPU ทำงาน)
  • AUTOTUNE: ให้ TF เลือก buffer size อัตโนมัติ

ลำดับที่สำคัญ

cache → shuffle → batch → prefetch (shuffle ก่อน batch เพื่อความสุ่มระดับ sample)

ผลกระทบ

ลด GPU idle time, เพิ่ม throughput, training เร็วขึ้นมาก โดยเฉพาะ dataset ใหญ่หรือ storage ช้า