本文整理匯總了Python中tensorflow.keras.models方法的典型用法代碼示例。如果您正苦於以下問題:Python keras.models方法的具體用法?Python keras.models怎麽用?Python keras.models使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tensorflow.keras
的用法示例。
在下文中一共展示了keras.models方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: compute_backbone_shapes
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def compute_backbone_shapes(config, image_shape):
"""Computes the width and height of each stage of the backbone network.
Returns:
[N, (height, width)]. Where N is the number of stages
"""
if callable(config.BACKBONE):
return config.COMPUTE_BACKBONE_SHAPE(image_shape)
# Currently supports ResNet only
assert config.BACKBONE in ["resnet50", "resnet101"]
return np.array(
[[int(math.ceil(image_shape[0] / stride)),
int(math.ceil(image_shape[1] / stride))]
for stride in config.BACKBONE_STRIDES])
############################################################
# Resnet Graph
############################################################
# Code adopted from:
# https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
示例2: get_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def get_kwargs():
return {
'backend': tfkeras.backend,
'layers': tfkeras.layers,
'models': tfkeras.models,
'utils': tfkeras.utils,
}
示例3: get_submodules_from_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def get_submodules_from_kwargs(kwargs):
backend = kwargs.get('backend', _KERAS_BACKEND)
layers = kwargs.get('layers', _KERAS_LAYERS)
models = kwargs.get('models', _KERAS_MODELS)
utils = kwargs.get('utils', _KERAS_UTILS)
for key in kwargs.keys():
if key not in ['backend', 'layers', 'models', 'utils']:
raise TypeError('Invalid keyword argument: %s', key)
return backend, layers, models, utils
示例4: inject_keras_modules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def inject_keras_modules(func):
import keras
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs['backend'] = keras.backend
kwargs['layers'] = keras.layers
kwargs['models'] = keras.models
kwargs['utils'] = keras.utils
return func(*args, **kwargs)
return wrapper
示例5: inject_tfkeras_modules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def inject_tfkeras_modules(func):
import tensorflow.keras as tfkeras
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs['backend'] = tfkeras.backend
kwargs['layers'] = tfkeras.layers
kwargs['models'] = tfkeras.models
kwargs['utils'] = tfkeras.utils
return func(*args, **kwargs)
return wrapper
示例6: get_imagenet_weights
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def get_imagenet_weights(self):
"""Downloads ImageNet trained weights from Keras.
Returns path to weights file.
"""
from keras.utils.data_utils import get_file
TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/'\
'releases/download/v0.2/'\
'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
weights_path = get_file('resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',
TF_WEIGHTS_PATH_NO_TOP,
cache_subdir='models',
md5_hash='a268eb855778b3df3c7506639542a6af')
return weights_path
示例7: summary
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def summary(self, *args, **kwargs):
"""Override summary() to display summaries of both, the wrapper
and inner models."""
super(ParallelModel, self).summary(*args, **kwargs)
self.inner_model.summary(*args, **kwargs)
示例8: decode_predictions
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def decode_predictions(preds, top=5, **kwargs):
"""Decodes the prediction of an ImageNet model.
# Arguments
preds: Numpy tensor encoding a batch of predictions.
top: Integer, how many top-guesses to return.
# Returns
A list of lists of top class prediction tuples
`(class_name, class_description, score)`.
One list of tuples per sample in batch input.
# Raises
ValueError: In case of invalid shape of the `pred` array
(must be 2D).
"""
global CLASS_INDEX
if len(preds.shape) != 2 or preds.shape[1] != 1000:
raise ValueError('`decode_predictions` expects '
'a batch of predictions '
'(i.e. a 2D array of shape (samples, 1000)). '
'Found array with shape: ' + str(preds.shape))
if CLASS_INDEX is None:
fpath = keras_utils.get_file(
'imagenet_class_index.json',
CLASS_INDEX_PATH,
cache_subdir='models',
file_hash='c2c37ea517e94d9795004a39431a14cb')
with open(fpath) as f:
CLASS_INDEX = json.load(f)
results = []
for pred in preds:
top_indices = pred.argsort()[-top:][::-1]
result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices]
result.sort(key=lambda x: x[2], reverse=True)
results.append(result)
return results
示例9: inject_global_submodules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def inject_global_submodules(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs['backend'] = _KERAS_BACKEND
kwargs['layers'] = _KERAS_LAYERS
kwargs['models'] = _KERAS_MODELS
kwargs['utils'] = _KERAS_UTILS
return func(*args, **kwargs)
return wrapper
示例10: filter_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def filter_kwargs(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
new_kwargs = {k: v for k, v in kwargs.items() if k in ['backend', 'layers', 'models', 'utils']}
return func(*args, **new_kwargs)
return wrapper
示例11: get_preprocessing
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def get_preprocessing(name):
preprocess_input = Backbones.get_preprocessing(name)
# add bakcend, models, layers, utils submodules in kwargs
preprocess_input = inject_global_submodules(preprocess_input)
# delete other kwargs
# keras-applications preprocessing raise an error if something
# except `backend`, `layers`, `models`, `utils` passed in kwargs
preprocess_input = filter_kwargs(preprocess_input)
return preprocess_input
示例12: load_model
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def load_model(input_model_path, input_json_path=None, input_yaml_path=None):
if not Path(input_model_path).exists():
raise FileNotFoundError(
'Model file `{}` does not exist.'.format(input_model_path))
try:
model = keras.models.load_model(input_model_path)
return model
except FileNotFoundError as err:
logging.error('Input mode file (%s) does not exist.', FLAGS.input_model)
raise err
except ValueError as wrong_file_err:
if input_json_path:
if not Path(input_json_path).exists():
raise FileNotFoundError(
'Model description json file `{}` does not exist.'.format(
input_json_path))
try:
model = model_from_json(open(str(input_json_path)).read())
model.load_weights(input_model_path)
return model
except Exception as err:
logging.error("Couldn't load model from json.")
raise err
elif input_yaml_path:
if not Path(input_yaml_path).exists():
raise FileNotFoundError(
'Model description yaml file `{}` does not exist.'.format(
input_yaml_path))
try:
model = model_from_yaml(open(str(input_yaml_path)).read())
model.load_weights(input_model_path)
return model
except Exception as err:
logging.error("Couldn't load model from yaml.")
raise err
else:
logging.error(
'Input file specified only holds the weights, and not '
'the model definition. Save the model using '
'model.save(filename.h5) which will contain the network '
'architecture as well as its weights. '
'If the model is saved using the '
'model.save_weights(filename) function, either '
'input_model_json or input_model_yaml flags should be set to '
'to import the network architecture prior to loading the '
'weights. \n'
'Check the keras documentation for more details '
'(https://keras.io/getting-started/faq/)')
raise wrong_file_err
示例13: set_framework
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import models [as 別名]
def set_framework(name):
"""Set framework for Segmentation Models
Args:
name (str): one of ``keras``, ``tf.keras``, case insensitive.
Raises:
ValueError: in case of incorrect framework name.
ImportError: in case framework is not installed.
"""
name = name.lower()
if name == _KERAS_FRAMEWORK_NAME:
import keras
import efficientnet.keras # init custom objects
elif name == _TF_KERAS_FRAMEWORK_NAME:
from tensorflow import keras
import efficientnet.tfkeras # init custom objects
else:
raise ValueError('Not correct module name `{}`, use `{}` or `{}`'.format(
name, _KERAS_FRAMEWORK_NAME, _TF_KERAS_FRAMEWORK_NAME))
global _KERAS_BACKEND, _KERAS_LAYERS, _KERAS_MODELS
global _KERAS_UTILS, _KERAS_LOSSES, _KERAS_FRAMEWORK
_KERAS_FRAMEWORK = name
_KERAS_BACKEND = keras.backend
_KERAS_LAYERS = keras.layers
_KERAS_MODELS = keras.models
_KERAS_UTILS = keras.utils
_KERAS_LOSSES = keras.losses
# allow losses/metrics get keras submodules
base.KerasObject.set_submodules(
backend=keras.backend,
layers=keras.layers,
models=keras.models,
utils=keras.utils,
)
# set default framework