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

วิธีใช้ TensorFlow/Keras ดึง Constructor Arguments ของ Layer Instance ใน Python

บทนำ

Keras Functional API ช่วยสร้างโมเดลที่ยืดหยุ่น (Non-linear topology, Shared layers, Multi I/O) ใช้ get_config() เพื่อ Serialize Layer Configuration

การติดตั้ง

pip install tensorflow

ตัวอย่างโค้ด

from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf

class CustomDense(layers.Layer):
    def __init__(self, units=32):
        super(CustomDense, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            trainable=True
        )
        self.b = self.add_weight(
            shape=(self.units,),
            initializer="random_normal",
            trainable=True
        )

    def call(self, inputs):
        return tf.matmul(inputs, self.w) + self.b

    def get_config(self):
        return {"units": self.units}

inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)

print("The below function returns constructor arguments for the instance of the layer")
config = model.get_config()
new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})

ผลลัพธ์

The below function returns constructor arguments for the instance of the layer

คำอธิบาย

  • Custom Layer ต้อง Implement get_config() คืน Dict ของ Constructor Args

  • model.get_config() รวม Config ทุก Layer

  • Model.from_config() สร้างโมเดลใหม่จาก Config (ต้องส่ง custom_objects)