Python keras.utils.generic_utils.CustomObjectScope() Examples

The following are 6 code examples of keras.utils.generic_utils.CustomObjectScope(). 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 keras.utils.generic_utils , or try the search function .
Example #1
Source Project: PSPNet-Keras-tensorflow   Author: Vladkryvoruchko   File:    License: MIT License 6 votes vote down vote up
def __init__(self, nb_classes, resnet_layers, input_shape, weights):
        self.input_shape = input_shape
        self.num_classes = nb_classes

        json_path = join("weights", "keras", weights + ".json")
        h5_path = join("weights", "keras", weights + ".h5")
        if 'pspnet' in weights:
            if os.path.isfile(json_path) and os.path.isfile(h5_path):
                print("Keras model & weights found, loading...")
                with CustomObjectScope({'Interp': layers.Interp}):
                    with open(json_path) as file_handle:
                        self.model = model_from_json(
                print("No Keras model & weights found, import from npy weights.")
                self.model = layers.build_pspnet(nb_classes=nb_classes,
            print('Load pre-trained weights')
            self.model = load_model(weights) 
Example #2
Source Project: TUT-live-age-estimator   Author: mahehu   File:    License: MIT License 6 votes vote down vote up
def initialize_celeb(self):
        print("Initializing celebrity network...")

        with CustomObjectScope({'relu6': keras.layers.ReLU(6.),
                                'DepthwiseConv2D': keras.layers.DepthwiseConv2D,
                                'lifted_struct_loss': lifted_struct_loss,
                                'triplet_loss': triplet_loss}):
            self.siameseNet = keras.models.load_model(os.path.join(self.siamesepath, "feature_model.h5"))


        ##### Read celebrity features
        celebrity_features = self.siamesepath + os.sep + "features_" + self.celeb_dataset + ".h5"
        print("Reading celebrity data from {}...".format(celebrity_features))

        with h5py.File(celebrity_features, "r") as h5:
            celeb_features = np.array(h5["features"]).astype(np.float32)
            self.path_ends = list(h5["path_ends"])
            self.celeb_files = [os.path.join(self.visualization_path, s.decode("utf-8")) for s in self.path_ends]

        print("Building index...")
        self.celeb_index = faiss.IndexFlatL2(celeb_features.shape[1])
Example #3
Source Project: deephlapan   Author: jiujiezz   File:    License: GNU General Public License v2.0 5 votes vote down vote up
def run_model(i,X_test):
    score = np.zeros((5, len(X_test)))
    with CustomObjectScope({'Attention': Attention}):
        model=load_model(curDir+ 'model/binding_model' + str(i+1)+ '.hdf5')
        score[i,:] =np.squeeze(model.predict_proba(X_test))
    return score[i,:] 
Example #4
Source Project: deephlapan   Author: jiujiezz   File:    License: GNU General Public License v2.0 5 votes vote down vote up
def run_model1(i,X_test):
    score1 = np.zeros((5, len(X_test)))
    with CustomObjectScope({'Attention': Attention}):
        model1=load_model(curDir+ 'model/immunogenicity_model' + str(i+1)+ '.hdf5')
    return score1[i,:] 
Example #5
Source Project: Walk-Assistant   Author: YoongiKim   File:    License: GNU General Public License v3.0 5 votes vote down vote up
def load_model(self):
        global Graph  # multiprocess-able

        config = tf.ConfigProto()
        config.gpu_options.allow_growth = True
        config.gpu_options.per_process_gpu_memory_fraction = 0.3

        # model.99-0.98.h5
        files = glob.glob('models/{}/model.*.h5'.format(self.model_name))

        if len(files) == 0:
            print('Trained model not found from "models/{}/model.*.h5"'.format(self.model_name))
            print('Building new model because model file not found...')

            return self.build_model(self.kernel, self.stride)

        last_file = max(files, key=os.path.getctime)

        file_name = last_file.replace('\\', '/').split('/')[-1].replace('model.', '').replace('.h5', '')
        self.epoch = int(file_name.split('-')[0])
        acc = float(file_name.split('-')[1])

        with CustomObjectScope({'relu6': tf.nn.relu6, 'DepthwiseConv2D': keras.layers.DepthwiseConv2D, 'tf': tf}):
            model = load_model(last_file)


        Graph = tf.get_default_graph()

        print('Loaded last model - {}, epoch: {}, acc: {}'.format(last_file, self.epoch, acc))

        return model 
Example #6
Source Project: TUT-live-age-estimator   Author: mahehu   File:    License: MIT License 4 votes vote down vote up
def __init__(self, parent, params):
        print("Initializing recognition thread...")
        self.parent = parent

        ##### Initialize aligners for face alignment.
        aligner_path = params.get("recognition", "aligner")
        aligner_targets_path = params.get("recognition", "aligner_targets")
        self.aligner = keras.models.load_model(aligner_path)
        self.aligner_input_shape = (self.aligner.input_shape[2], self.aligner.input_shape[1])

        # load targets
        aligner_targets = np.loadtxt(aligner_targets_path)
        left_eye = (aligner_targets[36] + aligner_targets[39]) / 2
        right_eye = (aligner_targets[42] + aligner_targets[45]) / 2
        nose = aligner_targets[30]
        left_mouth = aligner_targets[48]
        right_mouth = aligner_targets[54]
        # Dlib order
        #self.shape_targets = np.stack((left_eye, left_mouth, nose, right_eye, right_mouth))
        # CNN order
        self.shape_targets = np.stack((left_eye, right_eye, nose, left_mouth, right_mouth))

        ##### Initialize networks for Age, Gender and Expression
        print("Initializing multitask network...")
        multitaskpath = params.get("recognition", "multitask_folder")
        with CustomObjectScope({'relu6': keras.layers.ReLU(6.),
                                'DepthwiseConv2D': keras.layers.DepthwiseConv2D}):
            self.multiTaskNet = keras.models.load_model(os.path.join(multitaskpath, 'model.h5'))

        ##### Read class names
        self.expressions = {int(key): val for key, val in params['expressions'].items()}  # convert string key to int
        self.minDetections = int(params.get("recognition", "mindetections"))

        ##### 2. CELEBRITY
        self.siamesepaths = params['celebmodels']
        self.siamesepath = self.siamesepaths["0"]
        self.celeb_dataset = params.get("recognition", "celeb_dataset")
        self.visualization_path = params.get("recognition", "visualization_path")

        # Starting the thread
        self.switching_model = False
        self.recognition_running = False
        print("Recognition thread started...")