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

Cách tạo Autoencoder từ Encoder và Decoder bằng Python (Keras Functional API)

TensorFlow framework ML của Google. Keras API deep learning Python trên TensorFlow. Functional API cho phép tạo nhiều mô hình từ cùng một đồ thị lớp.

Sử dụng Google Colab. Code xây dựng encoder, sau đó dùng đầu ra của encoder để xây dựng decoder, cuối cùng kết hợp thành autoencoder trong một đồ thị duy nhất:

Ví dụ

encoder_input = keras.Input(shape=(28, 28, 1), name="img")
print("Thêm lớp vào mô hình")
x = layers.Conv2D(16, 3, activation="relu")(encoder_input)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.Conv2D(16, 3, activation="relu")(x)
print("Thực hiện global max pooling")
encoder_output = layers.GlobalMaxPooling2D()(x)
print("Tạo mô hình encoder")
encoder = keras.Model(encoder_input, encoder_output, name="encoder")
print("Thông tin encoder")
encoder.summary()

print("Reshape các lớp")
x = layers.Reshape((4, 4, 1))(encoder_output)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
x = layers.Conv2DTranspose(32, 3, activation="relu")(x)
x = layers.UpSampling2D(3)(x)
x = layers.Conv2DTranspose(16, 3, activation="relu")(x)
decoder_output = layers.Conv2DTranspose(1, 3, activation="relu")(x)

autoencoder = keras.Model(encoder_input, decoder_output, name="autoencoder")
print("Thông tin autoencoder")
autoencoder.summary()

Nguồn: TensorFlow Guide

Đầu ra

... (tóm tắt encoder và autoencoder với các lớp và tham số) ...

Giải thích

  • Thêm lớp, thực hiện global max pooling, tạo mô hình encoder.
  • Hiển thị thông tin bằng summary.
  • Functional API cho phép tạo nhiều mô hình từ cùng một đồ thị lớp (encoder và autoencoder).
  • Stack lớp dùng để khởi tạo encoder (biến ảnh thành vector 16 chiều) và autoencoder (dùng để huấn luyện).