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

การเทรนโมเดล (Fit Data) ด้วย TensorFlow และ Python


แนวคิด

ใช้เมธอด fit เพื่อเทรนโมเดลกับข้อมูล

แนวคิด Transfer Learning, TensorFlow Hub, Google Colab เหมือนเดิม

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

print("Training for 2 epochs only")
class CollectBatchStats(tf.keras.callbacks.Callback):
    def __init__(self):
        self.batch_losses = []
        self.batch_acc = []
    def on_train_batch_end(self, batch, logs=None):
        self.batch_losses.append(logs['loss'])
        self.batch_acc.append(logs['acc'])
        self.model.reset_metrics()

batch_stats_callback = CollectBatchStats()
print("The fit method is called")
history = model.fit(train_ds, epochs=2, callbacks=[batch_stats_callback])

Credit: TensorFlow Tutorials

ผลลัพธ์

Training for 2 epochs only
The fit method is called
Epoch 1/2
92/92 [==============================] - 88s 919ms/step - loss: 0.7155 - acc: 0.7460
Epoch 2/2
92/92 [==============================] - 85s 922ms/step - loss: 0.3694 - acc: 0.8754

คำอธิบาย

  • เมธอด .fit ใช้เทรนโมเดล
  • เทรนสั้นๆ แค่ 2 epochs
  • ใช้ Custom Callback เพื่อบันทึก loss และ accuracy ทุก batch เพื่อพลอทภายหลัง