TensorFlow là framework ML của Google, hỗ trợ deep learning, tính toán GPU, nhiều dataset có sẵn.
Sử dụng Google Colab (miễn phí GPU, dựa trên Jupyter) để chạy ví dụ.
Cài đặt
pip install tensorflow
Khái niệm Tensor
- Rank: số chiều (scalar=0, vector=1, matrix=2, ...).
- Type: kiểu dữ liệu (float32, int32, ...).
- Shape: kích thước từng chiều.
Ví dụ: Bag-of-words linear model
print("Xây dựng mô hình bag-of-words linear cho dataset StackOverflow")
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
)
Kết quả huấn luyện (10 epochs)
Epoch 1/10 - loss: 1.2450 - accuracy: 0.5243 - val_loss: 0.9285 - val_accuracy: 0.7645
Epoch 2/10 - loss: 0.8304 - accuracy: 0.8172 - val_loss: 0.7675 - val_accuracy: 0.7895
...
Epoch 10/10 - loss: 0.3054 - accuracy: 0.9472 - val_loss: 0.5080 - val_accuracy: 0.8340
Giải thích
- Dùng
Sequential APIxây dựng mạng nơ-ron đơn giản. - Vector hóa dữ liệu văn bản ở chế độ 'binary' (bag-of-words).
- Huấn luyện 10 epochs, accuracy validation đạt ~83%.