Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách sử dụng mô hình tiền huấn luyện (pre-trained) với Keras trong Python

TensorFlow framework ML của Google. Keras API deep learning Python trên TensorFlow. Functional API và Sequential API đều có thể dùng mô hình tiền huấn luyện.

Sử dụng Google Colab. Code nạp Xception pre-trained trên ImageNet, đóng băng (freeze), thêm classifier trên đầu, biên dịch và huấn luyện:

Ví dụ

print("Nạp mô hình tích chập với trọng số tiền huấn luyện")
base_model = keras.applications.Xception(
    weights='imagenet',
    include_top=False,
    pooling='avg'
)
print("Đóng băng mô hình cơ sở")
base_model.trainable = False
print("Dùng Sequential thêm classifier có thể huấn luyện trên đầu")
model = keras.Sequential([
    base_model,
    layers.Dense(1000),
])
print("Biên dịch mô hình")
print("Huấn luyện mô hình trên dữ liệu kiểm tra")
model.compile(...)
model.fit(...)

Nguồn: TensorFlow Guide

Đầu ra

Nạp mô hình tích chập với trọng số tiền huấn luyện
Downloading data from https://storage.googleapis.com/tensorflow/kerasapplications/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h5
83689472/83683744 [==============================] - 1s 0us/step
Đóng băng mô hình cơ sở
Dùng Sequential thêm classifier có thể huấn luyện trên đầu
Biên dịch mô hình
Huấn luyện mô hình trên dữ liệu kiểm tra

Giải thích

  • Sequential model stack có thể dùng cùng pre-trained model để khởi tạo classification layers.
  • Sau khi xây dựng, biên dịch mô hình.
  • Sau khi biên dịch, fit mô hình vào dữ liệu huấn luyện.