Python keras.models.model_from_json() Examples

The following are 30 code examples of keras.models.model_from_json(). 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.models , or try the search function .
Example #1
Source File: use_charnet.py    From reading-text-in-the-wild with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, architecture_file=None, weight_file=None, optimizer=None):
        # Generate mapping for softmax layer to characters
        output_str = '0123456789abcdefghijklmnopqrstuvwxyz '
        self.output = [x for x in output_str]
        self.L = len(self.output)

        # Load model and saved weights
        from keras.models import model_from_json
        if architecture_file is None:
            self.model = model_from_json(open('char2_architecture.json').read())
        else:
            self.model = model_from_json(open(architecture_file).read())

        if weight_file is None:
            self.model.load_weights('char2_weights.h5')
        else:
            self.model.load_weights(weight_file)

        if optimizer is None:
            from keras.optimizers import SGD
            optimizer = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
        self.model.compile(loss='categorical_crossentropy', optimizer=optimizer) 
Example #2
Source File: keras_utils.py    From timeception with GNU General Public License v3.0 6 votes vote down vote up
def load_model(json_path, weight_path, metrics=None, loss=None, optimizer=None, custom_objects=None, is_compile=True):
    with open(json_path, 'r') as f:
        model_json_string = json.load(f)
    model_json_dict = json.loads(model_json_string)
    model = model_from_json(model_json_string, custom_objects=custom_objects)
    model.load_weights(weight_path)

    if is_compile:
        if optimizer is None:
            optimizer = model_json_dict['optimizer']['name']

        if loss is None:
            loss = model_json_dict['loss']

        if metrics is None:
            model.compile(loss=loss, optimizer=optimizer)
        else:
            model.compile(loss=loss, optimizer=optimizer, metrics=metrics)

    return model 
Example #3
Source File: Utils.py    From Contrastive-Explanation-Method with Apache License 2.0 6 votes vote down vote up
def load_AE(codec_prefix, print_summary=False):

    saveFilePrefix = "models/AE_codec/" + codec_prefix + "_"

    decoder_model_filename = saveFilePrefix + "decoder.json"
    decoder_weight_filename = saveFilePrefix + "decoder.h5"

    if not os.path.isfile(decoder_model_filename):
        raise Exception("The file for decoder model does not exist:{}".format(decoder_model_filename))
    json_file = open(decoder_model_filename, 'r')
    decoder = model_from_json(json_file.read(), custom_objects={"tf": tf})
    json_file.close()

    if not os.path.isfile(decoder_weight_filename):
        raise Exception("The file for decoder weights does not exist:{}".format(decoder_weight_filename))
    decoder.load_weights(decoder_weight_filename)

    if print_summary:
        print("Decoder summaries")
        decoder.summary()

    return decoder 
Example #4
Source File: neural_network.py    From kits19.MIScnn with GNU General Public License v3.0 6 votes vote down vote up
def load(self, name):
        # Create model input path
        inpath_model = os.path.join(self.config["model_path"],
                                    name + ".model.json")
        inpath_weights = os.path.join(self.config["model_path"],
                                      name + ".weights.h5")
        # Load json and create model
        json_file = open(inpath_model, 'r')
        loaded_model_json = json_file.read()
        json_file.close()
        self.model = model_from_json(loaded_model_json)
        # Load weights into new model
        self.model.load_weights(inpath_weights)
        # Compile model
        self.model.compile(optimizer=Adam(lr=self.config["learninig_rate"]),
                           loss=tversky_loss,
                           metrics=self.metrics) 
Example #5
Source File: atari_wrappers.py    From sonic_contest with MIT License 6 votes vote down vote up
def __init__(self, env):
        """Warp frames to 84x84 as done in the Nature paper and later work."""
        gym.ObservationWrapper.__init__(self, env)
        self.width = 84
        self.height = 84
        self.observation_space = spaces.Box(low=0, high=255,
            shape=(self.height, self.width, 1), dtype=np.uint8)
        #print("Load Keras Model!!!")
        # Load Keras model
        #self.json_name = './retro-movies/architecture_level_classifier_v5.json'
        #self.weight_name = './retro-movies/model_weights_level_classifier_v5.h5'
        #self.levelcls_model = model_from_json(open(self.json_name).read())
        #self.levelcls_model.load_weights(self.weight_name, by_name=True)
        ##self.levelcls_model.load_weights(self.weight_name)
        #print("Done Loading Keras Model!!!")
        #self.mean_pixel = [103.939, 116.779, 123.68]
        #self.warmup = 1000
        #self.interval = 500
        #self.counter = 0
        #self.num_inference = 0
        #self.max_inference = 5
        self.level_pred = [] 
Example #6
Source File: punchline_extractor.py    From robotreviewer with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, architecture_path=None, weights_path=None):
        self.bc = None
        try: 
            self.bc = BertClient() 
        except:
            raise Exception("PunchlineExtractor: Cannot instantiate BertClient. Is it running???")

        # check if we're loading in a pre-trained model
        if architecture_path is not None:
            assert(weights_path is not None)
            
            with open(architecture_path) as model_arch:
                model_arch_str = model_arch.read()
                self.model = model_from_json(model_arch_str)

            self.model.load_weights(weights_path)
        else:
            self.build_model() 
Example #7
Source File: nn.py    From mljar-supervised with MIT License 6 votes vote down vote up
def __init__(self, params):
        super(NeuralNetworkAlgorithm, self).__init__(params)

        self.library_version = keras.__version__

        self.rounds = additional.get("one_step", 1)
        self.max_iters = additional.get("max_steps", 1)
        self.learner_params = {
            "dense_layers": params.get("dense_layers"),
            "dense_1_size": params.get("dense_1_size"),
            "dense_2_size": params.get("dense_2_size"),
            "dropout": params.get("dropout"),
            "learning_rate": params.get("learning_rate"),
            "momentum": params.get("momentum"),
            "decay": params.get("decay"),
        }
        self.model = None  # we need input data shape to construct model

        if "model_architecture_json" in params:
            self.model = model_from_json(
                json.loads(params.get("model_architecture_json"))
            )
            self.compile_model()

        logger.debug("NeuralNetworkAlgorithm __init__") 
Example #8
Source File: punchline_extractor.py    From robotreviewer with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, architecture_path=None, weights_path=None):
        self.bc = None
        try: 
            self.bc = BertClient() 
        except:
            raise Exception("PunchlineExtractor: Cannot instantiate BertClient. Is it running???")

        # check if we're loading in a pre-trained model
        if architecture_path is not None:
            assert(weights_path is not None)
            
            with open(architecture_path) as model_arch:
                model_arch_str = model_arch.read()
                self.model = model_from_json(model_arch_str)

            self.model.load_weights(weights_path)
        else:
            self.build_model() 
Example #9
Source File: q_learning_agent.py    From reversi_ai with MIT License 6 votes vote down vote up
def get_model(self, filename=None):
        """Given a filename, load that model file; otherwise, generate a new model."""
        model = None
        if filename:
            info('attempting to load model {}'.format(filename))
            try:
                model = model_from_json(open(filename).read())
            except FileNotFoundError:
                print('could not load file {}'.format(filename))
                quit()
            print('loaded model file {}'.format(filename))
        else:
            print('no model file loaded, generating new model.')
            size = self.reversi.size ** 2
            model = Sequential()
            model.add(Dense(HIDDEN_SIZE, activation='relu', input_dim=size))
            # model.add(Dense(HIDDEN_SIZE, activation='relu'))
            model.add(Dense(size))

        model.compile(loss='mse', optimizer=optimizer)
        return model 
Example #10
Source File: NNScore2.01.02.py    From DLSCORE with MIT License 6 votes vote down vote up
def getout(self):
        #get and denormalize output units
    
        for k in range(1,len(self.outno)+1):
            self.output[k] = self.deo[k][1] * self.units[self.outno[k]] + self.deo[k][2]
			
			
#def dlscore():
    # Load the model
#	with open("model.json", "r") as json_file:
#	    loaded_model = model_from_json(json_file.read())

	# Load weights
#	loaded_model.load_weights("model.h5")

	# Compile the model
#	loaded_model.compile(
#		loss='mean_squared_error',
#		optimizer=keras.optimizers.Adam(lr=0.001),
#		metrics=[metrics.MSE])
	
#	return loaded_model 
Example #11
Source File: pspnet-video.py    From PSPNet-Keras-tensorflow with MIT License 6 votes vote down vote up
def __init__(self, nb_classes, resnet_layers, input_shape, weights):
        """Instanciate a PSPNet."""
        self.input_shape = input_shape
        json_path = join("weights", "keras", weights + ".json")
        h5_path = join("weights", "keras", weights + ".h5")
        if isfile(json_path) and isfile(h5_path):
            print("Keras model & weights found, loading...")
            with open(json_path, 'r') as file_handle:
                self.model = model_from_json(file_handle.read())
            self.model.load_weights(h5_path)
        else:
            print("No Keras model & weights found, import from npy weights.")
            self.model = layers.build_pspnet(nb_classes=nb_classes,
                                             resnet_layers=resnet_layers,
                                             input_shape=self.input_shape)
            self.set_npy_weights(weights) 
Example #12
Source File: classifier.py    From Document-Classifier-LSTM with MIT License 6 votes vote down vote up
def load_model(stamp):
	"""
	"""

	json_file = open(stamp+'.json', 'r')
	loaded_model_json = json_file.read()
	json_file.close()
	model = model_from_json(loaded_model_json, {'AttentionWithContext': AttentionWithContext})

	model.load_weights(stamp+'.h5')
	print("Loaded model from disk")

	model.summary()


	adam = Adam(lr=0.001)
	model.compile(loss='binary_crossentropy',
		optimizer=adam,
		metrics=[f1_score])


	return model 
Example #13
Source File: keras_utils.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_model(json_path, weight_path, metrics=None, loss=None, optimizer=None, custom_objects=None, is_compile=True):
    with open(json_path, 'r') as f:
        model_json_string = json.load(f)
    model_json_dict = json.loads(model_json_string)
    model = model_from_json(model_json_string, custom_objects=custom_objects)
    model.load_weights(weight_path)

    if is_compile:
        if optimizer is None:
            optimizer = model_json_dict['optimizer']['name']

        if loss is None:
            loss = model_json_dict['loss']

        if metrics is None:
            model.compile(loss=loss, optimizer=optimizer)
        else:
            model.compile(loss=loss, optimizer=optimizer, metrics=metrics)

    return model 
Example #14
Source File: pspnet.py    From PSPNet-Keras-tensorflow with 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(file_handle.read())
                self.model.load_weights(h5_path)
            else:
                print("No Keras model & weights found, import from npy weights.")
                self.model = layers.build_pspnet(nb_classes=nb_classes,
                                                 resnet_layers=resnet_layers,
                                                 input_shape=self.input_shape)
                self.set_npy_weights(weights)
        else:
            print('Load pre-trained weights')
            self.model = load_model(weights) 
Example #15
Source File: gcn.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_reconst_from_embed(self, embed, node_l=None, filesuffix=None):
        if filesuffix is None:
            if node_l is not None:
                return self._decoder.predict(
                    embed,
                    batch_size=self._n_batch)[:, node_l]
            else:
                return self._decoder.predict(embed, batch_size=self._n_batch)
        else:
            try:
                decoder = model_from_json(
                    open('decoder_model_' + filesuffix + '.json').read()
                )
            except:
                print('Error reading file: {0}. Cannot load previous model'.format('decoder_model_'+filesuffix+'.json'))
                exit()
            try:
                decoder.load_weights('decoder_weights_' + filesuffix + '.hdf5')
            except:
                print('Error reading file: {0}. Cannot load previous weights'.format('decoder_weights_'+filesuffix+'.hdf5'))
                exit()
            if node_l is not None:
                return decoder.predict(embed, batch_size=self._n_batch)[:, node_l]
            else:
                return decoder.predict(embed, batch_size=self._n_batch) 
Example #16
Source File: vae.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_reconst_from_embed(self, embed, node_l=None, filesuffix=None):
        if filesuffix is None:
            if node_l is not None:
                return self._decoder.predict(
                    embed,
                    batch_size=self._n_batch
                )[:, node_l]
            else:
                return self._decoder.predict(embed, batch_size=self._n_batch)
        else:
            try:
                decoder = model_from_json(
                    open('decoder_model_' + filesuffix + '.json').read())
            except:
                print('Error reading file: {0}. Cannot load previous model'.format('decoder_model_'+filesuffix+'.json'))
                exit()
            try:
                decoder.load_weights('decoder_weights_'+filesuffix+'.hdf5')
            except:
                print('Error reading file: {0}. Cannot load previous weights'.format('decoder_weights_'+filesuffix+'.hdf5'))
                exit()
            if node_l is not None:
                return decoder.predict(embed, batch_size=self._n_batch)[:, node_l]
            else:
                return decoder.predict(embed, batch_size=self._n_batch) 
Example #17
Source File: sdne.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_reconst_from_embed(self, embed, node_l=None, filesuffix=None):
        if filesuffix is None:
            if node_l is not None:
                return self._decoder.predict(
                    embed,
                    batch_size=self._n_batch)[:, node_l]
            else:
                return self._decoder.predict(embed, batch_size=self._n_batch)
        else:
            try:
                decoder = model_from_json(
                    open('decoder_model_' + filesuffix + '.json').read()
                )
            except:
                print('Error reading file: {0}. Cannot load previous model'.format('decoder_model_'+filesuffix+'.json'))
                exit()
            try:
                decoder.load_weights('decoder_weights_' + filesuffix + '.hdf5')
            except:
                print('Error reading file: {0}. Cannot load previous weights'.format('decoder_weights_'+filesuffix+'.hdf5'))
                exit()
            if node_l is not None:
                return decoder.predict(embed, batch_size=self._n_batch)[:, node_l]
            else:
                return decoder.predict(embed, batch_size=self._n_batch) 
Example #18
Source File: ae_static.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_reconst_from_embed(self, embed, node_l=None, filesuffix=None):
        if filesuffix is None:
            if node_l is not None:
                return self._decoder.predict(
                    embed,
                    batch_size=self._n_batch
                )[:, node_l]
            else:
                return self._decoder.predict(embed, batch_size=self._n_batch)
        else:
            try:
                decoder = model_from_json(
                    open('decoder_model_' + filesuffix + '.json').read())
            except:
                print('Error reading file: {0}. Cannot load previous model'.format('decoder_model_'+filesuffix+'.json'))
                exit()
            try:
                decoder.load_weights('decoder_weights_'+filesuffix+'.hdf5')
            except:
                print('Error reading file: {0}. Cannot load previous weights'.format('decoder_weights_'+filesuffix+'.hdf5'))
                exit()
            if node_l is not None:
                return decoder.predict(embed, batch_size=self._n_batch)[:, node_l]
            else:
                return decoder.predict(embed, batch_size=self._n_batch) 
Example #19
Source File: pipelinecomponents.py    From sia-cog with MIT License 6 votes vote down vote up
def model_predict(X, pipeline):
    if model_type == "mlp":
        json_file = open(projectfolder + '/model.json', 'r')
        loaded_model_json = json_file.read()
        json_file.close()
        model = model_from_json(loaded_model_json)
        model.load_weights(projectfolder + "/weights.hdf5")
        model.compile(loss=pipeline['options']['loss'], optimizer=pipeline['options']['optimizer'],
                         metrics=pipeline['options']['scoring'])
        if type(X) is pandas.DataFrame:
            X = X.values
        Y = model.predict(X)
    else:
        picklefile = projectfolder + "/model.out"
        with open(picklefile, "rb") as f:
            model = pickle.load(f)
        Y = model.predict(X)

    return Y 
Example #20
Source File: NNScore2.01.03.py    From DLSCORE with MIT License 6 votes vote down vote up
def getout(self):
        #get and denormalize output units
    
        for k in range(1,len(self.outno)+1):
            self.output[k] = self.deo[k][1] * self.units[self.outno[k]] + self.deo[k][2]
			
			
#def dlscore():
    # Load the model
#	with open("model.json", "r") as json_file:
#	    loaded_model = model_from_json(json_file.read())

	# Load weights
#	loaded_model.load_weights("model.h5")

	# Compile the model
#	loaded_model.compile(
#		loss='mean_squared_error',
#		optimizer=keras.optimizers.Adam(lr=0.001),
#		metrics=[metrics.MSE])
	
#	return loaded_model 
Example #21
Source File: cnn_major_shallow.py    From Facial-Expression-Recognition with MIT License 5 votes vote down vote up
def baseline_model_saved():
    #load json and create model
    json_file = open('model_2layer_2_2_pool.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    model = model_from_json(loaded_model_json)
    #load weights from h5 file
    model.load_weights("model_2layer_2_2_pool.h5")
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[categorical_accuracy])
    return model 
Example #22
Source File: neural_network.py    From songoku with MIT License 5 votes vote down vote up
def __init__(self):
        # Loads the model into memory
        with open('258epochs_model_7.json','r') as f:
            model_json = f.read()

        self.model = model_from_json(model_json)
        self.model.load_weights('258epochs_model_7.h5')

        print('Neural Network loaded!') 
Example #23
Source File: utils.py    From rpg_public_dronet with MIT License 5 votes vote down vote up
def jsonToModel(json_model_path):
    with open(json_model_path, 'r') as json_file:
        loaded_model_json = json_file.read()

    model = model_from_json(loaded_model_json)

    return model 
Example #24
Source File: cnn_major.py    From Facial-Expression-Recognition with MIT License 5 votes vote down vote up
def baseline_model_saved():
    #load json and create model
    json_file = open('model_4layer_2_2_pool.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    model = model_from_json(loaded_model_json)
    #load weights from h5 file
    model.load_weights("model_4layer_2_2_pool.h5")
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[categorical_accuracy])
    return model 
Example #25
Source File: dlscore.py    From DLSCORE with MIT License 5 votes vote down vote up
def dl_nets(nb_nets):
    """ Yields feed forward nerual nets from the network directory """
    # Read the networks
    with open(os.path.join(networks_dir, "sorted_models.pickle"), 'rb') as f:
        model_files = pickle.load(f)
    with open(os.path.join(networks_dir, "sorted_weights.pickle"), 'rb') as f:
        weight_files = pickle.load(f)
    
    assert(len(model_files) == len(weight_files)),         'Number of model files and the weight files are not the same.'
    for i, (model, weight) in enumerate(zip(model_files, weight_files)):
        if i==nb_nets:
            break
        # Load the network
        with open(os.path.join(networks_dir, model), 'r') as json_file:
            loaded_model = model_from_json(json_file.read())
            
        # Load the weights
        loaded_model.load_weights(os.path.join(networks_dir, weight))
        
        # Compile the network
        #loaded_model.compile(
        #    loss='mean_squared_error',
        #    optimizer=keras.optimizers.Adam(lr=0.001),
        #    metrics=[metrics.mse])
        
        yield loaded_model 
Example #26
Source File: utils.py    From rpg_public_dronet with MIT License 5 votes vote down vote up
def jsonToModel(json_model_path):
    """
    Serialize json into model.
    """
    with open(json_model_path, 'r') as json_file:
        loaded_model_json = json_file.read()

    model = model_from_json(loaded_model_json)
    return model 
Example #27
Source File: NNScore2.01.02.py    From DLSCORE with MIT License 5 votes vote down vote up
def dl_nets():
    """ Yields new set of deep learning based networks """
    # Read the networks
    networks = sorted(glob.glob("dl_networks_02/*.json"))
    weights = sorted(glob.glob("dl_networks_02/*.h5"))
    
    for net, weight in zip(networks, weights):
        # Load the network
        with open(net, 'r') as json_file:
            loaded_model = model_from_json(json_file.read())
            
        # Load weights
        loaded_model.load_weights(weight)
        
        # Compile the network
        #loaded_model.compile(
        #    loss='mean_squared_error',
        #    optimizer=keras.optimizers.Adam(lr=0.001),
        #    metrics=[metrics.mse])
        
        yield loaded_model


#def sensoring(test_x, train_y, pred):
#    """ Sensor the predicted data to get rid of outliers """
#    mn = np.min(train_y)
#    mx = np.max(train_y)

#    pred = np.minimum(pred, mx)
#    pred = np.maximum(pred, mn)
    
#    return pred 
Example #28
Source File: Q_Learning_Agent.py    From rf_helicopter with MIT License 5 votes vote down vote up
def load_model(self, name):
        """
        load Keras model from JSON and weights
        :param name: str
        :return: None (Loads to Self)
        """
        from keras.models import model_from_json
        self.model = model_from_json(
            open(
                self.directory +
                name +
                '_architecture.json').read())
        self.model.load_weights(self.directory + name + '_weights.h5')
        logging.info('Model Loaded!') 
Example #29
Source File: emotion.py    From libfaceid with MIT License 5 votes vote down vote up
def __init__(self, path):
        self._classifier = model_from_json(open(path + 'emotion_deploy.json', "r").read())
        self._classifier.load_weights(path + 'emotion_net.h5')
        self._selection = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'] 
Example #30
Source File: load_model.py    From autonomio with MIT License 5 votes vote down vote up
def load_model(saved_model):

    '''Load Model

    WHAT: Loads a saved model and makes it available for
    prediction use by predictor().

    '''

    json_file = open(saved_model + ".json", 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights(saved_model + '.h5')

    f = open(saved_model+".x", 'r')
    temp = f.read()
    try:
        X = map(int, temp.split()[:-1])
    except ValueError:
        X = temp.split()[:-1]

    try:
        flatten = float(temp.split()[-1])

    except ValueError:
        flatten = temp.split()[-1]

    f.close()

    if type(X) == list and len(X) == 1:
        X = X[0]

    return loaded_model, X, flatten