本文整理匯總了Python中tensorflow.keras.utils方法的典型用法代碼示例。如果您正苦於以下問題:Python keras.utils方法的具體用法?Python keras.utils怎麽用?Python keras.utils使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tensorflow.keras
的用法示例。
在下文中一共展示了keras.utils方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_ApogeeKplerEchelle
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def test_ApogeeKplerEchelle(self):
"""
Test ApogeeKplerEchelle models
- training, testing
"""
# Data preparation, keep the data size large (>800 data points to prevent issues)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y_train = utils.to_categorical(y_train, 10)
y_test = utils.to_categorical(y_test, 10)
# To convert to desirable type
y_train = y_train.astype(np.float32)
y_test = y_test.astype(np.float32)
x_train = x_train.astype(np.float32)
x_test = x_test.astype(np.float32)
print("======ApogeeKplerEchelle======")
apokasc_nn = ApogeeKplerEchelle()
apokasc_nn.max_epochs = 2
apokasc_nn.dropout_rate = 0.
apokasc_nn.input_norm_mode = {'input': 255, 'aux': 0}
apokasc_nn.labels_norm_mode = 0
apokasc_nn.task = 'classification'
apokasc_nn.callbacks = ErrorOnNaN()
apokasc_nn.train({'input': x_train, 'aux': y_train}, {'output': y_train})
prediction = apokasc_nn.test({'input': x_train, 'aux': y_train})
# we ave the answer as aux input so the prediction should be near perfect
total_num = y_train.shape[0]
assert np.sum((prediction>0.5) == (y_train>0.5)) > total_num * 0.99
apokasc_nn.save(name='apokasc_nn')
apokasc_nn_reloaded = load_folder('apokasc_nn')
prediction_reloaded = apokasc_nn_reloaded.test({'input': x_train, 'aux': y_train})
np.testing.assert_array_equal(prediction, prediction_reloaded)
示例2: test_mnist
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def test_mnist(self):
# create model instance
mnist_test = Cifar10CNN()
mnist_test.max_epochs = 1
mnist_test.callbacks = ErrorOnNaN()
mnist_test.train(x_train, y_train)
output_shape = mnist_test.output_shape
pred = mnist_test.test(x_test)
test_num = y_test.shape[0]
assert (np.sum(np.argmax(pred, axis=1) == y_test)) / test_num > 0.9 # assert accurancy
mnist_test.evaluate(x_test, utils.to_categorical(y_test, 10))
# create model instance for binary classification
mnist_test = Cifar10CNN()
mnist_test.max_epochs = 2
mnist_test.task = 'binary_classification'
mnist_test.train(x_train, y_train.astype(bool))
prediction = mnist_test.test(x_test)
assert (np.sum(np.argmax(prediction, axis=1) == y_test)) / test_num > 0.9 # assert accuracy
mnist_test.save('mnist_test')
mnist_reloaded = load_folder("mnist_test")
prediction_loaded = mnist_reloaded.test(x_test)
eval_result = mnist_reloaded.evaluate(x_test, utils.to_categorical(y_test, 10))
# Cifar10_CNN without dropout is deterministic
np.testing.assert_array_equal(prediction, prediction_loaded)
# test verbose metrics
mnist_reloaded.metrics = ['accuracy']
mnist_reloaded.compile()
mnist_test.save('mnist_test_accuracy')
mnist_reloaded_again = load_folder("mnist_test_accuracy")
# test with astype boolean deliberately
eval_result_again = mnist_reloaded_again.evaluate(x_test, utils.to_categorical(y_test, 10).astype(bool))
# assert saving again wont affect the model
self.assertAlmostEqual(eval_result_again['loss'], eval_result['loss'], places=3)
示例3: test_bayesian_mnist
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def test_bayesian_mnist(self):
import pylab as plt
# Create a astroNN neural network instance and set the basic parameter
net = MNIST_BCNN()
net.task = 'classification'
net.callbacks = ErrorOnNaN()
net.max_epochs = 1
# Train the neural network
net.train(x_train, y_train)
net.save('mnist_bcnn_test')
net.plot_dense_stats()
plt.close() # Travis-CI memory error??
net.evaluate(x_test, utils.to_categorical(y_test, 10))
pred, pred_err = net.test(x_test)
test_num = y_test.shape[0]
assert (np.sum(pred == y_test)) / test_num > 0.9 # assert accuracy
net_reloaded = load_folder("mnist_bcnn_test")
net_reloaded.mc_num = 3 # prevent memory issue on Tavis CI
prediction_loaded = net_reloaded.test(x_test[:200])
net_reloaded.folder_name = None # set to None so it can be saved
net_reloaded.save()
load_folder(net_reloaded.folder_name) # ignore pycharm warning, its not None
示例4: get_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def get_kwargs():
return {
'backend': tfkeras.backend,
'layers': tfkeras.layers,
'models': tfkeras.models,
'utils': tfkeras.utils,
}
示例5: get_submodules_from_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例6: inject_keras_modules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例7: inject_tfkeras_modules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例8: init_keras_custom_objects
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def init_keras_custom_objects():
import keras
from . import model
custom_objects = {
'swish': inject_keras_modules(model.get_swish)(),
'FixedDropout': inject_keras_modules(model.get_dropout)()
}
keras.utils.generic_utils.get_custom_objects().update(custom_objects)
示例9: init_tfkeras_custom_objects
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def init_tfkeras_custom_objects():
import tensorflow.keras as tfkeras
from . import model
custom_objects = {
'swish': inject_tfkeras_modules(model.get_swish)(),
'FixedDropout': inject_tfkeras_modules(model.get_dropout)()
}
tfkeras.utils.get_custom_objects().update(custom_objects)
示例10: init_keras_custom_objects
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def init_keras_custom_objects():
import keras
import efficientnet as model
custom_objects = {
'swish': inject_keras_modules(model.get_swish)(),
'FixedDropout': inject_keras_modules(model.get_dropout)()
}
keras.utils.generic_utils.get_custom_objects().update(custom_objects)
示例11: init_tfkeras_custom_objects
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [as 別名]
def init_tfkeras_custom_objects():
import tensorflow.keras as tfkeras
import efficientnet as model
custom_objects = {
'swish': inject_tfkeras_modules(model.get_swish)(),
'FixedDropout': inject_tfkeras_modules(model.get_dropout)()
}
tfkeras.utils.get_custom_objects().update(custom_objects)
示例12: inject_global_submodules
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例13: filter_kwargs
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例14: get_preprocessing
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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
示例15: set_framework
# 需要導入模塊: from tensorflow import keras [as 別名]
# 或者: from tensorflow.keras import utils [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