In [ ]:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Lướt nhanh nâng cao TensorFlow 2.0

Lưu ý: Cộng đồng TensorFlow tại Việt Nam đã và đang dịch những tài liệu này từ nguyên bản tiếng Anh. Những bản dịch này được hoàn thiện dựa trên sự nỗ lực đóng góp từ cộng đồng lập trình viên sử dụng TensorFlow, và điều này có thể không đảm bảo được tính cập nhật của bản dịch đối với Tài liệu chính thức bằng tiếng Anh này. Nếu bạn có bất kỳ đề xuất nào nhằm cải thiện bản dịch này, vui lòng tạo Pull request đến kho chứa trên GitHub của tensorflow/docs-l10n. Để đăng ký dịch hoặc cải thiện nội dung bản dịch, các bạn hãy liên hệ và đặt vấn đề tại docs-vi@tensorflow.org.

Đây là một tệp notebook . Các chương trình Python sẽ chạy trực tiếp trong trình duyệt, giúp bạn dễ dàng tìm hiểu và sử dụng TensorFlow. Để làm theo giáo trình này, chạy notebook trên Google Colab bằng cách nhấp vào nút ở đầu trang.

  1. Trong Colab, kết nối đến Python runtime: Ở phía trên cùng bên phải của thanh menu, chọn CONNECT.
  2. Chạy tất cả các ô chứa mã trong notebook: Chọn Runtime > Run all.

Tải và cài đặt TensorFlow 2.0 RC.

Import TensorFlow vào chương trình:


In [ ]:
import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

Load và chuẩn bị tập dữ liệu MNIST.


In [ ]:
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Add a channels dimension
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]

Dùng tf.data để xáo trộn tập dữ liệu:


In [ ]:
train_ds = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(10000).batch(32)

test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

Xây dựng mô hình tf.keras với subclassing API của Keras:


In [ ]:
class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.conv1 = Conv2D(32, 3, activation='relu')
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10, activation='softmax')

  def call(self, x):
    x = self.conv1(x)
    x = self.flatten(x)
    x = self.d1(x)
    return self.d2(x)

# Create an instance of the model
model = MyModel()

Chọn trình tối ưu hoá (optimizer) và hàm thiệt hại (loss) để huấn luyện:


In [ ]:
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()

optimizer = tf.keras.optimizers.Adam()

Chọn số liệu để đo lường thiệt hại (loss) và độ chính xác (accuracy) của mô hình. Các số liệu này tích lũy các giá trị qua các epoch và sau đó in kết quả tổng thể.


In [ ]:
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

Dùng tf.GradientTape để huấn luyện:


In [ ]:
@tf.function
def train_step(images, labels):
  with tf.GradientTape() as tape:
    predictions = model(images)
    loss = loss_object(labels, predictions)
  gradients = tape.gradient(loss, model.trainable_variables)
  optimizer.apply_gradients(zip(gradients, model.trainable_variables))

  train_loss(loss)
  train_accuracy(labels, predictions)

Kiểm thử mô hình:


In [ ]:
@tf.function
def test_step(images, labels):
  predictions = model(images)
  t_loss = loss_object(labels, predictions)

  test_loss(t_loss)
  test_accuracy(labels, predictions)

In [ ]:
EPOCHS = 5

for epoch in range(EPOCHS):
  for images, labels in train_ds:
    train_step(images, labels)

  for test_images, test_labels in test_ds:
    test_step(test_images, test_labels)

  template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
  print(template.format(epoch+1,
                        train_loss.result(),
                        train_accuracy.result()*100,
                        test_loss.result(),
                        test_accuracy.result()*100))

  # Reset the metrics for the next epoch
  train_loss.reset_states()
  train_accuracy.reset_states()
  test_loss.reset_states()
  test_accuracy.reset_states()

Mô hình phân loại ảnh này, sau khi được huấn luyện bằng tập dữ liệu trên, đạt độ chính xác (accuracy) ~98%. Để tìm hiểu thêm, bạn có thể đọc Giáo trình TensorFlow.