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

วิธีใช้ TensorFlow Compile และ Fit โมเดลด้วย Python


TensorFlow เฟรมเวิร์ก ML จาก Google Open Source ใช้กับ Python อัลกอริทึม Deep Learning งานวิจัยและ Production มีเทคนิคเพิ่มประสิทธิภาพคำนวณ ใช้ NumPy และ Multi-dimensional Arrays (Tensors) รองรับ Deep Neural Network สเกลได้ดี มี Dataset ยอดนิยม ใช้ GPU Computation จัดการ Resource อัตโนมัติ มี Library ML มากมาย รองรับเอกสารดี รัน โมเดล Deep Neural Network ฝึกและสร้าง Application ทำนายลักษณะข้อมูลได้

ติดตั้ง tensorflow บน Windows:

pip install tensorflow

Tensor โครงสร้างข้อมูลใน TensorFlow (Data Flow Graph) เป็นอาร์เรย์หลายมิติ/ลิสต์

ใช้ Google Colab รันโค้ด (Python บนเบราว์เซอร์ ฟรี GPU บน Jupyter Notebook)

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

print("The vocab_size is actually vocab_size+1 since 0 is used as padding")
int_model = create_model(vocab_size=VOCAB_SIZE + 1, num_labels=4)
print("The model is compiled")
int_model.compile(
    loss=losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer='adam',
    metrics=['accuracy'])
print("The model is fit to the data")
history = int_model.fit(int_train_ds, validation_data=int_val_ds, epochs=5)

Credit: TensorFlow Tutorials

ผลลัพธ์

The vocab_size is actually vocab_size+1 since 0 is used as padding
The model is compiled
The model is fit to the data
Epoch 1/5
188/188 [==============================] - 7s 37ms/step - loss: 1.3020 - accuracy: 0.3877 - val_loss: 0.8041 - val_accuracy: 0.6625
Epoch 2/5
188/188 [==============================] - 5s 25ms/step - loss: 0.7200 - accuracy: 0.7003 - val_loss: 0.5815 - val_accuracy: 0.7685
Epoch 3/5
188/188 [==============================] - 5s 25ms/step - loss: 0.4517 - accuracy: 0.8471 - val_loss: 0.5137 - val_accuracy: 0.8040
Epoch 4/5
188/188 [==============================] - 5s 25ms/step - loss: 0.2709 - accuracy: 0.9311 - val_loss: 0.5091 - val_accuracy: 0.8065
Epoch 5/5
188/188 [==============================] - 5s 25ms/step - loss: 0.1453 - accuracy: 0.9717 - val_loss: 0.5320 - val_accuracy: 0.8025

คำอธิบาย

  • ใช้เมธอด create_model สร้างโมเดล

  • คอมไพล์ด้วย compile

  • เรียก fit เพื่อฝึกข้อมูลเข้ากับโมเดล