本文整理汇总了Python中keras.models.model_from_json方法的典型用法代码示例。如果您正苦于以下问题:Python models.model_from_json方法的具体用法?Python models.model_from_json怎么用?Python models.model_from_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.models
的用法示例。
在下文中一共展示了models.model_from_json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例2: load_model
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例3: load_model
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例4: load
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例5: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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()
示例6: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例7: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例8: get_reconst_from_embed
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例9: get_reconst_from_embed
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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)
示例10: model_predict
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例11: get_model
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例12: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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 = []
示例13: load_AE
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例14: getout
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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
示例15: __init__
# 需要导入模块: from keras import models [as 别名]
# 或者: from keras.models import model_from_json [as 别名]
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__")