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

วิธีใช้ Keras ในการเทรน ประเมิน และ Inference โมเดล

TensorFlow: ML Framework Google Open-source Optimization คณิตศาสตร์ซับซ้อน ใช้ NumPy, Multi-dimensional arrays (Tensors) รองรับ Deep Neural Networks ติดตั้ง pip install tensorflow

Keras: Deep Learning API Python จาก ONEIROS รันบน TensorFlow Scalable, Cross-platform (TPU, GPU, Web, Mobile) เข้าถึงด้วย from tensorflow import keras

Functional API

ยืดหยุ่นกว่า Sequential API รองรับ Non-linear topology, Shared layers, Multiple I/O สร้าง DAG ของเลเยอร์

ตัวอย่าง: เทรน ประเมิน MNIST

print("Load the MNIST data")
print("Split data into training and test data")
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

print("Reshape the data for better training")
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255

print("Compile the model")
model.compile(
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=keras.optimizers.RMSprop(),
    metrics=["accuracy"],
)

print("Fit the data to the model")
history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)

test_scores = model.evaluate(x_test, y_test, verbose=2)
print("The loss associated with model:", test_scores[0])
print("The accuracy of the model:", test_scores[1])

Code credit: TensorFlow Keras Functional Guide

ผลลัพธ์

Load the MNIST data
Split data into training and test data
Reshape the data for better training
Compile the model
Fit the data to the model
Epoch 1/2 750/750 [==============================] - 3s 3ms/step - loss: 0.5768 - accuracy: 0.8394 - val_loss: 0.2015 - val_accuracy: 0.9405
Epoch 2/2 750/750 [==============================] - 2s 3ms/step - loss: 0.1720 - accuracy: 0.9495 - val_loss: 0.1462 - val_accuracy: 0.9580
313/313 - 0s - loss: 0.1433 - accuracy: 0.9584
The loss associated with model: 0.14328785240650177
The accuracy of the model: 0.9584000110626221

คำอธิบาย

  • โหลด MNIST Data
  • แบ่ง Train/Test Set
  • Reshape และ Normalize ข้อมูล
  • Build และ Compile โมเดล
  • Fit กับ Training Data
  • แสดง Loss และ Accuracy บน Test Set