本文整理汇总了Python中tensorflow.keras.models.load_model方法的典型用法代码示例。如果您正苦于以下问题:Python models.load_model方法的具体用法?Python models.load_model怎么用?Python models.load_model使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras.models
的用法示例。
在下文中一共展示了models.load_model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def __init__(self):
config = configparser.ConfigParser()
config.read('./config/config.ini')
self.log_Image = ''
self.LogNames = ''
if config.has_option('Analog_Counter', 'LogImageLocation'):
self.log_Image = config['Analog_Counter']['LogImageLocation']
if config.has_option('Analog_Counter', 'LogNames'):
zw_LogNames = config.get('Analog_Counter', 'LogNames').split(',')
self.LogNames = []
for nm in zw_LogNames:
self.LogNames.append(nm.strip())
else:
self.LogNames = ''
else:
self.log_Image = ''
self.model_file = config['Analog_Counter']['Modelfile']
self.CheckAndLoadDefaultConfig()
self.model = load_model(self.model_file)
示例2: _load_model
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def _load_model(self, name: str, reload: bool = False) -> Model:
if name in self.models and not reload:
return self.models[name]
model_dir = os.path.join(self._models_dir, name)
assert os.path.isdir(model_dir), 'The model {} does not exist'.format(name)
model = load_model(model_dir)
model.input_labels = []
model.output_labels = []
labels_file = os.path.join(model_dir, 'labels.json')
if os.path.isfile(labels_file):
with open(labels_file, 'r') as f:
labels = json.load(f)
if 'input' in labels:
model.input_labels = labels['input']
if 'output' in labels:
model.output_labels = labels['output']
return model
示例3: load_disc_gen
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def load_disc_gen():
""" load models for training. Separate from 'load_model'.
Returns Discriminator, Generator"""
home_dir = get_directory()
generators = glob.glob(os.path.join(home_dir, "models/checkpoints/generator-*.h5"))
discriminators = glob.glob(
os.path.join(home_dir, "models/checkpoints/discriminator-*.h5")
)
try:
gen_model_file = max(generators, key=os.path.getctime)
gen_model = load_model(gen_model_file)
except ValueError:
gen_model = generator()
try:
disc_model_file = max(discriminators, key=os.path.getctime)
disc_model = load_model(disc_model_file)
except ValueError:
disc_model = discriminator()
return disc_model, gen_model
示例4: infer
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def infer(img):
"""inference function, accepts an abstract image file return generated image"""
home_dir = get_directory()
# load model
backend.clear_session()
gen_model = load_model(home_dir + "/models/generator_model.h5", compile=False)
img = np.array(Image.open(img))
img = norm_data([img])
s_time = time.time()
result = gen_model.predict(img[0].reshape(1, 256, 256, 3))
f_time = time.time()
logger.info(
"\033[92m"
+ "[INFO] "
+ "\033[0m"
+ "Inference done in: {:2.3f} seconds".format(f_time - s_time)
)
# transform result from normalized to absolute values and convert to image object
result = Image.fromarray(reverse_norm(result[0]), "RGB")
# for debugging, uncomment the line below to inspect the generated image locally
# result.save("generted_img.jpg", "JPEG")
# convert image to bytes object to send it to the client
binary_buffer = io.BytesIO()
result.save(binary_buffer, format="JPEG")
return b2a_base64(binary_buffer.getvalue())
示例5: load_unet
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def load_unet(checkpoint=False):
"""
Return unet model. Only for use in local training.
checkpoint: True to return the latest ckeckpoint in models/,
False to return a model named 'unet.h5' in models/
"""
home_dir = get_directory()
unet_names = glob.glob(os.path.join(home_dir, "models/checkpoints/unet-*.h5"))
if checkpoint:
try:
unet_file = max(unet_names, key=os.path.getctime)
unet_model = load_model(unet_file)
except ValueError:
print("Could not load checkpoint. Returning new model instead.")
unet_model = unet_model()
else:
try:
unet_model = load_model(os.path.join(home_dir, "models/unet.h5"))
except ValueError:
print("Could not load from 'models/unet.h5'. Returning new model instead.")
unet_model = unet_model()
return unet_model
示例6: from_file
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def from_file(cls, filename: str) -> 'GraphModel':
"""
Class method to load model from
filename for keras model
filename.json for additional converters
Args:
filename: (str) model file name
Returns
GraphModel
"""
configs = loadfn(filename + '.json')
from tensorflow.keras.models import load_model
from megnet.layers import _CUSTOM_OBJECTS
model = load_model(filename, custom_objects=_CUSTOM_OBJECTS)
configs.update({'model': model})
return GraphModel(**configs)
示例7: validate_yolo_model
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def validate_yolo_model(model_path, image_file, anchors, class_names, model_image_size, loop_count):
custom_object_dict = get_custom_objects()
model = load_model(model_path, compile=False, custom_objects=custom_object_dict)
img = Image.open(image_file)
image = np.array(img, dtype='uint8')
image_data = preprocess_image(img, model_image_size)
#origin image shape, in (height, width) format
image_shape = tuple(reversed(img.size))
# predict once first to bypass the model building time
model.predict([image_data])
start = time.time()
for i in range(loop_count):
prediction = model.predict([image_data])
end = time.time()
print("Average Inference time: {:.8f}ms".format((end - start) * 1000 /loop_count))
if type(prediction) is not list:
prediction = [prediction]
prediction.sort(key=lambda x: len(x[0]))
handle_prediction(prediction, image_file, image, image_shape, anchors, class_names, model_image_size)
return
示例8: onnx_convert_with_savedmodel
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def onnx_convert_with_savedmodel(keras_model_file, output_file, op_set):
# only available for TF 2.x
if not tf.__version__.startswith('2'):
raise ValueError('savedmodel convert only support in TF 2.x env')
custom_object_dict = get_custom_objects()
model = load_model(keras_model_file, custom_objects=custom_object_dict)
# export to saved model
model.save('tmp_savedmodel', save_format='tf')
# use tf2onnx to convert to onnx model
cmd = 'python -m tf2onnx.convert --saved-model tmp_savedmodel --output {} --opset {}'.format(output_file, op_set)
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
# clean saved model
shutil.rmtree('tmp_savedmodel')
示例9: predict
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def predict(self, input_table_file, generic_opinion_terms):
"""Predict classification class according to model.
Args:
input_table_file: feature(X) and labels(Y) table file
generic_opinion_terms: generic opinion terms file name
Returns:
final_concat_opinion_lex: reranked_lex conctenated with generic lex
"""
x, terms, polarities = self.load_terms_and_generate_features(input_table_file)
model = load_model(self.rerank_model_path)
reranked_lexicon = model.predict(x, verbose=0)
reranked_lex = {}
for i, prediction in enumerate(reranked_lexicon):
if not np.isnan(prediction[0]) and prediction[0] > self.PREDICTION_THRESHOLD:
reranked_lex[terms[i]] = (prediction[0], polarities[terms[i]])
final_concat_opinion_lex = self._generate_concat_reranked_lex(
reranked_lex, generic_opinion_terms
)
return final_concat_opinion_lex
示例10: __setstate__
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def __setstate__(self, state):
if "model" in state:
with h5py.File(state["model"], compression="lzf", mode="r") as h5:
state["model"] = load_model(h5, compile=False)
if "history" in state:
state["model"].__dict__["history"] = state.pop("history")
self.__dict__ = state
return self
示例11: _load_model_by_path
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def _load_model_by_path(self, model_path, weights_only=True):
try:
if weights_only:
model = self._build_model()
model.load_weights(model_path)
else:
model = load_model(model_path)
except FileNotFoundError:
model = None
return model
示例12: __init__
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def __init__(self, model_path,
config_path,
train=False,
train_file_path=None,
vector_path=None):
self.model_path = model_path
self.config_path = config_path
if not train:
assert config_path is not None, 'The config path cannot be None.'
config = load_config(self.config_path)
if not config:
(self.word_index, self.max_len, self.embeddings) = config
self.model = load_model(self.model_path, self.build_model())
if not self.model:
print('The model cannot be loaded:', self.model_path)
else:
self.vector_path = vector_path
self.train_file_path = train_file_path
self.x_train, self.y_train, self.x_test, self.y_test, self.word_index, self.max_index = self.load_data()
self.max_len = self.x_train.shape[1]
config = load_config(self.config_path)
if not config:
self.embeddings = load_bin_word2vec(self.word_index, self.vector_path, self.max_index)
save_config((self.word_index, self.max_len, self.embeddings), self.config_path)
else:
(_, _, self.embeddings) = config
self.model = self.train()
save_model(self.model, self.model_path)
# 全连接的一个简单的网络, 仅用来作为基类测试代码通过,速度快, 但是分类效果特别差
示例13: run
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def run(self):
if self.args.type == "ml":
X = make_dataset_ml(self.args)
pipe = load(self.args.model)
pred = get_genres(pipe.predict(X)[0], self.genres)
print("{} is a {} song".format(self.args.song, pred))
else:
X = make_dataset_dl(self.args)
model = load_model(self.args.model)
preds = model.predict(X)
votes = majority_voting(preds, self.genres)
print("{} is a {} song".format(self.args.song, votes[0][0]))
print("most likely genres are: {}".format(votes[:3]))
示例14: load_network
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def load_network(self, path, name=None, ext="h5"):
# nothing has changed
path_model, path_target_model = self._get_path_model(path, name)
self.model = load_model('{}.{}'.format(path_model, ext))
self.target_model = load_model('{}.{}'.format(path_target_model, ext))
print("Succesfully loaded network.")
示例15: __init__
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import load_model [as 别名]
def __init__(self):
config = configparser.ConfigParser()
config.read('./config/config.ini')
self.log_Image = ''
self.LogNames = ''
self.model_file = config['Digital_Digit']['Modelfile']
if config.has_option('Digital_Digit', 'LogImageLocation'):
self.log_Image = config['Digital_Digit']['LogImageLocation']
self.CheckAndLoadDefaultConfig()
if config.has_option('Digital_Digit', 'LogImageLocation'):
if (os.path.exists(self.log_Image)):
for i in range(10):
pfad = self.log_Image + '/' + str(i)
if not os.path.exists(pfad):
os.makedirs(pfad)
pfad = self.log_Image + '/NaN'
if not os.path.exists(pfad):
os.makedirs(pfad)
if config.has_option('Digital_Digit', 'LogNames'):
zw_LogNames = config.get('Digital_Digit', 'LogNames').split(',')
self.LogNames = []
for nm in zw_LogNames:
self.LogNames.append(nm.strip())
else:
self.LogNames = ''
else:
self.log_Image = ''
self.model_file = config['Digital_Digit']['Modelfile']
self.model = load_model(self.model_file)