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

Keras Model สามารถใช้เป็น Layer และเรียกใช้ได้หรือไม่? (Python)

TensorFlow: ML Framework Google Open-source ใช้ Python Algorithms, Deep Learning Tensor = Multi-dimensional array ใน Data Flow Graph

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

คำตอบ: ใช่ได้

Keras Model สามารถนำไปใช้เหมือน Layer ได้ โดยการเรียกมันบน Input หรือ Output ของ Layer อื่น

Functional API

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

ตัวอย่าง: Autoencoder จาก Encoder + Decoder Model

encoder_input = keras.Input(shape=(28, 28, 1), name="original_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()

decoder_input = keras.Input(shape=(16,), name="encoded_img")
print("Reshaping the layers in the model")
x = layers.Reshape((4, 4, 1))(decoder_input)
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)
print("Creating a model using the layers")
decoder = keras.Model(decoder_input, decoder_output, name="decoder")
print("More information about the model")
decoder.summary()

autoencoder_input = keras.Input(shape=(28, 28, 1), name="img")
encoded_img = encoder(autoencoder_input)
decoded_img = decoder(encoded_img)
autoencoder = keras.Model(autoencoder_input, decoded_img, name="autoencoder")
print("More information about the model")
autoencoder.summary()

Code credit: TensorFlow Keras Functional Guide

ผลลัพธ์ (Model Summaries)

Model: "encoder"
Total params: 18,672

Model: "decoder"
Total params: 9,569

Model: "autoencoder"
Total params: 28,241 (encoder + decoder)

คำอธิบาย

  • โมเดลใดๆ ก็สามารถใช้เป็น Layer ได้ โดยการเรียกมันบน Input/Output ของ Layer อื่น
  • เมื่อเรียกโมเดล Architecture และ Weights จะถูกนำไปใช้ซ้ำ (Reuse)
  • Autoencoder สร้างได้จากการ Chain Encoder และ Decoder Model เข้าด้วยกัน