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

Cách dùng Keras trích xuất đặc trưng từ Sequential model bằng Python

TensorFlow framework ML của Google. Keras API deep learning Python trên TensorFlow. Sequential model sau khi build hành xử như Functional API: mỗi lớp có input/output.

Sử dụng Google Colab. Code trích xuất đặc trưng từ TẤT CẢ các lớp của Sequential model:

Ví dụ

print("Tạo Sequential model")
initial_model = keras.Sequential(
    [
        keras.Input(shape=(250, 250, 3)),
        layers.Conv2D(32, 5, strides=2, activation="relu"),
        layers.Conv2D(32, 3, activation="relu"),
        layers.Conv2D(32, 3, activation="relu"),
    ]
)
print("Trích xuất đặc trưng từ mô hình")
feature_extractor = keras.Model(
    inputs=initial_model.inputs,
    outputs=[layer.output for layer in initial_model.layers],
)
print("Gọi feature extractor trên dữ liệu test")
x = tf.ones((1, 250, 250, 3))
features = feature_extractor(x)

Nguồn: TensorFlow Guide

Đầu ra

Sequential model created
Feature extraction form the model
The feature extractor method is called on test data

Giải thích

  • Sau khi kiến trúc sẵn sàng, huấn luyện, đánh giá, lưu, khôi phục mô hình.
  • Dùng nhiều GPU để tăng tốc.
  • Sequential model sau build như Functional API: mỗi lớp có input/output.
  • Trích xuất output của tất cả các lớp cùng lúc.