จะโหลดโมเดลจากสถาปัตยกรรมของฉันได้อย่างไร

ฉันทำโค้ดนี้เสร็จแล้วและฉันต้องโหลดโมเดลเพื่อใช้งานในภายหลัง แต่เมื่อฉันพยายามใช้ load_model() ข้อผิดพลาดคือ No model found in config file. และเมื่อฉันพยายามโหลดตุ้มน้ำหนัก เกิดข้อผิดพลาดคือ ไม่สามารถโหลดตุ้มน้ำหนักที่บันทึกในรูปแบบ HDF5 ลงในโมเดลย่อยที่ยังไม่ได้สร้างตัวแปร เรียกโมเดลก่อน จากนั้นจึงโหลดตุ้มน้ำหนัก

นี่คือรหัสของฉัน

class Sampling(layers.Layer):
    """Uses (z_mean, z_log_var) to sample z, the vector encoding a digit."""

    def call(self, inputs):
        z_mean, z_log_var = inputs
        batch = tf.shape(z_mean)[0]
        dim = tf.shape(z_mean)[1]
        epsilon = tf.keras.backend.random_normal(shape=(batch, dim))
        return z_mean + tf.exp(0.5 * z_log_var) * epsilon

ฉันกำหนดตัวเข้ารหัสและตัวถอดรหัสที่จะใช้ในภายหลัง

class VAE(keras.Model):
    def __init__(self, encoder, decoder, **kwargs):
        super(VAE, self).__init__(**kwargs)
        self.encoder = encoder
        self.decoder = decoder

    def train_step(self, data):
        if isinstance(data, tuple):
            data = data[0]
        with tf.GradientTape() as tape:
            z_mean, z_log_var, z = encoder(data)
            reconstruction = decoder(z)
            reconstruction_loss = tf.reduce_mean(
                keras.losses.binary_crossentropy(data, reconstruction)
            )
            reconstruction_loss *= 64 * 64 * 3
            kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)
            kl_loss = tf.reduce_mean(kl_loss)
            kl_loss *= -0.5
            total_loss = reconstruction_loss + kl_loss
        grads = tape.gradient(total_loss, self.trainable_weights)
        self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
        return {
            "loss": total_loss,
            "reconstruction_loss": reconstruction_loss,
            "kl_loss": kl_loss,
        }
    
    def test_step(self, data):
        if isinstance(data, tuple):
            data = data[0]
        with tf.GradientTape() as tape:
            z_mean, z_log_var, z = encoder(data)
            reconstruction = decoder(z)
            reconstruction_loss = tf.reduce_mean(
                keras.losses.binary_crossentropy(data, reconstruction)
            )
            reconstruction_loss *= 64 * 64 * 3
            kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)
            kl_loss = tf.reduce_mean(kl_loss)
            kl_loss *= -0.5
            total_loss = reconstruction_loss + kl_loss
        grads = tape.gradient(total_loss, self.trainable_weights)
        self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
        return {
            "loss": total_loss,
            "reconstruction_loss": reconstruction_loss,
            "kl_loss": kl_loss,
        }

สุดท้ายนี่คือวิธีที่ฉันใช้มันและสร้างโมเดล

model_name = 'car_racing_VAE.h5'

vae = VAE(encoder, decoder)
vae.compile(optimizer=keras.optimizers.Adam(0.001))

checkpointer = keras.callbacks.ModelCheckpoint(filepath=model_name, monitor='val_loss', verbose=1, save_best_only=True, mode='min', save_freq='epoch')

history = vae.fit(train, train,
                epochs=150,
                batch_size = 128,
                shuffle=True,
                validation_data=(val, val), validation_batch_size=128,
                callbacks=[checkpointer])

แล้วฉันจะโหลดโมเดลและใช้งานในภายหลังได้อย่างไร?

model = load_model(model_name)
vae.load_weights(model_name)

ไม่มีใครทำงานเลย


person Marisol Rodriguez    schedule 18.11.2020    source แหล่งที่มา
comment
แล้วเส้นทางตัวเข้ารหัสของคุณอยู่ที่ไหน? และคุณช่วยแนบข้อผิดพลาดที่คุณพบได้ไหม   -  person dtlam26    schedule 18.11.2020
comment
เส้นทางเต็มที่คุณใช้ในการบันทึกโมเดลคืออะไร? ลองดูในตำแหน่งนั้นและดูว่ามีไฟล์ .h5 อยู่หรือไม่   -  person Gerry P    schedule 18.11.2020
comment
ไฟล์ .h5 คือตำแหน่งของโปรเจ็กต์ ฉันพยายามสร้างโฟลเดอร์และเรียกมัน ดังนั้นฉันจึงลอง vae.load_weights(model_name) และ vae.load_weights('/tmp/my_model.h5') ข้อผิดพลาดที่ฉันได้รับคือ Unable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights. หรือ No model found in config file. เมื่อใช้ model = load_model('my_model.h5')   -  person Marisol Rodriguez    schedule 18.11.2020


คำตอบ (1)


ตามข้อผิดพลาด ดูเหมือนว่ามีปัญหาในการโหลดโมเดลที่บันทึกไว้จากเส้นทาง

ตามที่ Gerry P แนะนำในความคิดเห็น ให้ตรวจสอบตำแหน่งของโมเดลที่บันทึกไว้และโหลดจากตำแหน่งเดียวกัน

คุณสามารถใช้โค้ดด้านล่างเพื่อหลีกเลี่ยงปัญหาเกี่ยวกับตำแหน่ง

#saving model
model = ...  # Get model 
model.save('path/to/location')

#loading the model back
from tensorflow import keras
model = keras.models.load_model('path/to/location')
person TFer    schedule 25.11.2020