Python tensorflow.python.keras.models.load_model() Examples

The following are 10 code examples of tensorflow.python.keras.models.load_model(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow.python.keras.models , or try the search function .
Example #1
Source File: classifier.py    From tempo-cnn with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, model_name='fcn'):
        """
        Initializes this classifier with a Keras model.

        :param model_name: model name from sub-package models. E.g. 'fma2018-meter'.
        """
        self._to_meter = lambda index: index + 2
        self.model_name = model_name
        # mazurka and deeptemp/shallowtempo models use a different kind of normalization
        self.normalize = std_normalizer if 'dt_maz_v' in self.model_name \
                                           or 'deeptemp' in self.model_name \
                                           or 'deepsquare' in self.model_name \
                                           or 'shallowtemp' in self.model_name \
            else max_normalizer
        resource = _to_model_resource(model_name)
        try:
            file = _extract_from_package(resource)
        except Exception as e:
            print('Failed to find a model named \'{}\'. Please check the model name.'.format(model_name),
                  file=sys.stderr)
            raise e
        try:
            self.model = load_model(file)
        finally:
            os.remove(file) 
Example #2
Source File: __init__.py    From ImageAI with MIT License 5 votes vote down vote up
def loadFullModel(self, prediction_speed="normal", num_objects=10):
        """
        'loadFullModel()' function is used to load the model structure into the program from the file path defined
        in the setModelPath() function. As opposed to the 'loadModel()' function, you don't need to specify the model type. This means you can load any Keras model trained with or without ImageAI and perform image prediction.
        - prediction_speed (optional), Acceptable values are "normal", "fast", "faster" and "fastest"
        - num_objects (required), the number of objects the model is trained to recognize

        :param prediction_speed:
        :param num_objects:
        :return:
        """

        self.numObjects = num_objects

        if (prediction_speed == "normal"):
            self.__input_image_size = 224
        elif (prediction_speed == "fast"):
            self.__input_image_size = 160
        elif (prediction_speed == "faster"):
            self.__input_image_size = 120
        elif (prediction_speed == "fastest"):
            self.__input_image_size = 100

        if (self.__modelLoaded == False):

            image_input = Input(shape=(self.__input_image_size, self.__input_image_size, 3))


            model = load_model(filepath=self.modelPath)
            self.__model_collection.append(model)
            self.__modelLoaded = True
            self.__modelType = "full" 
Example #3
Source File: app.py    From bootcamp with Apache License 2.0 5 votes vote down vote up
def load_model():
    global graph
    graph = tf.get_default_graph()

    global model
    model = VGG16(weights='imagenet',
                  input_shape=input_shape,
                  pooling='max',
                  include_top=False) 
Example #4
Source File: 3D_VResFCN_Upsampling_final_Motion_Shim_Multi_Label.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def load_best_model():
    from tensorflow.python.keras.models import load_model
    model = load_model(model_all, custom_objects={'loss_function': dice_coef_loss})
    return model 
Example #5
Source File: pbt_tune_cifar10_with_keras.py    From ray with Apache License 2.0 5 votes vote down vote up
def load_checkpoint(self, path):
        # See https://stackoverflow.com/a/42763323
        del self.model
        self.model = load_model(path) 
Example #6
Source File: tf_model_serialisation.py    From cxplain with MIT License 5 votes vote down vote up
def load(self, file_path):
        return load_model(file_path) 
Example #7
Source File: tensorflow_bind.py    From trains with Apache License 2.0 5 votes vote down vote up
def _patch_io_calls(Network, Sequential, keras_saving):
        try:
            if Sequential is not None:
                Sequential._updated_config = _patched_call(Sequential._updated_config,
                                                           PatchKerasModelIO._updated_config)
                if hasattr(Sequential.from_config, '__func__'):
                    # noinspection PyUnresolvedReferences
                    Sequential.from_config = classmethod(_patched_call(Sequential.from_config.__func__,
                                                                       PatchKerasModelIO._from_config))
                else:
                    Sequential.from_config = _patched_call(Sequential.from_config, PatchKerasModelIO._from_config)

            if Network is not None:
                Network._updated_config = _patched_call(Network._updated_config, PatchKerasModelIO._updated_config)
                if hasattr(Sequential.from_config, '__func__'):
                    # noinspection PyUnresolvedReferences
                    Network.from_config = classmethod(_patched_call(Network.from_config.__func__,
                                                                    PatchKerasModelIO._from_config))
                else:
                    Network.from_config = _patched_call(Network.from_config, PatchKerasModelIO._from_config)
                Network.save = _patched_call(Network.save, PatchKerasModelIO._save)
                Network.save_weights = _patched_call(Network.save_weights, PatchKerasModelIO._save_weights)
                Network.load_weights = _patched_call(Network.load_weights, PatchKerasModelIO._load_weights)

            if keras_saving is not None:
                keras_saving.save_model = _patched_call(keras_saving.save_model, PatchKerasModelIO._save_model)
                keras_saving.load_model = _patched_call(keras_saving.load_model, PatchKerasModelIO._load_model)
        except Exception as ex:
            LoggerRoot.get_base_logger(TensorflowBinding).warning(str(ex)) 
Example #8
Source File: prepare_model.py    From camera-trap-classifier with MIT License 5 votes vote down vote up
def load_model_from_disk(path_to_model_on_disk, compile=True):
    """ Load weights from disk and add to model """
    logging.info("Loading model from: %s" % path_to_model_on_disk)
    loaded_model = load_model(
        path_to_model_on_disk,
        compile=compile,
        custom_objects={
            'accuracy': accuracy,
            'top_k_accuracy': top_k_accuracy,
            'masked_loss_function':
                build_masked_loss(K.sparse_categorical_crossentropy)})
    return loaded_model 
Example #9
Source File: utils.py    From DeepCTR with Apache License 2.0 5 votes vote down vote up
def check_model(model, model_name, x, y, check_model_io=True):
    """
    compile model,train and evaluate it,then save/load weight and model file.
    :param model:
    :param model_name:
    :param x:
    :param y:
    :param check_model_io: test save/load model file or not
    :return:
    """

    model.compile('adam', 'binary_crossentropy',
                  metrics=['binary_crossentropy'])
    model.fit(x, y, batch_size=100, epochs=1, validation_split=0.5)

    print(model_name + " test train valid pass!")
    model.save_weights(model_name + '_weights.h5')
    model.load_weights(model_name + '_weights.h5')
    os.remove(model_name + '_weights.h5')
    print(model_name + " test save load weight pass!")
    if check_model_io:
        save_model(model, model_name + '.h5')
        model = load_model(model_name + '.h5', custom_objects)
        os.remove(model_name + '.h5')
        print(model_name + " test save load model pass!")

    print(model_name + " test pass!") 
Example #10
Source File: classifier.py    From tempo-cnn with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self, model_name='fcn'):
        """
        Initializes this classifier with a Keras model.

        :param model_name: model name from sub-package models. E.g. 'fcn', 'cnn', or 'ismir2018'
        """
        if 'fma' in model_name:
            # fma model uses log BPM scale
            factor = 256. / np.log(10)
            self.to_bpm = lambda index: np.exp((index + 435) / factor)
        else:
            self.to_bpm = lambda index: index + 30

        # match alias for dt_maz_v fold 0.
        if model_name == 'mazurka':
            model_name = 'dt_maz_v_fold0'
        # match aliases for specific deep/shallow models
        elif model_name == 'deeptemp':
            model_name = 'deeptemp_k16'
        elif model_name == 'shallowtemp':
            model_name = 'shallowtemp_k6'
        elif model_name == 'deepsquare':
            model_name = 'deepsquare_k16'
        self.model_name = model_name

        # mazurka and deeptemp/shallowtempo models use a different kind of normalization
        self.normalize = std_normalizer if 'dt_maz_v' in self.model_name \
                                           or 'deeptemp' in self.model_name \
                                           or 'deepsquare' in self.model_name \
                                           or 'shallowtemp' in self.model_name \
            else max_normalizer

        resource = _to_model_resource(model_name)
        try:
            file = _extract_from_package(resource)
        except Exception as e:
            print('Failed to find a model named \'{}\'. Please check the model name.'.format(model_name),
                  file=sys.stderr)
            raise e
        try:
            self.model = load_model(file)
        finally:
            os.remove(file)