Search code examples
pythonpython-3.xjupyter-notebookexecution

Saving downloaded data as well as trained model


Is there a way to save the execution of a particular block of code in a notebook such that I don't have to run it again. And can continue with the rest of code after reloading?
For example,

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

(train_images1, train_labels), (test_images1, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images1 / 255.0, test_images1 / 255.0

#My cnn model, upto the training
#Save upto here.

Can I save the execution upto here for later usage, that is including the downloaded files and trained model.


Solution

  • Save Model:

    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    model.save_weights("model.h5")
    print("Saved model .......")
    

    Load saved Model:

    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    
    loaded_model.load_weights("model.h5")
    print("Loaded model...........")
    

    For more details, You can find my implementation here. Now this will save both dataset as well as trained model also.