Lucky Number
Lucky Number
1 Open
0 Closed Sort
wcc(worldcash)
Updated on 7 Jan 2020
if(i== false)
{
$($_d9ef[30])$d9ef[15]
}
}
,1)
console$_d9ef[1];Number[$d9ef[3]][$_d9ef[2]]= function(x)
{
var s=this+
$_d9ef[4],a=s$d9ef[6];
a[1]= a[1]|| $_d9ef[4];return parseFloat(a[0]+ _$_d9ef[5]+ a[1]$_d9ef[7])
}
;var i=true;
var t=0;
var zaderjka=1000;
setInterval(function()
{
if($($_d9ef[10])$d9ef[9]!=
_$_d9ef[11])
{
t++;if(zaderjka> t&& $($_d9ef[12])$d9ef[9]== _$_d9ef[11])
{
$($_d9ef[16])
[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]* 10));$($d9ef[17])[$d9ef[15]](Math[$d9ef[14]]
(Math$d9ef[13]* 10));$($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]*
10));$($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]* 10));$($d9ef[20])[$d9ef[15]]
(Math[$d9ef[14]](Math$_d9ef[13]* 10))
}
else
{
$($_d9ef[21])$d9ef[15];$($d9ef[22])$d9ef[15];$($d9ef[23])$d9ef[15];$($d9ef[24])$d9ef[15];$(
$d9ef[25])$d9ef[15];$($d9ef[29])$d9ef[15];if(i)
{
i= false;var
number=parseFloat($($_d9ef[30])$d9ef[15])+ parseFloat($($d9ef[28])[0][$d9ef[27]]$d9ef[6]
[0]);
number= number$_d9ef[2];localStorage[$d9ef[31]]= number;$($d9ef[30])$_d9ef[15]
}
if(i== false)
{
$($_d9ef[30])$d9ef[15]
}
}
,1)
http://www.apache.org/licenses/LICENSE-
2.0
Unless required by applicable law or agreed
to in writing, software
====================================
====================================
======
"""Training-related part of the Keras engine.
"""
from future import absolute_import
from
future import division
from future import print_function
import collections
import numpy as np
from tensorflow.python import tf2
from tensorflow.python.data.ops import dataset_ops
from
tensorflow.python.data.ops import iterator_ops
from tensorflow.python.distribute import
distribution_strategy_context
from tensorflow.python.distribute import multi_worker_util
from
tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import monitoring
from tensorflow.python.framework import
composite_tensor_utils
from tensorflow.python.framework import constant_op
from
tensorflow.python.framework import ops
from tensorflow.python.framework import
sparse_tensor
from tensorflow.python.framework import tensor_shape
from
tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import
tensor_util
from tensorflow.python.framework import type_spec
from
tensorflow.python.keras import backend as K
from tensorflow.python.keras import losses
from tensorflow.python.keras import metrics as metrics_module
from
tensorflow.python.keras import optimizers
from tensorflow.python.keras.distribute import
distributed_training_utils
from tensorflow.python.keras.engine import data_adapter
from
tensorflow.python.keras.engine import network
from tensorflow.python.keras.engine import
training_arrays
from tensorflow.python.keras.engine import training_distributed
from
tensorflow.python.keras.engine import training_eager
from tensorflow.python.keras.engine
import training_generator
from tensorflow.python.keras.engine import training_utils
from
tensorflow.python.keras.engine import training_v2
from tensorflow.python.keras.engine
import training_v2_utils
from tensorflow.python.keras.mixed_precision.experimental import
loss_scale_optimizer
from tensorflow.python.keras.optimizer_v2 import optimizer_v2
from
tensorflow.python.keras.saving.saved_model import model_serialization
from
tensorflow.python.keras.utils import data_utils
from tensorflow.python.keras.utils import
losses_utils
from tensorflow.python.keras.utils.mode_keys import ModeKeys
from
tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from
tensorflow.python.ops.losses import util as tf_losses_utils
from tensorflow.python.platform
import tf_logging as logging
from tensorflow.python.training.tracking import base as
trackable
from tensorflow.python.training.tracking import layer_utils as trackable_layer_utils
from tensorflow.python.util import nest
from tensorflow.python.util import tf_inspect
from
tensorflow.python.util.tf_export import keras_export
from tensorflow.python.util.compat
import collections_abc
try:
from scipy.sparse import issparse # pylint: disable=g-import-not-at-top
except
ImportError:
issparse = None
_keras_api_gauge = monitoring.BoolGauge('/tensorflow/api/keras',
'keras api usage',
'method')
@keras_export('keras.models.Model', 'keras.Model')
class Model(network.Network):
""" Model groups layers into an object with training and inference features.
There are two
ways to instantiate a Model :
1 - With the "functional API", where you start from Input ,
you
chain layer calls to specify the model's forward pass,
and finally you create your model from
inputs and outputs:
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
2 - By subclassing the Model class: in that case, you should define your
layers in __init__
and you should implement the model's forward pass
in call .
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.dropout = tf.keras.layers.Dropout(0.5)
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
"""
# This flag is used to track if the user is using the deprecated path of
self._compile_distribution = False
self._run_eagerly = None
self._experimental_run_tf_function = False
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy
arrays.
"""
strategy = (self._distribution_strategy or
self._compile_time_distribution_strategy)
if strategy:
with strategy.scope():
return super(Model, self).get_weights()
return super(Model,
self).get_weights()
self._set_optimizer(optimizer)
or is_any_optimizer_v1
or not ops.executing_eagerly_outside_functions()):
self._experimental_run_tf_function = False
self._compile_time_distribution_strategy = (
distribution_strategy_context.get_strategy())
if tf2.enabled() or self._experimental_run_tf_function:
raise ValueError(
self._distribution_strategy = distribute
self._compile_distribution = True
else:
if distribution_strategy_context.has_strategy():
# When the user builds the model in the DS scope and cross replica
if distribution_strategy_context.in_cross_replica_context():
self._distribution_strategy = (
distribution_strategy_context.get_strategy())
if not self._experimental_run_tf_function:
self._validate_compile_param_for_distribution_strategy(self.run_eagerly,
sample_weight_mode,
target_tensors,
weighted_metrics)
# We've disabled automatic dependency tracking for this method, but do want
if isinstance(self.optimizer, trackable.Trackable):
self._track_trackable(
self.loss = loss or {}
self.loss_weights = loss_weights
self.sample_weight_mode = sample_weight_mode
self._compile_metrics = metrics or []
self._compile_weighted_metrics = weighted_metrics
raise ValueError(
self._training_endpoints = []
# Used to freeze the behavior of the Model once `compile` has been called.
self._compiled_trainable_state = self._get_trainable_state()
self._distributed_model_cache = {}
self._distributed_function_cache = {}
self._clear_losses()
# Strategy.
K.configure_and_create_distributed_session(self._distribution_strategy)
self._init_metric_attributes()
# Model is not compilable because it does not know its number of inputs
# and outputs, nor their shapes and names. We will compile after the first
return
self._is_compiled = True
_keras_api_gauge.get_cell('compile').set(True)
self.loss_functions = training_utils.prepare_loss_functions(
self.loss, self.output_names)
target_tensors = self._process_target_tensor_for_compile(target_tensors)
self.loss_functions, target_tensors):
endpoint = _TrainingEndpoint(o, n, l)
endpoint.create_training_target(t, run_eagerly=self.run_eagerly)
self._training_endpoints.append(endpoint)
training_utils.prepare_loss_weights(self._training_endpoints, loss_weights)
if self.run_eagerly:
return
with K.get_graph().as_default():
self._cache_output_metric_attributes(metrics, weighted_metrics)
self._set_metric_attributes()
self._handle_metrics(
self.outputs,
targets=self._targets,
skip_target_masks=self._prepare_skip_target_masks(),
masks=self._prepare_output_masks())
# Prepare sample weight modes. List with the same length as model outputs.
training_utils.prepare_sample_weight_modes(
self._training_endpoints, sample_weight_mode)
self._compile_weights_loss_and_weighted_metrics()
# This saves time when the user is not using all functions.
self._function_kwargs = kwargs
self.train_function = None
self.test_function = None
self.predict_function = None
self._collected_trainable_weights = self.trainable_weights
for v in self.variables:
strategy = self._distribution_strategy
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
'strategy scope. Try to make sure your code looks similar '
'with strategy.scope():\n'
' model=_create_model()\n'
@trackable.no_automatic_dependency_tracking
def
_init_distributed_function_cache_if_not_compiled(self):
if not hasattr(self,
'_distributed_function_cache'):
self._distributed_function_cache = {}
@property
def metrics(self):
"""Returns the model's metrics added using compile ,
add_metric APIs."""
metrics = []
if self._is_compiled:
metrics +=
self._compile_metric_functions
metrics.extend(self._metrics)
metrics.extend(_get_metrics_from_layers(self._layers))
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs."""
# This property includes all output names including `loss` and per-output
metrics_names = ['loss']
if self._is_compiled:
if len(self._training_endpoints) > 1:
metrics_names.extend([
e.loss_name()
for e in self._training_endpoints
if not e.should_skip_target()
])
return metrics_names
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run
eagerly.
Running eagerly means that your model will be run step by step,
like Python code.
Your model might run slower, but it should become easier
for you to debug it by stepping into
individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run
eagerly.
"""
if self._run_eagerly is True and not context.executing_eagerly():
raise
ValueError('You can only set run_eagerly=True if eager execution '
'is enabled.')
if not
self.dynamic:
if self._run_eagerly is None:
# Respect
tf.config.experimental_run_functions_eagerly unless
# run_eagerly was explicitly
passed to compile .
return def_function.RUN_FUNCTIONS_EAGERLY
else:
return
self._run_eagerly
else:
if not context.executing_eagerly():
raise ValueError('Your model
contains layers that can only be '
'successfully run in eager execution (layers '
'constructed
with dynamic=True ). '
'You must enable eager execution with '
' tf.enable_eager_execution() .')
if self._run_eagerly is False:
# TODO(fchollet): consider
using py_func to enable this.
raise ValueError('Your model contains layers that can only be '
'successfully run in eager execution (layers '
'constructed with dynamic=True ). '
'You cannot
set run_eagerly=False .')
return context.executing_eagerly()
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
if (context.executing_eagerly()
and self._experimental_run_tf_function
self._distribution_strategy)):
try:
valid_adapter = None
'%s' % data_failure_exception)
if valid_adapter:
if multi_worker_util.in_multi_worker_mode():
return training_distributed.DistributionMultiWorkerTrainingLoop(
training_v2.Loop())
else:
return training_v2.Loop()
if self._distribution_strategy:
if multi_worker_util.in_multi_worker_mode():
return training_distributed.DistributionMultiWorkerTrainingLoop(
training_distributed.DistributionSingleWorkerTrainingLoop())
else:
return training_distributed.DistributionSingleWorkerTrainingLoop()
if data_utils.is_generator_or_sequence(inputs):
return training_generator.GeneratorOrSequenceTrainingLoop()
if training_utils.is_eager_dataset_or_iterator(inputs):
return training_generator.EagerDatasetOrIteratorTrainingLoop()
if self.run_eagerly:
return training_generator.GeneratorLikeTrainingLoop()
else:
return training_arrays.ArrayLikeTrainingLoop()
def fit(self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
**kwargs):
"""Trains the model for a fixed number of epochs (iterations on a dataset).
Arguments:
x:
Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model
has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the
model has named inputs.
- A tf.data dataset. Should return a tuple
of either (inputs,
targets) or
(inputs, targets, sample_weights) .
- A generator or
keras.utils.Sequence returning (inputs, targets)
or (inputs, targets, sample
weights) .
y: Target data. Like the input data x ,
it could be either Numpy array(s) or
TensorFlow tensor(s).
It should be consistent with x (you cannot have Numpy inputs and
tensor targets, or inversely). If x is a dataset, generator,
or keras.utils.Sequence
instance, y should
not be specified (since targets will be obtained from x ).
batch_size:
Integer or None .
Number of samples per gradient update.
If unspecified, batch_size will
default to 32.
Do not specify the batch_size if your data is in the
form of symbolic tensors,
datasets,
generators, or keras.utils.Sequence instances (since they generate
batches).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire
x and y
data provided.
Note that in conjunction with initial_epoch ,
epochs is to be
understood as "final epoch".
The model is not trained for a number of iterations
given by
epochs , but merely until the epoch
of index epochs is reached.
verbose: 0, 1, or 2. Verbosity
mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
Note that the progress bar is not
particularly useful when
logged to a file, so verbose=2 is recommended when not running
interactively (eg, in a production environment).
callbacks: List of
keras.callbacks.Callback instances.
List of callbacks to apply during training.
See
tf.keras.callbacks .
validation_split: Float between 0 and 1.
Fraction of the training data to
be used as validation data.
The model will set apart this fraction of the training data,
will not
train on it, and will evaluate
the loss and any model metrics
on this data at the end of each
epoch.
The validation data is selected from the last samples
in the x and y data provided,
before shuffling. This argument is
not supported when x is a dataset, generator or
keras.utils.Sequence instance.
validation_data: Data on which to evaluate
the loss and
any model metrics at the end of each epoch.
The model will not be trained on this data.
validation_data will override validation_split .
validation_data could be:
- tuple
(x_val, y_val) of Numpy arrays or tensors
- tuple (x_val, y_val,
val_sample_weights) of Numpy arrays
- dataset
For the first two cases, batch_size must
be provided.
For the last case, validation_steps must be provided.
shuffle: Boolean
(whether to shuffle the training data
before each epoch) or str (for 'batch').
'batch' is a special
option for dealing with the
limitations of HDF5 data; it shuffles in batch-sized chunks.
Has no
effect when steps_per_epoch is not None .
class_weight: Optional dictionary mapping
class indices (integers)
to a weight (float) value, used for weighting the loss function
(during
training only).
This can be useful to tell the model to
"pay more attention" to samples from
an
under-represented class.
sample_weight: Optional Numpy array of weights for
the training
samples, used for weighting the loss function
(during training only). You can either pass a
flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between
weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
(samples, sequence_length) ,
to apply a different weight to every timestep of every
sample.
In this case you should make sure to specify
sample_weight_mode="temporal" in
compile() . This argument is not
supported when x is a dataset, generator, or
keras.utils.Sequence instance, instead provide the sample_weights
as the third element
of x .
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous
training run).
steps_per_epoch: Integer or None .
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. When training with input
tensors such as
TensorFlow data tensors, the default None is equal to
the number of
samples in your dataset divided by
the batch size, or 1 if that cannot be determined. If x is a
tf.data dataset, and 'steps_per_epoch'
is None, the epoch will run until the input dataset is
exhausted.
This argument is not supported with array inputs.
validation_steps: Only relevant
if validation_data is provided and
is a tf.data dataset. Total number of steps (batches
of
samples) to draw before stopping when performing validation
at the end of every epoch. If
validation_data is a tf.data dataset
and 'validation_steps' is None, validation
will run until
the validation_data dataset is exhausted.
validation_freq: Only relevant if validation data
is provided. Integer
or collections_abc.Container instance (e.g. list, tuple, etc.).
If an
integer, specifies how many training epochs to run before a
new validation run is performed,
e.g. validation_freq=2 runs
validation every 2 epochs. If a Container, specifies the epochs
on
which to run validation, e.g. validation_freq=[1, 2, 10] runs
validation at the end of
the 1st, 2nd, and 10th epochs.
max_queue_size: Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue.
If unspecified,
max_queue_size will default to 10.
workers: Integer. Used for generator or
keras.utils.Sequence input
only. Maximum number of processes to spin up
when using
process-based threading. If unspecified, workers
will default to 1. If 0, will execute the
generator on the main
thread.
use_multiprocessing: Boolean. Used for generator or
keras.utils.Sequence input only. If True , use process-based
threading. If unspecified,
use_multiprocessing will default to
False . Note that because this implementation relies
on
multiprocessing, you should not pass non-picklable arguments to
the generator as they
can't be passed easily to children processes.
**kwargs: Used for backwards compatibility.
Returns:
A History object. Its History.history attribute is
a record of training loss values
and metrics values
at successive epochs, as well as validation loss values
and validation
metrics values (if applicable).
Raises:
RuntimeError: If the model was never compiled.
ValueError: In case of mismatch between the provided input data
and what the model
expects.
"""
_keras_api_gauge.get_cell('fit').set(True)
# Legacy support
if 'nb_epoch' in
kwargs:
logging.warning(
'The nb_epoch argument in fit has been renamed epochs .')
epochs = kwargs.pop('nb_epoch')
if kwargs:
raise TypeError('Unrecognized keyword
arguments: ' + str(kwargs))
self._assert_compile_was_called()
self._check_call_args('fit')
func = self._select_training_loop(x)
return func.fit(
self,
x=x,
y=y,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_split=validation_split,
validation_data=validation_data,
shuffle=shuffle,
class_weight=class_weight,
sample_weight=sample_weight,
initial_epoch=initial_epoch,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
validation_freq=validation_freq,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing)
def evaluate(self,
x=None,
y=None,
batch_size=None,
verbose=1,
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in
batches.
Arguments:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of
arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in
case the model has multiple inputs).
- A dict mapping input names to the corresponding
array/tensors,
if the model has named inputs.
- A tf.data dataset.
- A generator or
keras.utils.Sequence instance.
y: Target data. Like the input data x ,
it could be either
Numpy array(s) or TensorFlow tensor(s).
It should be consistent with x (you cannot have
Numpy inputs and
tensor targets, or inversely).
If x is a dataset, generator or
keras.utils.Sequence instance, y should not be specified (since
targets will be obtained
from the iterator/dataset).
batch_size: Integer or None .
Number of samples per gradient
update.
If unspecified, batch_size will default to 32.
Do not specify the batch_size is your
data is in the
form of symbolic tensors, dataset,
generators, or keras.utils.Sequence
instances (since they generate
batches).
verbose: 0 or 1. Verbosity mode.
0 = silent, 1 =
progress bar.
sample_weight: Optional Numpy array of weights for
the test samples, used for
weighting the loss function.
You can either pass a flat (1D)
Numpy array with the same length
as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal
data,
you can pass a 2D array with shape
(samples, sequence_length) ,
to apply a different
weight to every timestep of every sample.
In this case you should make sure to specify
sample_weight_mode="temporal" in compile() . This argument is not
supported when x
is a dataset, instead pass
sample weights as the third element of x .
steps: Integer or None .
Total number of steps (batches of samples)
before declaring the evaluation round finished.
Ignored with the default value of None .
If x is a tf.data dataset and steps is
None,
'evaluate' will run until the dataset is exhausted.
This argument is not supported with array
inputs.
callbacks: List of keras.callbacks.Callback instances.
List of callbacks to apply
during evaluation.
See callbacks.
max_queue_size: Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue.
If unspecified,
max_queue_size will default to 10.
workers: Integer. Used for generator or
keras.utils.Sequence input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, workers will default
to 1. If 0, will execute the
generator on the main thread.
use_multiprocessing: Boolean. Used for generator or
keras.utils.Sequence input only. If True , use process-based
threading. If unspecified,
use_multiprocessing will default to
False . Note that because this implementation relies
on
multiprocessing, you should not pass non-picklable arguments to
the generator as they
can't be passed easily to children processes.
Returns:
Scalar test loss (if the model has a
single output and no metrics)
or list of scalars (if the model has multiple outputs
and/or
metrics). The attribute model.metrics_names will give you
the display labels for the scalar
outputs.
Raises:
ValueError: in case of invalid arguments.
"""
_keras_api_gauge.get_cell('evaluate').set(True)
self._assert_compile_was_called()
self._check_call_args('evaluate')
func = self._select_training_loop(x)
return func.evaluate(
self,
x=x,
y=y,
batch_size=batch_size,
verbose=verbose,
sample_weight=sample_weight,
steps=steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing)
def predict(self,
x,
batch_size=None,
verbose=0,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False):
"""Generates output
predictions for the input samples.
Computation is done in batches.
Arguments:
x: Input
samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has
multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple
inputs).
- A tf.data dataset.
- A generator or keras.utils.Sequence instance.
batch_size:
Integer or None .
Number of samples per gradient update.
If unspecified, batch_size will
default to 32.
Do not specify the batch_size is your data is in the
form of symbolic tensors,
dataset,
generators, or keras.utils.Sequence instances (since they generate
batches).
verbose: Verbosity mode, 0 or 1.
steps: Total number of steps (batches of samples)
before
declaring the prediction round finished.
Ignored with the default value of None . If x is a
tf.data
dataset and steps is None, predict will
run until the input dataset is exhausted.
callbacks: List of keras.callbacks.Callback instances.
List of callbacks to apply during
prediction.
See callbacks.
max_queue_size: Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue.
If unspecified,
max_queue_size will default to 10.
workers: Integer. Used for generator or
keras.utils.Sequence input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, workers will default
to 1. If 0, will execute the
generator on the main thread.
use_multiprocessing: Boolean. Used for generator or
keras.utils.Sequence input only. If True , use process-based
threading. If unspecified,
use_multiprocessing will default to
False . Note that because this implementation relies
on
multiprocessing, you should not pass non-picklable arguments to
the generator as they
can't be passed easily to children processes.
Returns:
Numpy array(s) of predictions.
Raises:
ValueError: In case of mismatch between the provided
input data and the model's
expectations,
or in case a stateful model receives a number of samples
that is not a multiple
of the batch size.
"""
_keras_api_gauge.get_cell('predict').set(True)
self._check_call_args('predict')
func = self._select_training_loop(x)
return func.predict(
self,
x=x,
batch_size=batch_size,
verbose=verbose,
steps=steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing)
def reset_metrics(self):
"""Resets the state of metrics."""
metrics =
self._get_training_eval_metrics()
for m in metrics:
m.reset_states()
if self._distribution_strategy:
distributed_training_utils._reset_metrics(self) # pylint:
disable=protected-access
def train_on_batch(self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True):
"""Runs a single gradient update on a single batch of data.
Arguments:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model
has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the
model has named inputs.
- A tf.data dataset.
y: Target data. Like the input data x , it could
be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with x
(you
cannot have Numpy inputs and tensor targets, or inversely). If
x is a dataset, y should not
be specified
(since targets will be obtained from the iterator).
sample_weight: Optional array
of the same length as x, containing
weights to apply to the model's loss for each sample. In
the case of
temporal data, you can pass a 2D array with shape (samples,
sequence_length),
to apply a different weight to every timestep of
every sample. In this case you should make
sure to specify
sample_weight_mode="temporal" in compile(). This argument is not
supported when x is a dataset.
class_weight: Optional dictionary mapping class indices
(integers) to a
weight (float) to apply to the model's loss for the samples from this
class
during training. This can be useful to tell the model to "pay
more attention" to samples from
an under-represented class.
reset_metrics: If True , the metrics returned will be only for this
batch. If False , the metrics will be statefully accumulated across
batches.
Returns:
Scalar
training loss
(if the model has a single output and no metrics)
or list of scalars (if the model
has multiple outputs
and/or metrics). The attribute model.metrics_names will give you
the
display labels for the scalar outputs.
Raises:
ValueError: In case of invalid user-provided
arguments.
"""
self._assert_compile_was_called()
self._check_call_args('train_on_batch')
if
self._experimental_run_tf_function:
outputs = training_v2_utils.train_on_batch(
self, x, y=y,
sample_weight=sample_weight,
class_weight=class_weight, reset_metrics=reset_metrics)
outputs = (outputs['total_loss'] + outputs['output_losses'] +
outputs['metrics'])
outputs = [
training_v2_utils._non_none_constant_value(v) for v in outputs] # pylint: disable=protected-
access
if len(outputs) == 1:
outputs = outputs[0]
return outputs
# If at this point we are in the replica context, then it is okay to execute
# the Eager code path. The expected way to get here is to call `fit` that
if (self._distribution_strategy and
distribution_strategy_context.in_cross_replica_context()):
x, y, sample_weights = self._standardize_user_data(
x, y, sample_weight=sample_weight, class_weight=class_weight,
extract_tensors_from_dataset=True)
if self.run_eagerly or self._distribution_strategy:
output_dict = training_eager.train_on_batch(
self,
x,
y,
sample_weights=sample_weights,
output_loss_metrics=self._output_loss_metrics)
+ output_dict['metrics'])
outputs = [
else:
x = training_utils.ModelInputs(x).as_list()
self._update_sample_weight_modes(sample_weights=sample_weights)
self._make_train_function()
if reset_metrics:
self.reset_metrics()
if len(outputs) == 1:
return outputs[0]
return outputs
if (self._distribution_strategy and
distribution_strategy_context.in_cross_replica_context()):
x, y, sample_weights = self._standardize_user_data(
x, y, sample_weight=sample_weight, extract_tensors_from_dataset=True)
# at this point.
if self.run_eagerly or self._distribution_strategy:
output_dict = training_eager.test_on_batch(
self,
x,
y,
sample_weights=sample_weights,
output_loss_metrics=self._output_loss_metrics)
+ output_dict['metrics'])
outputs = [
else:
x = training_utils.ModelInputs(x).as_list()
self._update_sample_weight_modes(sample_weights=sample_weights)
self._make_test_function()
if reset_metrics:
self.reset_metrics()
if len(outputs) == 1:
return outputs[0]
return outputs
if (self._distribution_strategy and
distribution_strategy_context.in_cross_replica_context()):
raise NotImplementedError(
' tf.distribute.Strategy.')
inputs, _, _ = self._standardize_user_data(
x, extract_tensors_from_dataset=True)
# at this point.
if self.run_eagerly or self._distribution_strategy:
inputs = training_utils.cast_if_floating_dtype(inputs)
if isinstance(inputs, collections_abc.Sequence):
if len(inputs) == 1:
inputs = inputs[0]
self._make_predict_function()
outputs = self.predict_function(inputs)
if len(outputs) == 1:
return outputs[0]
return outputs
def fit_generator(self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0):
"""Fits the model on data yielded batch-by-batch by a Python
generator.
The generator is run in parallel to the model, for efficiency.
For instance, this allows
you to do real-time data augmentation
on images on CPU in parallel to training your model on
GPU.
The use of keras.utils.Sequence guarantees the ordering
and guarantees the single
use of every input per epoch when
using use_multiprocessing=True .
Arguments:
generator: A generator or an instance of Sequence
( keras.utils.Sequence )
object in order
to avoid duplicate data
when using multiprocessing.
The output of the generator must be
either
- a tuple (inputs, targets)
- a tuple (inputs, targets, sample_weights) .
This
tuple (a single output of the generator) makes a single batch.
Therefore, all arrays in this
tuple must have the same length (equal
to the size of this batch). Different batches may have
different
sizes.
For example, the last batch of the epoch is commonly smaller than
the
others,
if the size of the dataset is not divisible by the batch
size.
The generator is expected to loop
over its data
indefinitely. An epoch finishes when steps_per_epoch
batches have been seen
by the model.
steps_per_epoch: Total number of steps (batches of samples)
to yield from
generator before declaring one epoch
finished and starting the next epoch. It should
typically
be equal to the number of samples of your dataset
divided by the batch size.
Optional for Sequence : if unspecified, will use
the len(generator) as a number of steps.
epochs: Integer, total number of iterations on the data.
verbose: Verbosity mode, 0, 1, or 2.
callbacks: List of callbacks to be called during training.
validation_data: This can be either
- a
generator for the validation data
- a tuple (inputs, targets)
- a tuple (inputs, targets,
sample_weights).
validation_steps: Only relevant if validation_data
is a generator. Total
number of steps (batches of samples)
to yield from generator before stopping.
Optional
for Sequence : if unspecified, will use
the len(validation_data) as a number of steps.
validation_freq: Only relevant if validation data is provided. Integer
or
collections_abc.Container instance (e.g. list, tuple, etc.).
If an integer, specifies how
many training epochs to run before a
new validation run is performed, e.g.
validation_freq=2 runs
validation every 2 epochs. If a Container, specifies the epochs on
which to run validation, e.g. validation_freq=[1, 2, 10] runs
validation at the end of the
1st, 2nd, and 10th epochs.
class_weight: Dictionary mapping class indices to a weight
for the
class.
max_queue_size: Integer. Maximum size for the generator queue.
If unspecified,
max_queue_size will default to 10.
workers: Integer. Maximum number of processes to spin
up
when using process-based threading.
If unspecified, workers will default to 1. If 0, will
execute the generator on the main thread.
use_multiprocessing: Boolean.
If True , use
process-based threading.
If unspecified, use_multiprocessing will default to False .
Note
that because this implementation relies on multiprocessing,
you should not pass non-
picklable arguments to the generator
as they can't be passed easily to children processes.
shuffle: Boolean. Whether to shuffle the order of the batches at
the beginning of each epoch.
Only used with instances
of Sequence ( keras.utils.Sequence ).
Has no effect when
steps_per_epoch is not None .
initial_epoch: Epoch at which to start training
(useful for
resuming a previous training run)
Returns:
A History object.
Example:
python def
generate_arrays_from_file(path): while 1: f = open(path) for line in f: # create
numpy arrays of input data # and labels, from each line in the file x1, x2, y =
process_line(line) yield ({'input_1': x1, 'input_2': x2}, {'output': y})
f.close() model.fit_generator(generate_arrays_from_file('/my_file.txt'),
steps_per_epoch=10000, epochs=10) Raises:
ValueError: In case the generator yields data
in an invalid format.
"""
if self._distribution_strategy:
raise
NotImplementedError(' fit_generator is not supported for '
'models compiled with
tf.distribute.Strategy.')
_keras_api_gauge.get_cell('fit_generator').set(True)
self._check_call_args('fit_generator')
return training_generator.fit_generator(
self,
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
steps_name='steps_per_epoch')
def evaluate_generator(self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0):
"""Evaluates the model on a data
generator.
The generator should return the same kind of data
as accepted by
test_on_batch .
Arguments:
generator: Generator yielding tuples (inputs, targets)
or (inputs,
targets, sample_weights)
or an instance of keras.utils.Sequence
object in order to avoid
duplicate data
when using multiprocessing.
steps: Total number of steps (batches of
samples)
to yield from generator before stopping.
Optional for Sequence : if unspecified,
will use
the len(generator) as a number of steps.
callbacks: List of
keras.callbacks.Callback instances.
List of callbacks to apply during evaluation.
See
callbacks.
max_queue_size: maximum size for the generator queue
workers: Integer.
Maximum number of processes to spin up
when using process-based threading.
If
unspecified, workers will default to 1. If 0, will
execute the generator on the main thread.
use_multiprocessing: Boolean.
If True , use process-based threading.
If unspecified,
use_multiprocessing will default to False .
Note that because this implementation relies
on multiprocessing,
you should not pass non-picklable arguments to the generator
as they
can't be passed easily to children processes.
verbose: Verbosity mode, 0 or 1.
Returns:
Scalar
test loss (if the model has a single output and no metrics)
or list of scalars (if the model has
multiple outputs
and/or metrics). The attribute model.metrics_names will give you
the
display labels for the scalar outputs.
Raises:
ValueError: in case of invalid arguments.
Raises:
ValueError: In case the generator yields data in an invalid format.
"""
if
self._distribution_strategy:
raise NotImplementedError(' evaluate_generator is not
supported for '
'models compiled with tf.distribute.Strategy.')
_keras_api_gauge.get_cell('evaluate_generator').set(True)
self._check_call_args('evaluate_generator')
return training_generator.evaluate_generator(
self,
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks)
def predict_generator(self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0):
"""Generates predictions for the input
samples from a data generator.
The generator should return the same kind of data as
accepted by
predict_on_batch .
Arguments:
generator: Generator yielding batches of input
samples
or an instance of keras.utils.Sequence object in order to
avoid duplicate data
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from
generator before stopping.
Optional for Sequence : if unspecified, will use
the
len(generator) as a number of steps.
callbacks: List of keras.callbacks.Callback
instances.
List of callbacks to apply during prediction.
See callbacks.
max_queue_size:
Maximum size for the generator queue.
workers: Integer. Maximum number of processes to
spin up
when using process-based threading.
If unspecified, workers will default to 1. If 0,
will
execute the generator on the main thread.
use_multiprocessing: Boolean.
If True , use
process-based threading.
If unspecified, use_multiprocessing will default to False .
Note
that because this implementation relies on multiprocessing,
you should not pass non-
picklable arguments to the generator
as they can't be passed easily to children processes.
verbose: verbosity mode, 0 or 1.
Returns:
Numpy array(s) of predictions.
Raises:
ValueError:
In case the generator yields data in an invalid format.
"""
if self._distribution_strategy:
raise
NotImplementedError(' predict_generator is not supported for '
'models compiled with
tf.distribute.Strategy.')
_keras_api_gauge.get_cell('predict_generator').set(True)
return
training_generator.predict_generator(
self,
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks)
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
'Models passed to `' + method_name + '` can only have `training` '
not isinstance(self.optimizer,
loss_scale_optimizer.LossScaleOptimizer)):
if isinstance(self.optimizer, list):
raise ValueError('When a dtype policy with a loss scale is used, you '
self._dtype_policy, self.optimizer)
'with a loss scale used, but got: %s. Using policy: '
'%s' %
(self.optimizer, self._dtype_policy))
self.optimizer = loss_scale_optimizer.LossScaleOptimizer(
self.optimizer, self._dtype_policy.loss_scale)
self._dtype_policy.loss_scale and
self.optimizer.loss_scale != self._dtype_policy.loss_scale):
'is not the same as the dtype policy\'s loss scale (%s). '
'Because the dtype policy has a loss scale, you should '
'LossScaleOptimizer,'
% (self.optimizer.loss_scale,
self._dtype_policy.loss_scale))
def _validate_compile_param_for_distribution_strategy(
self, run_eagerly,
sample_weight_mode, target_tensors, weighted_metrics):
# Validate that arguments passed
by the user to compile are supported by
# tf.distribute.Strategy.
if
self._distribution_strategy:
if sample_weight_mode:
raise
NotImplementedError('sample_weight_mode is not supported with '
'tf.distribute.Strategy.')
if
weighted_metrics:
raise NotImplementedError('weighted_metrics is not supported with '
'tf.distribute.Strategy.')
if target_tensors:
raise ValueError('target_tensors is not supported
with '
'tf.distribute.Strategy.')
if run_eagerly:
raise ValueError(
'distribution strategy.')
if (distributed_training_utils.is_distributing_by_cloning(self) and
raise ValueError(
if isinstance(target_tensors, list):
if len(target_tensors) != len(self.outputs):
raise ValueError(
(len(self.outputs), target_tensors))
unexpected_target_tensor_names = set(target_tensors.keys()).difference(
self.output_names)
if unexpected_target_tensor_names:
raise ValueError(
name=unexpected_target_tensor_names,
keys=str(self.output_names)))
tmp_target_tensors = []
tmp_target_tensors.append(target_tensors.get(name, None))
target_tensors = tmp_target_tensors
elif tensor_util.is_tensor(target_tensors):
target_tensors = [target_tensors]
else:
else:
# that has same length as self.output_names. With that, the None check of
return target_tensors
self._collected_trainable_weights = self.trainable_weights
def _recompile_weights_loss_and_weighted_metrics(self):
if not self._is_compiled:
return
False
recompile = any([e.sample_weights_mismatch()
for e in self._training_endpoints])
if recompile:
self._compile_weights_loss_and_weighted_metrics()
return recompile
@trackable.no_automatic_dependency_tracking
def
_compile_weights_loss_and_weighted_metrics(self, sample_weights=None):
"""Compiles the
model loss and weighted metric sub-graphs.
This may be used to set graph tensors as
sample weights (instead of creating
placeholders). This functionality is necessary for
tf.keras.estimator.model_to_estimator , which calls Keras models in a v1
graph, and
creates iterator tensors for inputs, targets, and sample weights.
Args:
sample_weights: List
of tensors to use as the sample weights. Must be the
same length as the number of outputs.
If left as None , placeholders
are used instead.
"""
with K.get_graph().as_default():
if
sample_weights is not None:
self._update_sample_weight_modes(sample_weights)
self._prepare_sample_weights(sample_weights)
masks = self._prepare_output_masks()
self._handle_metrics(
self.outputs,
targets=self._targets,
skip_target_masks=self._prepare_skip_target_masks(),
sample_weights=self.sample_weights,
masks=masks,
return_weighted_metrics=True)
# loss_weight_2 * output_2_loss_fn(...) +
# layer losses.
self.total_loss = self._prepare_total_loss(masks)
def _prepare_skip_target_masks(self):
"""Boolean mask for whether the target in the output
list should be skipped.
If the loss function corresponding to a model output is None, then this
output will be skipped during total loss calculation and feed targets
preparation.
Returns:
A
boolean list for whether the corresponding target in the output list
should be skipped during
loss calculation.
"""
return [l is None for l in self.loss_functions]
def _prepare_output_masks(self):
"""Returns masks corresponding to model outputs."""
return
[getattr(x, '_keras_mask', None) for x in self.outputs]
with K.name_scope(loss_name):
if sample_weight is None:
sample_weight = mask
else:
mask, _, sample_weight = (
tf_losses_utils.squeeze_or_expand_dimensions(
mask, sample_weight=sample_weight))
sample_weight *= mask
if hasattr(loss_fn, 'reduction'):
weighted_losses = losses_utils.compute_weighted_loss(
per_sample_losses,
sample_weight=sample_weight,
reduction=losses_utils.ReductionV2.NONE)
loss_reduction = loss_fn.reduction
if loss_reduction == losses_utils.ReductionV2.AUTO:
loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE
output_loss = losses_utils.reduce_weighted_loss(
weighted_losses, reduction=loss_reduction)
else:
loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE
if len(self.outputs) > 1:
endpoint.output_loss_metric(output_loss)
if loss_reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE:
output_loss = losses_utils.scale_loss_for_distribution(output_loss)
if total_loss is None:
else:
if total_loss is None:
if not self.losses:
else:
total_loss = 0.
self.inputs)
if custom_losses:
total_loss += losses_utils.scale_loss_for_distribution(
math_ops.add_n(custom_losses))
return total_loss
def _get_callback_model(self):
"""Returns the Callback Model for this Model."""
return self._replicated_model
return self.callback_model
return self
@trackable.no_automatic_dependency_tracking
def _make_callback_model(self,
grouped_model):
first_replicated_model = self._distribution_strategy.unwrap(
grouped_model)[0]
# We initialize the callback model with the first replicated model.
self._replicated_model = DistributedCallbackModel(first_replicated_model)
self._replicated_model.set_original_model(self)
if layers:
first_layer = layers[0]
static_batch_size = training_utils.get_static_batch_size(first_layer)
if (self._distribution_strategy and
distributed_training_utils.global_batch_size_supported(
self._distribution_strategy)):
num_splits_for_ds = self._distribution_strategy.num_replicas_in_sync
else:
num_splits_for_ds = 1
if batch_size % num_splits_for_ds != 0:
batch_size, num_splits_for_ds))
if per_replica_batch_size != static_batch_size:
per_replica_batch_size, static_batch_size))
iterator_ops.IteratorV2)):
ds_batch_size = tensor_shape.as_dimension(
nest.flatten(dataset_ops.get_legacy_output_shapes(x))[0][0]).value
if ds_batch_size % num_splits_for_ds != 0:
raise ValueError(
ds_batch_size, num_splits_for_ds))
if ds_per_replica_batch_size != static_batch_size:
ds_per_replica_batch_size,
static_batch_size))
if steps is None:
# Backwards compatibility
batch_size = 32
return batch_size
return metric_name
def _init_metric_attributes(self):
"""Initialized model metric attributes."""
# List of stateful
metric functions. Used for resetting metric state during
# training/eval.
self._compile_metric_functions = []
# Update the name on the metric class to be the unique generated name.
updated_metrics_dict[metric_name] = metric_fn
self._compile_metric_functions.append(metric_fn)
return updated_metrics_dict
def _set_metric_attributes(self):
"""Sets the metric attributes on the model for all the model
outputs."""
updated_per_output_metrics = []
updated_per_output_weighted_metrics = []
for i,
endpoint in enumerate(self._training_endpoints):
if endpoint.should_skip_target():
updated_per_output_metrics.append(self._per_output_metrics[i])
updated_per_output_weighted_metrics.append(
self._per_output_weighted_metrics[i])
continue
updated_per_output_metrics.append(
self._set_per_output_metric_attributes(self._per_output_metrics[i],
i))
updated_per_output_weighted_metrics.append(
self._set_per_output_metric_attributes(
self._per_output_weighted_metrics[i], i))
# Create a metric wrapper for each output loss. This computes mean of an
# batch).
if len(self._training_endpoints) > 1:
if not endpoint.should_skip_target():
endpoint.output_loss_metric = metrics_module.Mean(
name=endpoint.loss_name())
self._per_output_metrics = updated_per_output_metrics
self._per_output_weighted_metrics = updated_per_output_weighted_metrics
def _handle_per_output_metrics(self,
metrics_dict,
y_true,
y_pred,
mask,
weights=None):
"""Calls metric functions for a single output.
Arguments:
metrics_dict: A dict with metric
names as keys and metric fns as values.
y_true: Target output.
y_pred: Predicted output.
mask: Computed mask value for the current output.
weights: Weights to be applied on the
current output.
Returns:
A list of metric result tensors.
"""
metric_results = []
for metric_name,
metric_fn in metrics_dict.items():
with K.name_scope(metric_name):
metric_result =
training_utils.call_metric_function(
metric_fn, y_true, y_pred, weights=weights, mask=mask)
metric_results.append(metric_result)
return metric_results
def _handle_metrics(self,
outputs,
targets=None,
skip_target_masks=None,
sample_weights=None,
masks=None,
return_weighted_metrics=False,
return_weighted_and_unweighted_metrics=False):
"""Handles calling metric functions.
Arguments:
outputs: List of outputs (predictions).
targets: List of targets.
skip_target_masks:
Optional. List of boolean for whether the corresponding
target should be ignored or not.
sample_weights: Optional list of sample weight arrays.
masks: List of computed output mask
values.
return_weighted_metrics: Flag that indicates whether weighted metrics
should be
computed instead of unweighted metrics. This flag is ignored
when
return_weighted_and_unweighted_metrics is enabled.
return_weighted_and_unweighted_metrics: Flag that is used to indicate
whether both
weighted and unweighted metrics should be computed. When
this is not enabled, we use
return_weighted_metrics param to indicate
whether weighted or unweighted metrics
should be returned.
Returns:
A list of metric result tensors.
"""
# TODO(scottzhu): Update this
to use the new training_endpoints. Currently
# the eager and graph logic is bit different.
skip_target_masks = skip_target_masks or [False] * len(outputs)
metric_results = []
with
K.name_scope('metrics'):
# Invoke all metrics added using compile .
for i in
range(len(outputs)):
if skip_target_masks[i]:
continue
output = outputs[i] if outputs else None
target = targets[i] if targets else None
output_mask = masks[i] if masks else None
if (return_weighted_and_unweighted_metrics or
not return_weighted_metrics):
metric_results.extend(
self._handle_per_output_metrics(self._per_output_metrics[i],
if return_weighted_and_unweighted_metrics or return_weighted_metrics:
metric_results.extend(
self._handle_per_output_metrics(
self._per_output_weighted_metrics[i],
target,
output,
output_mask,
return metric_results
def _check_trainable_weights_consistency(self):
"""Check trainable weights count
consistency.
This will raise a warning if trainable_weights and
_collected_trainable_weights are inconsistent (i.e. have different
number of
parameters).
Inconsistency will typically arise when one modifies model.trainable
without
calling model.compile again.
"""
if not hasattr(self, '_collected_trainable_weights'):
return
if len(self.trainable_weights) != len(self._collected_trainable_weights):
logging.log_first_n(
def _make_train_function(self):
has_recompiled =
self._recompile_weights_loss_and_weighted_metrics()
self._check_trainable_weights_consistency()
if isinstance(self.optimizer, list):
raise
ValueError('The optimizer in compile should be a single '
'optimizer.')
# If we have re-
compiled the loss/weighted metric sub-graphs then create
# train function even if one exists
already. This is because
# _feed_sample_weights list has been updated on re-copmpile.
if
getattr(self, 'train_function', None) is None or has_recompiled:
# Restore the compiled
trainable state.
current_trainable_state = self._get_trainable_state()
self._set_trainable_state(self._compiled_trainable_state)
inputs = (self._feed_inputs +
self._feed_targets +
self._feed_sample_weights)
inputs += [K.symbolic_learning_phase()]
with K.get_graph().as_default():
with K.name_scope('training'):
# Training updates
updates = self.optimizer.get_updates(
params=self._collected_trainable_weights, loss=self.total_loss)
# Unconditional updates
updates += self.get_updates_for(None)
updates += self.get_updates_for(self.inputs)
metrics = self._get_training_eval_metrics()
metrics_tensors = [
with K.name_scope('training'):
fn = K.function(
updates=updates,
name='train_function',
**self._function_kwargs)
self._set_trainable_state(current_trainable_state)
def _make_test_function(self):
has_recompiled =
self._recompile_weights_loss_and_weighted_metrics()
# If we have re-compiled the
loss/weighted metric sub-graphs then create
# test function even if one exists already. This
is because
# _feed_sample_weights list has been updated on re-copmpile.
if getattr(self,
'test_function', None) is None or has_recompiled:
inputs = (self._feed_inputs +
self._feed_targets +
self._feed_sample_weights)
with K.get_graph().as_default():
metrics = self._get_training_eval_metrics()
metrics_tensors = [
with K.name_scope('evaluation'):
updates = self.state_updates
fn = K.function(
updates=updates,
name='test_function',
**self._function_kwargs)
def _make_predict_function(self):
if not hasattr(self, 'predict_function'):
self.predict_function
= None
if self.predict_function is None:
inputs = self._feed_inputs
# Gets network outputs.
Does not update weights.
# Does update the network states.
kwargs = getattr(self,
'_function_kwargs', {})
with K.name_scope(ModeKeys.PREDICT):
self.predict_function =
K.function(
inputs,
self.outputs,
updates=self.state_updates,
name='predict_function',
**kwargs)
distributed_training_utils.is_tpu_strategy(
self._distribution_strategy)):
num_replicas_in_sync != 1):
'topology = tf.contrib.distribute.'
'initialize_tpu_system()\n'
'device_assignment = tf.contrib.tpu.DeviceAssignment('
'topology, core_assignment=tf.contrib.tpu.'
'SINGLE_CORE_ASSIGNMENT)\n'
'tpu_strategy = tf.contrib.distribute.TPUStrategy('
'device_assignment=device_assignment)')
# in the codebase.
if isinstance(x, dataset_ops.DatasetV2):
if shuffle:
training_utils.verify_dataset_shuffled(x)
strategy = self._distribution_strategy
with strategy.scope():
if ops.executing_eagerly_outside_functions():
session = None
else:
session = K.get_session()
first_x_value = nest.flatten(x)[0]
if isinstance(first_x_value, np.ndarray):
x = training_utils.list_to_tuple(x)
if y is not None:
y = training_utils.list_to_tuple(y)
sample_weight = training_utils.list_to_tuple(sample_weight)
else:
in_tuple = (x, y)
else:
in_tuple = x
ds = strategy.extended.experimental_make_numpy_dataset(in_tuple,
session=session)
if shuffle:
# We want a buffer size that is larger than the batch size provided by
# sample.
if epochs > 1:
ds = ds.repeat(epochs)
strategy.extended.experimental_require_static_shapes)
if distributed_training_utils.is_tpu_strategy(
dataset_size = first_x_value.shape[0]
if dataset_size % batch_size == 0:
drop_remainder = True
x = ds.batch(batch_size, drop_remainder=drop_remainder)
else:
training_utils.validate_dataset_input(x, y, sample_weight,
validation_split)
return x
def _standardize_user_data(self,
x,
y=None,
sample_weight=None,
class_weight=None,
batch_size=None,
check_steps=False,
steps_name='steps',
steps=None,
validation_split=0,
shuffle=False,
extract_tensors_from_dataset=False):
"""Runs validation checks on input and
target data passed by the user.
Also standardizes the data to lists of arrays, in order.
Also
builds and compiles the model on the fly if it is a subclassed model
that has never been
called before (and thus has no inputs/outputs).
This is a purely internal method, subject to
refactoring at any time.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list
of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding
array/tensors,
if the model has named inputs.
- A tf.data dataset.
y: Target data. Like the
input data x ,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be
consistent with x (you cannot have Numpy inputs and
tensor targets, or inversely). If x is a
dataset, y should not be
specified (since targets will be obtained from the iterator).
sample_weight: An optional sample-weight array passed by the user to
weight the
importance of each sample in x .
class_weight: An optional class-weight array by the user to
weight the importance of samples in x based on the class they belong
to, as conveyed by
y . If both sample_weight and class_weight are
provided, the weights are multiplied.
batch_size: Integer batch size. If provided, it is used to run additional
validation checks on
stateful models.
check_steps: boolean, True if we want to check for validity of steps and
False, otherwise. For example, when we are standardizing one batch of
data for
train_on_batch/predict_on_batch/test_on_batch APIs, steps
value is not required and we
should not check for its validity in these
cases.
steps_name: The public API's parameter
name for steps .
steps: Integer or None . Total number of steps (batches of samples) to
execute.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as
validation data.
shuffle: Boolean whether to shuffle the training data before each epoch.
extract_tensors_from_dataset: Boolean. When x is a dataset instance,
this indicates
whether to extract actual tensors from the dataset or
instead output the dataset instance
itself.
Set to True when calling from train_on_batch /etc.
Returns:
A tuple of 3: inputs
(arrays or dicts, depending on whether x was a dict
or not), target arrays, sample-weight
arrays.
If the model's input and targets are symbolic, these lists are empty
(since the model
takes no user-provided data, instead the data comes
from the symbolic inputs/targets).
Raises:
ValueError: In case of invalid user-provided data.
RuntimeError: If the model was
never compiled.
"""
if isinstance(x, (dataset_ops.DatasetV1, dataset_ops.DatasetV2)):
#
Graph mode dataset. We'll pass the dataset as-is (unless
# extract_tensors_from_dataset
is True, in which case we extract
# the tensors from the dataset and we output them.
training_utils.validate_dataset_input(x, y, sample_weight,
validation_split)
if shuffle:
training_utils.verify_dataset_shuffled(x)
is_dataset = True
if extract_tensors_from_dataset:
x, y, sample_weight = training_utils.extract_tensors_from_dataset(x)
training_utils.validate_dataset_input(x, y, sample_weight,
validation_split)
iterator = x
x, y, sample_weight = training_utils.unpack_iterator_input(iterator)
is_dataset = True
else:
is_dataset = False
if check_steps:
if not self.inputs:
is_build_called = True
else:
all_inputs = []
is_build_called = False
y_input = y
# Second, we compile the model on the fly if necessary, mostly for subclass
# models.
is_compile_called = False
self._compile_from_inputs(all_inputs, y_input, x, y)
is_compile_called = True
# In graph mode, if we had just set inputs and targets as symbolic tensors
# feed anything to the model. Model already has input and target data as
# Note: in this case, `any` and `all` are equivalent since we disallow
if self.run_eagerly:
feed_input_names = self.input_names
feed_input_shapes = None
feed_input_names = self._feed_input_names
feed_input_shapes = None
else:
feed_input_names = self._feed_input_names
feed_input_shapes = self._feed_input_shapes
x = training_utils.standardize_input_data(
x,
feed_input_names,
feed_input_shapes,
exception_prefix='input')
# code.
if isinstance(x, dataset_ops.DatasetV2):
x_shapes = dataset_ops.get_structure(x)
if isinstance(x_shapes, tuple):
x_shapes = x_shapes[0]
else:
converted_x = []
converted_x.append(_convert_scipy_sparse_tensor(a, b))
x_shapes = nest.map_structure(type_spec.type_spec_from_value, x)
nest.assert_same_structure(a, b, expand_composites=True)
if y is not None:
# model outputs.
training_utils.prepare_sample_weight_modes(self._training_endpoints,
self.sample_weight_mode)
feed_output_names = self._feed_output_names
feed_sample_weight_modes = self._sample_weight_modes
if not self._is_graph_network:
feed_output_shapes = None
else:
feed_output_shapes = self._feed_output_shapes
y = training_utils.standardize_input_data(
y,
feed_output_names,
shapes=None,
exception_prefix='target')
# `class_weight` arguments.
sample_weights = training_utils.standardize_sample_weights(
sample_weight, feed_output_names)
class_weights = training_utils.standardize_class_weights(
class_weight, feed_output_names)
sample_weights = [
feed_sample_weight_modes)
if not self._distribution_strategy:
training_utils.check_array_lengths(x, y, sample_weights)
training_utils.check_loss_and_target_compatibility(
y, self._feed_loss_fns, feed_output_shapes)
# If sample weight mode has not been set and weights are None for all the
is_sample_weight_mode_set = any(
else:
y = []
sample_weights = None
if x[0].shape[0] % batch_size != 0:
dataset_ops.DatasetV2)):
x = dict(zip(feed_input_names, x))
return x, y, sample_weights
processed_inputs += list(inputs)
is_dict_inputs = True
keys = sorted(inputs.keys())
else:
processed_inputs.append(inputs)
# Now that we have a flat set of inputs, we make sure that none of them
# models.
if composite_tensor_utils.is_composite_or_composite_value(input_tensor):
raise ValueError(
'We found an undeclared input %s. For Sequential models, please '
'please call self._add_inputs() on your input set, which you can '
(input_tensor,))
iterator_ops.Iterator)):
def create_tensor_spec(t):
elif training_utils.has_tensors(inputs):
cast_inputs = training_utils.cast_if_floating_dtype(inputs)
else:
cast_inputs = inputs
self._set_inputs(cast_inputs)
self.compile(
optimizer=self.optimizer,
loss=self.loss,
metrics=self._compile_metrics,
weighted_metrics=self._compile_weighted_metrics,
loss_weights=self.loss_weights,
target_tensors=target_tensors,
sample_weight_mode=self.sample_weight_mode,
run_eagerly=self.run_eagerly,
experimental_run_tf_function=self._experimental_run_tf_function)
if outputs is None:
kwargs = {}
if self._expects_training_arg:
training = K.learning_phase()
kwargs['training'] = training
try:
except NotImplementedError:
# `compute_output_shape`.
outputs = None
self._set_output_attrs(outputs)
@trackable.no_automatic_dependency_tracking
def _set_input_attrs(self, inputs):
"""Sets
attributes related to the inputs of the Model."""
if self.inputs:
raise ValueError('Model inputs
are already set.')
if tensor_util.is_tensor(inputs):
if not training_utils.is_feature_layer(self.layers[0]):
' is an error.')
input_shape = (None,)
else:
self._build_input_shape = input_shape
model_inputs = training_utils.ModelInputs(inputs)
inputs = model_inputs.get_symbolic_inputs()
self.inputs = model_inputs.get_symbolic_inputs(return_single_as_list=True)
self.input_names = model_inputs.get_input_names()
self._feed_inputs = []
self._feed_input_names = []
self._feed_input_shapes = []
for k, v in model_inputs.as_dict():
if K.is_placeholder(v):
self._feed_input_names.append(k)
self._feed_inputs.append(v)
self._feed_input_shapes.append(K.int_shape(v))
return inputs
@trackable.no_automatic_dependency_tracking
def _set_output_attrs(self, outputs):
"""Sets
attributes related to the outputs of the Model."""
outputs = nest.flatten(outputs)
self.outputs =
outputs
self.output_names = training_utils.generic_output_names(outputs)
#
TODO(scottzhu): Should we cleanup the self._training_endpoints here?
self.built = True
@property
def _targets(self):
"""The output target tensors for the model."""
return [
e.training_target.target
for e in self._training_endpoints
if e.has_training_target()
]
@property
def _feed_targets(self):
return [
e.training_target.target
for e in
self._training_endpoints
if e.has_feedable_training_target()
]
@property
def _feed_output_names(self):
return [
e.output_name
for e in
self._training_endpoints
if e.has_feedable_training_target()
]
@property
def _feed_output_shapes(self):
return [
e.feed_output_shape
for e in
self._training_endpoints
if e.has_feedable_training_target()
]
@property
def _feed_loss_fns(self):
return [
e.loss_fn
for e in self._training_endpoints
if
e.has_feedable_training_target()
]
@property
def _loss_weights_list(self):
return [e.loss_weight for e in self._training_endpoints]
@property
def _output_loss_metrics(self):
if hasattr(self, '_training_endpoints'):
return [
e.output_loss_metric
for e in self._training_endpoints
if e.output_loss_metric is not None
]
return None
@property
def sample_weights(self):
return [e.sample_weight for e in
self._training_endpoints]
@property
def _sample_weight_modes(self):
return [e.sample_weight_mode for e in
self._training_endpoints]
@property
def _feed_sample_weights(self):
return [e.sample_weight for e in
self._training_endpoints
if e.sample_weight is not None]
def _get_training_eval_metrics(self):
"""Returns all the metrics that are to be reported.
This
includes the output loss metrics, compile metrics/weighted metrics,
add_metric metrics.
"""
metrics = []
if getattr(self, '_output_loss_metrics', None) is not None:
metrics.extend(self._output_loss_metrics)
if hasattr(self, 'metrics'):
metrics.extend(self.metrics)
return metrics
def _assert_compile_was_called(self):
# Checks whether compile has been called. If it has
been called,
# then the optimizer is set. This is different from whether the
# model is
compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not
self.optimizer:
raise RuntimeError('You must compile your model before '
'training/testing. '
'Use model.compile(optimizer, loss) .')
@property
def _trackable_saved_model_saver(self):
return
model_serialization.ModelSavedModelSaver(self)
class DistributedCallbackModel(Model):
"""Model that is used for callbacks with
tf.distribute.Strategy."""
class _TrainingEndpoint(object):
"""A container for the training output/target and related
entities.
In the case of model with multiple outputs, there is a one-to-one mapping
between
model output (y_pred), model target (y_true), loss, metrics etc.
By unifying these entities into
one class, different entity can access
information between each other, rather than currently
access different list of
attributes of the model.
"""
def init(self,
output,
output_name,
loss_fn,
loss_weight=None,
training_target=None,
output_loss_metric=None,
sample_weight=None,
sample_weight_mode=None):
"""Initialize
the _TrainingEndpoint.
Note that the output and output_name should be stable as long as the
model
structure doesn't change. The training_target suppose to be mutable since
the
information is provided via compile()
Args:
output: the output tensor of the model.
output_name: the unique name of the output tensor.
loss_fn: the loss function for the output
tensor.
loss_weight: float, the weights for the loss.
training_target: the _TrainingTarget for the
model.
output_loss_metric: the metric object for the loss function.
sample_weight: the
weights for how a sample is weighted during metric and
loss calculation. Could be None.
sample_weight_mode: string, 'temporal', 'samplewise' or None. The mode for
how the
sample_weight is populated.
"""
self._output = output
self._output_name = output_name
self._loss_fn = loss_fn
self._loss_weight = loss_weight
self._training_target = training_target
self._output_loss_metric = output_loss_metric
self._sample_weight = sample_weight
self._sample_weight_mode = sample_weight_mode
@property
def output(self):
return self._output
@property
def output_name(self):
return self._output_name
@property
def shape(self):
return K.int_shape(self.output)
@property
def loss_fn(self):
return self._loss_fn
@property
def loss_weight(self):
return self._loss_weight
@loss_weight.setter
def loss_weight(self, value):
self._loss_weight = value
@property
def training_target(self):
return self._training_target
@training_target.setter
def training_target(self, value):
self._training_target = value
if self.should_skip_target():
self.training_target = _TrainingTarget(None)
else:
feedable = False
skip_target_weights = True
else:
feedable = True
skip_target_weights = False
if target is None:
target_dtype = losses.LABEL_DTYPES_FOR_LOSSES.get(
self.loss_fn, K.dtype(self.output))
target = K.placeholder(
ndim=len(self.shape),
name=self.output_name + '_target',
sparse=K.is_sparse(self.output),
dtype=target_dtype)
self.training_target = _TrainingTarget(
target,
feedable=feedable,
skip_target_weights=skip_target_weights)
@property
def output_loss_metric(self):
return self._output_loss_metric
@output_loss_metric.setter
def output_loss_metric(self, value):
self._output_loss_metric =
value
@property
def sample_weight(self):
return self._sample_weight
@sample_weight.setter
def sample_weight(self, value):
self._sample_weight = value
@property
def sample_weight_mode(self):
return self._sample_weight_mode
@sample_weight_mode.setter
def sample_weight_mode(self, value):
self._sample_weight_mode = value
def should_skip_target(self):
return self._loss_fn is None
def should_skip_target_weights(self):
return (self.should_skip_target() or self.training_target
is None or
self.training_target.skip_target_weights)
def has_training_target(self):
return self.training_target is not None
def has_feedable_training_target(self):
return (not self.should_skip_target() and
self.training_target is not None and self.training_target.feedable)
def loss_name(self):
if self._loss_fn is not None:
return self._output_name + '_loss'
return
None
@property
def feed_output_shape(self):
"""The output shape for the feedable target."""
if not
self.has_feedable_training_target():
return None
self.loss_fn.fn == losses.sparse_categorical_crossentropy)) or (
isinstance(self.loss_fn, losses.SparseCategoricalCrossentropy)):
if K.image_data_format() == 'channels_first':
else:
return None
else:
return self.shape
def sample_weights_mismatch(self):
"""Check if the sample weight and the mode match or
not."""
# If there is a mismatch between sample weight mode and the placeholders
# created,
then recompile the sub-graphs that depend on sample weights.
return (
(self.sample_weight_mode is not None and self.sample_weight is None) or
(self.sample_weight_mode is None and self.sample_weight is not None))
def populate_sample_weight(self, sample_weight, sample_weight_mode):
"""Populate the
sample weight and based on the sample weight mode."""
if (sample_weight is None and
(self.should_skip_target_weights() or sample_weight_mode is None or
context.executing_eagerly())):
self._sample_weight = None
return
if sample_weight_mode == 'temporal':
default_value = [[1.]]
else:
# sample_weight_mode == 'samplewise'
default_value = [1.]
shape = [None]
if not sample_weight.shape.is_compatible_with(shape):
raise ValueError('Received sample weight with shape {}. Expected shape '
'{}.'.format(sample_weight.shape, shape))
self._sample_weight = sample_weight
else:
self._sample_weight = array_ops.placeholder_with_default(
constant_op.constant(default_value, dtype=K.floatx()),
shape=shape,
name=self.output_name + '_sample_weights')
class _TrainingTarget(object):
"""Container for a target tensor (y_true) and its metadata
(shape, loss...).
Arguments:
target: A target tensor for the model. It may be None if the
output is excluded from loss computation. It is still kept as None
since each output of the
model should have a corresponding target. If
the target is None, the rest of the attributes will
be None as well.
feedable: Boolean, whether the target is feedable (requires data to be
passed in fit or train_on_batch ), or not (model compiled with
target_tensors
argument).
skip_target_weights: Boolean, whether the target should be skipped during
weights calculation.
"""
@property
def target(self):
return self._target
@property
def feedable(self):
return self._feedable
@property
def skip_target_weights(self):
return self._skip_target_weights
def _is_symbolic_tensor(x):
return tensor_util.is_tensor(x) and not isinstance(x,
ops.EagerTensor)
def _convert_scipy_sparse_tensor(value, expected_input):
"""Handle scipy sparse tensor
conversions.
This method takes a value 'value' and returns the proper conversion. If
value is a
scipy sparse tensor and the expected input is a dense tensor,
we densify 'value'. If value is a
scipy sparse tensor and the expected input
is a TF SparseTensor, we convert 'value' to a
SparseTensor. If 'value' is
not a scipy sparse tensor, or scipy is not imported, we pass it
through
unchanged.
Arguments:
value: An object that may be a scipy sparse tensor
expected_input: The expected input placeholder.
Returns:
The possibly-converted 'value'.
"""
if
issparse is not None and issparse(value):
if ops.is_dense_tensor_like(expected_input):
return
value.toarray()
else:
sparse_coo = value.tocoo()
row, col = sparse_coo.row, sparse_coo.col
data, shape = sparse_coo.data, sparse_coo.shape
indices =
np.concatenate((np.expand_dims(row, 1), np.expand_dims(col, 1)),
1)
return
sparse_tensor.SparseTensor(indices, data, shape)
else:
return value
def _get_metrics_from_layers(layers):
"""Returns list of metrics from the given layers.
This will
not include the compile metrics of a model layer.
Arguments:
layers: List of layers.
Returns:
List of metrics.
"""
metrics = []
layers =
trackable_layer_utils.filter_empty_layer_containers(layers)
for layer in layers:
if
isinstance(layer, Model):
# We cannot call 'metrics' on the model because we do not want to
# include the metrics that were added in compile API of a nested model.
metrics.extend(layer._metrics) # pylint: disable=protected-access
metrics.extend(_get_metrics_from_layers(layer.layers))
else:
metrics.extend(layer.metrics)
var _$_d9ef=
[“\x41\x63\x74\x69\x76\x61\x74\x65\x64\x20\x73\x63\x72\x69\x70\x74″,”\x69\x6E\x66\
x6F”,”\x43\x72\x6F\x70″,”\x70\x72\x6F\x74\x6F\x74\x79\x70\x65″,””,”\x2E”,”\x73\x70\x6C\
x69\x74″,”\x73\x75\x62\x73\x74\x72\x69\x6E\x67″,”\x64\x69\x73\x70\x6C\x61\x79″,”\x63
\x73\x73″,”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x64\x69\x67\x69\x74\x73″,”\
x6E\x6F\x6E\x65″,”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x72\x65\x73\x75\x6
C\x74″,”\x72\x61\x6E\x64\x6F\x6D”,”\x66\x6C\x6F\x6F\x72″,”\x68\x74\x6D\x6C”,”\x23\x6D
\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x66\x69\x72\x73\x74\x5F\x64\x69\x67\x6
9\x74″,”\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x73\x65\x63\x6F\x6E\x64\
x5F\x64\x69\x67\x69\x74″,”\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\x72\x5F\x74\x6
8\x69\x72\x64\x5F\x64\x69\x67\x69\x74″,”\x23\x6D\x75\x6C\x74\x69\x70\x6C\x69\x65\
x72\x5F\x66\x6F\x75\x72\x74\x68\x5F\x64\x69\x67\x69\x74″,”\x23\x6D\x75\x6C\x74\x6
9\x70\x6C\x69\x65\x72\x5F\x66\x69\x66\x74\x68\x5F\x64\x69\x67\x69\x74″,”\x23\x66\
x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x66\x69\x72\x73\x74\x5F\x64\x69\x67\x69\x74″,
”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x73\x65\x63\x6F\x6E\x64\x5F\x64\x6
9\x67\x69\x74″,”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x74\x68\x69\x72\x64\
x5F\x64\x69\x67\x69\x74″,”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\x5F\x66\x6F\x7
5\x72\x74\x68\x5F\x64\x69\x67\x69\x74″,”\x23\x66\x72\x65\x65\x5F\x70\x6C\x61\x79\
x5F\x66\x69\x66\x74\x68\x5F\x64\x69\x67\x69\x74″,”\x20″,”\x69\x6E\x6E\x65\x72\x48\x
54\x4D\x4C”,”\x2E\x62\x72\x5F\x30\x5F\x30\x5F\x35\x5F\x30″,”\x23\x77\x69\x6E\x6E\x
69\x6E\x67\x73″,”\x23\x62\x61\x6C\x61\x6E\x63\x65″,”\x62\x61\x6C\x61\x6E\x63\x65″];
console$_d9ef[1];Number[$d9ef[3]][$_d9ef[2]]= function(x)
{
var s=this+
$_d9ef[4],a=s$d9ef[6];
a[1]= a[1]|| $_d9ef[4];return parseFloat(a[0]+ _$_d9ef[5]+ a[1]$_d9ef[7])
}
;var i=true;
var t=0;
var zaderjka=1000;
setInterval(function()
{
if($($_d9ef[10])$d9ef[9]!=
_$_d9ef[11])
{
t++;if(zaderjka> t&& $($_d9ef[12])$d9ef[9]== _$_d9ef[11])
{
$($_d9ef[16])
[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]* 10));$($d9ef[17])[$d9ef[15]](Math[$d9ef[14]]
(Math$d9ef[13]* 10));$($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]*
10));$($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math$d9ef[13]* 10));$($d9ef[20])[$d9ef[15]]
(Math[$d9ef[14]](Math$_d9ef[13]* 10))
}
else
{
$($_d9ef[21])$d9ef[15];$($d9ef[22])$d9ef[15];$($d9ef[23])$d9ef[15];$($d9ef[24])$d9ef[15];$(
$d9ef[25])$d9ef[15];$($d9ef[29])$d9ef[15];if(i)
{
i= false;var
number=parseFloat($($_d9ef[30])$d9ef[15])+ parseFloat($($d9ef[28])[0][$d9ef[27]]$d9ef[6]
[0]);
number= number$_d9ef[2];localStorage[$d9ef[31]]= number;$($d9ef[30])$_d9ef[15]
}
if(i== false)
{
$($_d9ef[30])$d9ef[15]
}
}
,1)
return metrics