本文整理汇总了Python中keras.io方法的典型用法代码示例。如果您正苦于以下问题:Python keras.io方法的具体用法?Python keras.io怎么用?Python keras.io使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras
的用法示例。
在下文中一共展示了keras.io方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import keras [as 别名]
# 或者: from keras import io [as 别名]
def __init__(self,
input_dim,
quantiles,
depth=3,
width=128,
activation="relu",
ensemble_size=1,
**kwargs):
"""
Create a QRNN model.
Arguments:
input_dim(int): The dimension of the measurement space, i.e. the number
of elements in a single measurement vector y
quantiles(np.array): 1D-array containing the quantiles to estimate of
the posterior distribution. Given as fractions
within the range [0, 1].
depth(int): The number of hidden layers in the neural network to
use for the regression. Default is 3, i.e. three hidden
plus input and output layer.
width(int): The number of neurons in each hidden layer.
activation(str): The name of the activation functions to use. Default
is "relu", for rectified linear unit. See
`this <https://keras.io/activations>`_ link for
available functions.
**kwargs: Additional keyword arguments are passed to the constructor
call `keras.layers.Dense` of the hidden layers, which can
for example be used to add regularization. For more info consult
`Keras documentation. <https://keras.io/layers/core/#dense>`_
"""
self.input_dim = input_dim
self.quantiles = np.array(quantiles)
self.depth = depth
self.width = width
self.activation = activation
model = Sequential()
if depth == 0:
model.add(Dense(input_dim=input_dim,
units=len(quantiles),
activation=None))
else:
model.add(Dense(input_dim=input_dim,
units=width,
activation=activation))
for i in range(depth - 2):
model.add(Dense(units=width,
activation=activation,
**kwargs))
model.add(Dense(units=len(quantiles), activation=None))
self.models = [clone_model(model) for i in range(ensemble_size)]
示例2: keras_reproducible
# 需要导入模块: import keras [as 别名]
# 或者: from keras import io [as 别名]
def keras_reproducible(seed=1234, verbose=0, TF_CPP_MIN_LOG_LEVEL="3"):
"""
https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development
"""
import random
import pkg_resources
import os
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = "0" # might need to do this outside the script
if verbose == 0:
os.environ[
"TF_CPP_MIN_LOG_LEVEL"
] = TF_CPP_MIN_LOG_LEVEL # 2 will print warnings
try:
import tensorflow
except ImportError:
raise ImportError("Missing required package 'tensorflow'")
# Use the TF 1.x API
if pkg_resources.get_distribution("tensorflow").version.startswith("1."):
tf = tensorflow
else:
tf = tensorflow.compat.v1
if verbose == 0:
# https://github.com/tensorflow/tensorflow/issues/27023
try:
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
except ImportError:
try:
from tensorflow.python.util import module_wrapper as deprecation
except ImportError:
from tensorflow.python.util import deprecation_wrapper as deprecation
deprecation._PER_MODULE_WARNING_LIMIT = 0
# this was deprecated in 1.15 (maybe earlier)
tensorflow.compat.v1.logging.set_verbosity(tensorflow.compat.v1.logging.ERROR)
ConfigProto = tf.ConfigProto
session_conf = tf.ConfigProto(
intra_op_parallelism_threads=1, inter_op_parallelism_threads=1
)
with capture_all(): # doesn't have quiet option
try:
from tensorflow.python.keras import backend as K
except ImportError:
raise ImportError("Missing required module 'keras'")
tf.set_random_seed(seed)
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)
示例3: load_model
# 需要导入模块: import keras [as 别名]
# 或者: from keras import io [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