儲存載入模型model.save()

Ding大道至簡發表於2020-12-15

當savemodel hd5 時

需要 metricstf.metrics.SparseCategoricalAcc uracy() 不能是 accuracy 字串 否則when load model 測試精確度會有問題。將產生懷疑

    def create_model():
        model = tf.keras.models.Sequential([
            keras.layers.Dense(512, activation='relu', input_shape=(784,)),
            keras.layers.Dropout(0.2),
            keras.layers.Dense(10)
        ])

        model.compile(optimizer='adam',
                      loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
                      metrics=[tf.metrics.SparseCategoricalAccuracy()])

        return model
model = create_model()
    model.fit(train_images, train_labels, epochs=5)

    model.save('saved_model/my_model')
    new_model = tf.keras.models.load_model('saved_model/my_model')


    # # 將整個模型儲存為 HDF5 檔案。
    # # '.h5' 副檔名指示應將模型儲存到 HDF5。
    # model.save('my_model.h5')
    #
    # # 重新建立完全相同的模型,包括其權重和優化程式
    # new_model = tf.keras.models.load_model('my_model.h5')

    # 顯示網路結構
    new_model.summary()
    # new_model.fit(train_images, train_labels, epochs=5)
    loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)
    print('Restored model, accuracy: {:5.2f}%'.format(100 * acc))

相關文章