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

วิธีใช้ TensorFlow เทรนโมเดลด้วยชุดข้อมูล StackOverflow Questions ใน Python

บทนำ

TensorFlow เป็นเฟรมเวิร์ก Machine Learning ของ Google ใช้ร่วมกับ Python รองรับ Deep Learning, GPU, และมีดาต้าเซตยอดนิยม built-in

Tensor (เทนเซอร์) คือโครงสร้างข้อมูลหลายมิติ มี 3 แอตทริบิวต์หลัก: Rank (มิติ), Type (ชนิดข้อมูล), Shape (รูปร่าง)

ใช้ Google Colab (ฟรี GPU, รันบนเบราว์เซอร์) ในตัวอย่างนี้

การติดตั้ง

pip install tensorflow

ตัวอย่างโค้ด (Bag-of-words Linear Model)

print("A bag-of-words linear model is built to train the stackoverflow dataset")
binary_model = tf.keras.Sequential([layers.Dense(4)])
binary_model.compile(
    loss=losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer='adam',
    metrics=['accuracy']
)
history = binary_model.fit(
    binary_train_ds, validation_data=binary_val_ds, epochs=10)

ผลลัพธ์การเทรน (10 Epochs)

Epoch 1/10 - loss: 1.2450 - accuracy: 0.5243 - val_accuracy: 0.7645
Epoch 2/10 - loss: 0.8304 - accuracy: 0.8172 - val_accuracy: 0.7895
...
Epoch 10/10 - loss: 0.3054 - accuracy: 0.9472 - val_accuracy: 0.8340

คำอธิบาย

  • ใช้ Sequential API สร้างโมเดล Linear (Dense layer)

  • ข้อมูลแบบ binary ใช้ Bag-of-words model

  • Loss: SparseCategoricalCrossentropy, Optimizer: Adam