Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง Autoencoder จาก Encoder และ Decoder ด้วย Python

TensorFlow: ML Framework Google Open-source Tensor = Multi-dimensional array ใน Data Flow Graph ติดตั้ง pip install tensorflow

Keras: Deep Learning API Python จาก ONEIROS รันบน TensorFlow Scalable, Cross-platform เข้าถึงด้วย from tensorflow import keras

Functional API

ยืดหยุ่นกว่า Sequential API รองรับ Non-linear topology, Shared layers, Multiple I/O สร้าง DAG ของเลเยอร์

ตัวอย่าง: สร้าง Autoencoder แบบเดียว (Single Model) จาก Stack ของเลเยอร์

encoder_input = keras.Input(shape=(28, 28, 1), name="img")
print("Adding layers to the model")
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("Performing global max pooling")
encoder_output = layers.GlobalMaxPooling2D()(x)
print("Creating a model using the layers")
encoder = keras.Model(encoder_input, encoder_output, name="encoder")
print("More information about the model")
encoder.summary()

print("Reshaping the layers in the model")
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("More information about the autoencoder")
autoencoder.summary()

Code credit: TensorFlow Keras Functional Guide

ผลลัพธ์ (Model Summaries)

Model: "encoder"
Total params: 18,672

Model: "autoencoder"
Total params: 28,241

คำอธิบาย

  • เพิ่มเลเยอร์ลงในโมเดล
  • ทำ Global Max Pooling
  • สร้าง Model จากเลเยอร์ (Encoder)
  • แสดงข้อมูลโมเดลด้วย summary()
  • Functional API: ระบุ Inputs/Outputs ของ Graph-of-layers → ได้หลายโมเดลจากกราฟเดียว
  • Stack เหมือนกัน ใช้สร้าง Encoder (แปลงภาพเป็น 16-D Vector) และ Autoencoder (สำหรับเทรน)