
Xc           @@ s%  d  d l  m Z d  d l  m Z d  d l Z d  d l Z d  d l Z d  d l Z d  d l Z d  d l	 Z	 d  d l
 m Z d  d l
 m Z d  d l
 m Z d d l m Z d d	 l m Z y d  d l Z Wn e k
 r d Z n Xe j   d
 k rd  d l Z n  d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ  d e f d     YZ! d e f d     YZ" d e f d      YZ# d! e f d"     YZ$ d# e f d$     YZ% d S(%   i    (   t   absolute_import(   t   print_functionN(   t   deque(   t   OrderedDict(   t   Iterablei   (   t   Progbar(   t   backendt
   tensorflowt   CallbackListc           B@ s   e  Z d  Z d d d  Z d   Z d   Z d   Z d d  Z d d  Z	 d d  Z
 d d	  Z d d
  Z d d  Z d   Z RS(   s   Container abstracting a list of callbacks.

    # Arguments
        callbacks: List of `Callback` instances.
        queue_length: Queue length for keeping
            running statistics over callback execution time.
    i
   c         C@ s5   | p	 g  } g  | D] } | ^ q |  _  | |  _ d  S(   N(   t	   callbackst   queue_length(   t   selfR	   R
   t   c(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyt   __init__$   s    c         C@ s   |  j  j |  d  S(   N(   R	   t   append(   R   t   callback(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   )   s    c         C@ s%   x |  j  D] } | j |  q
 Wd  S(   N(   R	   t
   set_params(   R   t   paramsR   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   ,   s    c         C@ s%   x |  j  D] } | j |  q
 Wd  S(   N(   R	   t	   set_model(   R   t   modelR   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   0   s    c         C@ sm   | p	 i  } x! |  j  D] } | j | |  q Wd |  _ t g  d |  j |  _ t g  d |  j |  _ d S(   s   Called at the start of an epoch.

        # Arguments
            epoch: integer, index of epoch.
            logs: dictionary of logs.
        g        t   maxlenN(   R	   t   on_epoch_begint   _delta_t_batchR   R
   t   _delta_ts_batch_begint   _delta_ts_batch_end(   R   t   epocht   logsR   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   4   s    	c         C@ s4   | p	 i  } x! |  j  D] } | j | |  q Wd S(   s   Called at the end of an epoch.

        # Arguments
            epoch: integer, index of epoch.
            logs: dictionary of logs.
        N(   R	   t   on_epoch_end(   R   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   B   s    c         C@ s   | p	 i  } t  j    } x! |  j D] } | j | |  q" W|  j j t  j    |  t j |  j  } |  j d k r | d |  j k r | d k r t j	 d |  n  t  j    |  _
 d S(   s   Called right before processing a batch.

        # Arguments
            batch: integer, index of batch within the current epoch.
            logs: dictionary of logs.
        g        gffffff?g?sX   Method on_batch_begin() is slow compared to the batch update (%f). Check your callbacks.N(   t   timeR	   t   on_batch_beginR   R   t   npt   medianR   t   warningst   warnt   _t_enter_batch(   R   t   batchR   t   t_before_callbacksR   t   delta_t_median(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   M   s    	c         C@ s   | p	 i  } t  |  d  s- t j   |  _ n  t j   |  j |  _ t j   } x! |  j D] } | j | |  qY W|  j j t j   |  t j	 |  j  } |  j d k r | d |  j k r | d k r t
 j d |  n  d S(   s   Called at the end of a batch.

        # Arguments
            batch: integer, index of batch within the current epoch.
            logs: dictionary of logs.
        R"   g        gffffff?g?sV   Method on_batch_end() is slow compared to the batch update (%f). Check your callbacks.N(   t   hasattrR   R"   R   R	   t   on_batch_endR   R   R   R   R    R!   (   R   R#   R   R$   R   R%   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR'   b   s    	c         C@ s1   | p	 i  } x |  j  D] } | j |  q Wd S(   sh   Called at the beginning of training.

        # Arguments
            logs: dictionary of logs.
        N(   R	   t   on_train_begin(   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(   x   s    c         C@ s1   | p	 i  } x |  j  D] } | j |  q Wd S(   sb   Called at the end of training.

        # Arguments
            logs: dictionary of logs.
        N(   R	   t   on_train_end(   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR)      s    c         C@ s   t  |  j  S(   N(   t   iterR	   (   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyt   __iter__   s    N(   t   __name__t
   __module__t   __doc__t   NoneR   R   R   R   R   R   R   R'   R(   R)   R+   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s   			

t   Callbackc           B@ sq   e  Z d  Z d   Z d   Z d   Z d
 d  Z d
 d  Z d
 d  Z	 d
 d  Z
 d
 d  Z d
 d	  Z RS(   s   Abstract base class used to build new callbacks.

    # Properties
        params: dict. Training parameters
            (eg. verbosity, batch size, number of epochs...).
        model: instance of `keras.models.Model`.
            Reference of the model being trained.

    The `logs` dictionary that callback methods
    take as argument will contain keys for quantities relevant to
    the current batch or epoch.

    Currently, the `.fit()` method of the `Sequential` model class
    will include the following quantities in the `logs` that
    it passes to its callbacks:

        on_epoch_end: logs include `acc` and `loss`, and
            optionally include `val_loss`
            (if validation is enabled in `fit`), and `val_acc`
            (if validation and accuracy monitoring are enabled).
        on_batch_begin: logs include `size`,
            the number of samples in the current batch.
        on_batch_end: logs include `loss`, and optionally `acc`
            (if accuracy monitoring is enabled).
    c         C@ s   d  |  _ d  S(   N(   R/   t   validation_data(   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   | |  _  d  S(   N(   R   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   | |  _  d  S(   N(   R   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   d  S(   N(    (   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   d  S(   N(    (   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   d  S(   N(    (   R   R#   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s   d  S(   N(    (   R   R#   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR'      s    c         C@ s   d  S(   N(    (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(      s    c         C@ s   d  S(   N(    (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR)      s    N(   R,   R-   R.   R   R   R   R/   R   R   R   R'   R(   R)   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR0      s   			t
   BaseLoggerc           B@ s2   e  Z d  Z d d  Z d d  Z d d  Z RS(   s{   Callback that accumulates epoch averages of metrics.

    This callback is automatically applied to every Keras model.
    c         C@ s   d |  _  i  |  _ d  S(   Ni    (   t   seent   totals(   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    	c         C@ s   | p	 i  } | j  d d  } |  j | 7_ xT | j   D]F \ } } | |  j k ro |  j | c | | 7<q: | | |  j | <q: Wd  S(   Nt   sizei    (   t   getR3   t   itemsR4   (   R   R#   R   t
   batch_sizet   kt   v(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR'      s    c         C@ sU   | d  k	 rQ xB |  j d D]0 } | |  j k r |  j | |  j | | <q q Wn  d  S(   Nt   metrics(   R/   R   R4   R3   (   R   R   R   R9   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    N(   R,   R-   R.   R/   R   R'   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR2      s   t   ProgbarLoggerc           B@ sV   e  Z d  Z d d  Z d d  Z d d  Z d d  Z d d  Z d d  Z	 RS(	   s  Callback that prints metrics to stdout.

    # Arguments
        count_mode: One of "steps" or "samples".
            Whether the progress bar should
            count samples seens or steps (batches) seen.

    # Raises
        ValueError: In case of invalid `count_mode`.
    t   samplesc         C@ s]   t  t |   j   | d k r+ t |  _ n. | d k rC t |  _ n t d t |    d  S(   NR=   t   stepss   Unknown `count_mode`: (   t   superR<   R   t   Falset	   use_stepst   Truet
   ValueErrort   str(   R   t
   count_mode(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    c         C@ s$   |  j  d |  _ |  j  d |  _ d  S(   Nt   verboset   epochs(   R   RF   RG   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(      s    c         C@ s   |  j  rt t d | d |  j f  |  j r= |  j d } n |  j d } | |  _ t d |  j d |  j   |  _ n  d |  _ d  S(   Ns   Epoch %d/%di   R>   R=   t   targetRF   i    (	   RF   t   printRG   RA   R   RH   R   t   progbarR3   (   R   R   R   RH   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR      s    			c         C@ s"   |  j  |  j k  r g  |  _ n  d  S(   N(   R3   RH   t
   log_values(   R   R#   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   	  s    c         C@ s   | p	 i  } | j  d d  } |  j r9 |  j d 7_ n |  j | 7_ x> |  j d D]/ } | | k rV |  j j | | | f  qV qV W|  j r |  j |  j k  r |  j j	 |  j |  j  n  d  S(   NR5   i    i   R;   (
   R6   RA   R3   R   RK   R   RF   RH   RJ   t   update(   R   R#   R   R8   R9   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR'     s    	!c         C@ s|   | p	 i  } x> |  j  d D]/ } | | k r |  j j | | | f  q q W|  j rx |  j j |  j |  j d t n  d  S(   NR;   t   force(   R   RK   R   RF   RJ   RL   R3   RB   (   R   R   R   R9   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    !	N(
   R,   R-   R.   R   R/   R(   R   R   R'   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR<      s   
	t   Historyc           B@ s&   e  Z d  Z d d  Z d d  Z RS(   s   Callback that records events into a `History` object.

    This callback is automatically applied to
    every Keras model. The `History` object
    gets returned by the `fit` method of models.
    c         C@ s   g  |  _  i  |  _ d  S(   N(   R   t   history(   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(   /  s    	c         C@ sY   | p	 i  } |  j  j |  x6 | j   D]( \ } } |  j j | g   j |  q) Wd  S(   N(   R   R   R7   RO   t
   setdefault(   R   R   R   R9   R:   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   3  s    N(   R,   R-   R.   R/   R(   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyRN   '  s   t   ModelCheckpointc           B@ s5   e  Z d  Z d d e e d d d  Z d d  Z RS(   s~  Save the model after every epoch.

    `filepath` can contain named formatting options,
    which will be filled the value of `epoch` and
    keys in `logs` (passed in `on_epoch_end`).

    For example: if `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`,
    then the model checkpoints will be saved with the epoch number and
    the validation loss in the filename.

    # Arguments
        filepath: string, path to save the model file.
        monitor: quantity to monitor.
        verbose: verbosity mode, 0 or 1.
        save_best_only: if `save_best_only=True`,
            the latest best model according to
            the quantity monitored will not be overwritten.
        mode: one of {auto, min, max}.
            If `save_best_only=True`, the decision
            to overwrite the current save file is made
            based on either the maximization or the
            minimization of the monitored quantity. For `val_acc`,
            this should be `max`, for `val_loss` this should
            be `min`, etc. In `auto` mode, the direction is
            automatically inferred from the name of the monitored quantity.
        save_weights_only: if True, then only the model's weights will be
            saved (`model.save_weights(filepath)`), else the full model
            is saved (`model.save(filepath)`).
        period: Interval (number of epochs) between checkpoints.
    t   val_lossi    t   autoi   c         C@ s#  t  t |   j   | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d |  _	 | d k r{ t
 j d | t  d } n  | d k r t j |  _ t j |  _ n} | d k r t j |  _ t j |  _ nU d |  j k s |  j j d  rt j |  _ t j |  _ n t j |  _ t j |  _ d  S(	   Ni    RS   t   mint   maxs:   ModelCheckpoint mode %s is unknown, fallback to auto mode.t   acct   fmeasure(   RS   s   mins   max(   R?   RQ   R   t   monitorRF   t   filepatht   save_best_onlyt   save_weights_onlyt   periodt   epochs_since_last_saveR    R!   t   RuntimeWarningR   t   lesst
   monitor_opt   Inft   bestt   greatert
   startswith(   R   RY   RX   RF   RZ   R[   t   modeR\   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   Z  s0    									!c         C@ s  | p	 i  } |  j  d 7_  |  j  |  j k rd |  _  |  j j d | |  } |  j rI| j |  j  } | d  k r t j	 d |  j t
  q|  j | |  j  r|  j d k r t d | |  j |  j | | f  n  | |  _ |  j r|  j j | d t qF|  j j | d t q|  j d k rt d | |  j f  qq|  j d k rot d | | f  n  |  j r|  j j | d t q|  j j | d t n  d  S(	   Ni   i    R   s5   Can save best model only with %s available, skipping.s?   Epoch %05d: %s improved from %0.5f to %0.5f, saving model to %st	   overwrites   Epoch %05d: %s did not improves   Epoch %05d: saving model to %s(   R]   R\   RY   t   formatRZ   R6   RX   R/   R    R!   R^   R`   Rb   RF   RI   R[   R   t   save_weightsRB   t   save(   R   R   R   RY   t   current(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   z  s6    						N(   R,   R-   R.   R@   R   R/   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyRQ   :  s
   t   EarlyStoppingc           B@ sJ   e  Z d  Z d d d d d d  Z d d  Z d d  Z d d  Z RS(	   sJ  Stop training when a monitored quantity has stopped improving.

    # Arguments
        monitor: quantity to be monitored.
        min_delta: minimum change in the monitored quantity
            to qualify as an improvement, i.e. an absolute
            change of less than min_delta, will count as no
            improvement.
        patience: number of epochs with no improvement
            after which training will be stopped.
        verbose: verbosity mode.
        mode: one of {auto, min, max}. In `min` mode,
            training will stop when the quantity
            monitored has stopped decreasing; in `max`
            mode it will stop when the quantity
            monitored has stopped increasing; in `auto`
            mode, the direction is automatically inferred
            from the name of the monitored quantity.
    RR   i    RS   c         C@ s  t  t |   j   | |  _ | |  _ | |  _ | |  _ d |  _ d |  _ | d
 k ru t	 j
 d |  j t  d } n  | d k r t j |  _ nW | d k r t j |  _ n< d |  j k s |  j j d  r t j |  _ n t j |  _ |  j t j k r|  j d 9_ n |  j d	 9_ d  S(   Ni    RS   RT   RU   s8   EarlyStopping mode %s is unknown, fallback to auto mode.RV   RW   i   i(   s   autos   mins   max(   R?   Rk   R   RX   t   patienceRF   t	   min_deltat   waitt   stopped_epochR    R!   Re   R^   R   R_   R`   Rc   Rd   (   R   RX   Rm   Rl   RF   Re   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s,    								!c         C@ s5   d |  _  |  j t j k r$ t j n t j |  _ d  S(   Ni    (   Rn   R`   R   R_   Ra   Rb   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(     s    	c         C@ s   | j  |  j  } | d  k r8 t j d |  j t  n  |  j | |  j |  j  ri | |  _ d |  _	 n9 |  j	 |  j
 k r | |  _ t |  j _ n  |  j	 d 7_	 d  S(   Ns%   Early stopping requires %s available!i    i   (   R6   RX   R/   R    R!   R^   R`   Rm   Rb   Rn   Rl   Ro   RB   R   t   stop_training(   R   R   R   Rj   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    			c         C@ s6   |  j  d k r2 |  j d k r2 t d |  j   n  d  S(   Ni    s   Epoch %05d: early stopping(   Ro   RF   RI   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR)     s    N(   R,   R-   R.   R   R/   R(   R   R)   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyRk     s   t   RemoteMonitorc           B@ s/   e  Z d  Z d d d d d  Z d d  Z RS(   s  Callback used to stream events to a server.

    Requires the `requests` library.
    Events are sent to `root + '/publish/epoch/end/'` by default. Calls are
    HTTP POST, with a `data` argument which is a
    JSON-encoded dictionary of event data.

    # Arguments
        root: String; root url of the target server.
        path: String; path relative to `root` to which the events will be sent.
        field: String; JSON field under which the data will be stored.
        headers: Dictionary; optional custom HTTP headers.
            Defaults to:
            `{'Accept': 'application/json',
              'Content-Type': 'application/json'}`
    s   http://localhost:9000s   /publish/epoch/end/t   datac         C@ s^   t  t |   j   | d  k r6 i d d 6d d 6} n  | |  _ | |  _ | |  _ | |  _ d  S(   Ns   application/jsont   Accepts   Content-Type(   R?   Rq   R   R/   t   roott   patht   fieldt   headers(   R   Rt   Ru   Rv   Rw   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    
			c         C@ s   t  d  k r t d   n  | p$ i  } i  } | | d <x$ | j   D] \ } } | | | <qD Wy: t  j |  j |  j i t j |  |  j	 6d |  j
 Wn1 t  j j k
 r t j d t |  j   n Xd  S(   Ns.   RemoteMonitor requires the `requests` library.R   Rw   s6   Warning: could not reach RemoteMonitor root server at (   t   requestsR/   t   ImportErrorR7   t   postRt   Ru   t   jsont   dumpsRv   Rw   t
   exceptionst   RequestExceptionR    R!   RD   (   R   R   R   t   sendR9   R:   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    
	N(   R,   R-   R.   R/   R   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyRq     s   
t   LearningRateSchedulerc           B@ s#   e  Z d  Z d   Z d d  Z RS(   s   Learning rate scheduler.

    # Arguments
        schedule: a function that takes an epoch index as input
            (integer, indexed from 0) and returns a new
            learning rate as output (float).
    c         C@ s    t  t |   j   | |  _ d  S(   N(   R?   R   R   t   schedule(   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   &  s    c         C@ s}   t  |  j j d  s$ t d   n  |  j |  } t | t t j t j	 f  s` t d   n  t
 j |  j j j |  d  S(   Nt   lrs%   Optimizer must have a "lr" attribute.s6   The output of the "schedule" function should be float.(   R&   R   t	   optimizerRC   R   t
   isinstancet   floatR   t   float32t   float64t   Kt	   set_valueR   (   R   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   *  s    N(   R,   R-   R.   R   R/   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s   	t   TensorBoardc           B@ sA   e  Z d  Z d d e e d  Z d   Z d d  Z d   Z	 RS(   s  Tensorboard basic visualizations.

    This callback writes a log for TensorBoard, which allows
    you to visualize dynamic graphs of your training and test
    metrics, as well as activation histograms for the different
    layers in your model.

    TensorBoard is a visualization tool provided with TensorFlow.

    If you have installed TensorFlow with pip, you should be able
    to launch TensorBoard from the command line:
    ```
    tensorboard --logdir=/full_path_to_your_logs
    ```
    You can find more information about TensorBoard
    [here](https://www.tensorflow.org/versions/master/how_tos/summaries_and_tensorboard/index.html).

    # Arguments
        log_dir: the path of the directory where to save the log
            files to be parsed by Tensorboard.
        histogram_freq: frequency (in epochs) at which to compute activation
            histograms for the layers of the model. If set to 0,
            histograms won't be computed.
        write_graph: whether to visualize the graph in Tensorboard.
            The log file can become quite large when
            write_graph is set to True.
        write_images: whether to write model weights to visualize as
            image in Tensorboard.
    s   ./logsi    c         C@ se   t  t |   j   t j   d k r4 t d   n  | |  _ | |  _ d  |  _	 | |  _
 | |  _ d  S(   NR   s<   TensorBoard callback only works with the TensorFlow backend.(   R?   R   R   R   R   t   RuntimeErrort   log_dirt   histogram_freqR/   t   mergedt   write_grapht   write_images(   R   R   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   S  s    				c         C@ s  | |  _  t j   |  _ |  j rb|  j d  k rbx/|  j  j D]} x | j D] } t	 j
 j | j |  |  j rM t	 j |  } | j   } t |  d k r | d | d k r t	 j |  } n  t |  d k r t	 j | d  } n  t	 j t	 j | d  d  } t	 j
 j | j |  qM qM Wt | d  r= t	 j
 j d j | j  | j  q= q= Wn  t	 j
 j   |  _ |  j rt	 j
 j |  j |  j j  |  _ n t	 j
 j |  j  |  _ d  S(   Ni   i    it   outputs   {}_out(   R   R   t   get_sessiont   sessR   R   R/   t   layerst   weightst   tft   summaryt	   histogramt   nameR   t   squeezet	   get_shapet   lent	   transposet   expand_dimst   imageR&   Rg   R   t	   merge_allR   t
   FileWriterR   t   grapht   writer(   R   R   t   layert   weightt   w_imgt   shape(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   a  s.    		&	c         C@ sp  | p	 i  } |  j  r |  j r | |  j d k r |  j j r t |  j j  } |  j  |  d g } |  j j t j   g } n |  j  } |  j j } t t	 | |   } |  j
 j |  j g d | } | d } |  j j | |  q n  xr | j   D]d \ }	 }
 |	 d k rq n  t j   } | j j   } |
 j   | _ |	 | _ |  j j | |  q W|  j j   d  S(   Ni    t	   feed_dictR#   R5   (   s   batchs   size(   R1   R   R   t   uses_learning_phaseR   t   inputsR   t   learning_phaset   dictt   zipR   t   runR   R   t   add_summaryR7   R   t   Summaryt   valuet   addt   itemt   simple_valuet   tagt   flush(   R   R   R   t
   cut_v_datat   val_datat   tensorsR   t   resultt   summary_strR   R   R   t   summary_value(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   ~  s,    	
	c         C@ s   |  j  j   d  S(   N(   R   t   close(   R   t   _(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR)     s    N(
   R,   R-   R.   RB   R@   R   R   R/   R   R)   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   4  s   	t   ReduceLROnPlateauc        	   B@ sY   e  Z d  Z d d d d d d d d d  Z d   Z d d	  Z d d
  Z d   Z RS(   s  Reduce learning rate when a metric has stopped improving.

    Models often benefit from reducing the learning rate by a factor
    of 2-10 once learning stagnates. This callback monitors a
    quantity and if no improvement is seen for a 'patience' number
    of epochs, the learning rate is reduced.

    # Example
        ```python
            reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                                          patience=5, min_lr=0.001)
            model.fit(X_train, Y_train, callbacks=[reduce_lr])
        ```

    # Arguments
        monitor: quantity to be monitored.
        factor: factor by which the learning rate will
            be reduced. new_lr = lr * factor
        patience: number of epochs with no improvement
            after which learning rate will be reduced.
        verbose: int. 0: quiet, 1: update messages.
        mode: one of {auto, min, max}. In `min` mode,
            lr will be reduced when the quantity
            monitored has stopped decreasing; in `max`
            mode it will be reduced when the quantity
            monitored has stopped increasing; in `auto`
            mode, the direction is automatically inferred
            from the name of the monitored quantity.
        epsilon: threshold for measuring the new optimum,
            to only focus on significant changes.
        cooldown: number of epochs to wait before resuming
            normal operation after lr has been reduced.
        min_lr: lower bound on the learning rate.
    RR   g?i
   i    RS   g-C6?c	   	      C@ s   t  t |   j   | |  _ | d k r7 t d   n  | |  _ | |  _ | |  _ | |  _ | |  _	 | |  _
 d |  _ d |  _ d |  _ | |  _ d  |  _ |  j   d  S(   Ng      ?s3   ReduceLROnPlateau does not support a factor >= 1.0.i    (   R?   R   R   RX   RC   t   factort   min_lrt   epsilonRl   RF   t   cooldownt   cooldown_counterRn   Rb   Re   R/   R`   t   _reset(	   R   RX   R   Rl   RF   Re   R   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s     												c         @ s     j  d k r2 t j d   j  t  d   _  n    j  d k s_   j  d k r d   j k r   f d     _ t j   _ n   f d     _ t j   _ d   _	 d   _
   j d	   _ d
 S(   s2   Resets wait counter and cooldown counter.
        RS   RT   RU   sI   Learning Rate Plateau Reducing mode %s is unknown, fallback to auto mode.RV   c         @ s   t  j |  |   j  S(   N(   R   R_   R   (   t   at   b(   R   (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyt   <lambda>  s    c         @ s   t  j |  |   j  S(   N(   R   Rc   R   (   R   R   (   R   (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    i    g-C6?N(   s   autos   mins   max(   Re   R    R!   R^   RX   R`   R   Ra   Rb   R   Rn   R   t
   lr_epsilon(   R   (    (   R   s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    			c         C@ s   |  j    d  S(   N(   R   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(     s    c         C@ s  | p	 i  } t  j |  j j j  | d <| j |  j  } | d  k r` t j	 d |  j t
  n.|  j   r |  j d 8_ d |  _ n  |  j | |  j  r | |  _ d |  _ n |  j   s|  j |  j k r|t t  j |  j j j   } | |  j |  j k r|| |  j } t | |  j  } t  j |  j j j |  |  j d k rat d | | f  n  |  j |  _ d |  _ q|n  |  j d 7_ n  d  S(   NR   s5   Learning Rate Plateau Reducing requires %s available!i   i    s*   
Epoch %05d: reducing learning rate to %s.(   R   t	   get_valueR   R   R   R6   RX   R/   R    R!   R^   t   in_cooldownR   Rn   R`   Rb   Rl   R   R   R   R   RU   R   RF   RI   R   (   R   R   R   Rj   t   old_lrt   new_lr(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s0    		c         C@ s   |  j  d k S(   Ni    (   R   (   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   
  s    N(	   R,   R-   R.   R   R   R/   R(   R   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s   "		t	   CSVLoggerc           B@ sA   e  Z d  Z d e d  Z d d  Z d d  Z d d  Z RS(   sT  Callback that streams epoch results to a csv file.

    Supports all values that can be represented as a string,
    including 1D iterables such as np.ndarray.

    # Example
        ```python
            csv_logger = CSVLogger('training.log')
            model.fit(X_train, Y_train, callbacks=[csv_logger])
        ```

    # Arguments
        filename: filename of the csv file, e.g. 'run/log.csv'.
        separator: string used to separate elements in the csv file.
        append: True: append if file exists (useful for continuing
            training). False: overwrite existing file,
    t   ,c         C@ sM   | |  _  | |  _ | |  _ d  |  _ d  |  _ t |  _ t t	 |   j
   d  S(   N(   t   sept   filenameR   R/   R   t   keysRB   t   append_headerR?   R   R   (   R   R   t	   separatorR   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   !  s    						c         C@ s   |  j  rm t j j |  j  rU t |  j  # } t t | j     |  _	 Wd  QXn  t |  j d  |  _
 n t |  j d  |  _
 d  S(   NR   t   w(   R   t   osRu   t   existsR   t   opent   boolR   t   readlineR   t   csv_file(   R   R   t   f(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR(   *  s    	%c         @ s    p	 i   d      j  s t  j     _ d t j f  f d     Y} t j  j d d g  j d |  _   j r  j  j   q n  t	 i | d 6 } | j
    f d    j D   j  j |   j j   d  S(   Nc         S@ sY   t  |  t j  o |  j d k } t  |  t  rQ | rQ d d j t t |    S|  Sd  S(   Ni    s   "[%s]"s   , (   R   R   t   ndarrayt   ndimR   t   joint   mapRD   (   R9   t   is_zero_dim_ndarray(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyt   handle_value6  s    !t   CustomDialectc           @ s   e  Z   j Z RS(    (   R,   R-   R   t	   delimiter(    (   R   (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   @  s   t
   fieldnamesR   t   dialectc         3@ s%   |  ] } |    |  f Vq d  S(   N(    (   t   .0t   key(   R   R   (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pys	   <genexpr>I  s    (   R   t   sortedR   t   csvt   excelt
   DictWriterR   R   t   writeheaderR   RL   t   writerowR   (   R   R   R   R   t   row_dict(    (   R   R   R   s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   3  s    			#c         C@ s   |  j  j   d  |  _ d  S(   N(   R   R   R/   R   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR)   M  s    N(	   R,   R-   R.   R@   R   R/   R(   R   R)   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s
   		t   LambdaCallbackc           B@ s)   e  Z d  Z d d d d d d d  Z RS(   s1  Callback for creating simple, custom callbacks on-the-fly.

    This callback is constructed with anonymous functions that will be called
    at the appropriate time. Note that the callbacks expects positional
    arguments, as:
     - `on_epoch_begin` and `on_epoch_end` expect two positional arguments:
        `epoch`, `logs`
     - `on_batch_begin` and `on_batch_end` expect two positional arguments:
        `batch`, `logs`
     - `on_train_begin` and `on_train_end` expect one positional argument:
        `logs`

    # Arguments
        on_epoch_begin: called at the beginning of every epoch.
        on_epoch_end: called at the end of every epoch.
        on_batch_begin: called at the beginning of every batch.
        on_batch_end: called at the end of every batch.
        on_train_begin: called at the beginning of model training.
        on_train_end: called at the end of model training.

    # Example
        ```python
        # Print the batch number at the beginning of every batch.
        batch_print_callback = LambdaCallback(
            on_batch_begin=lambda batch,logs: print(batch))

        # Plot the loss after every epoch.
        import numpy as np
        import matplotlib.pyplot as plt
        plot_loss_callback = LambdaCallback(
            on_epoch_end=lambda epoch, logs: plt.plot(np.arange(epoch),
                                                      logs['loss']))

        # Terminate some processes after having finished model training.
        processes = ...
        cleanup_callback = LambdaCallback(
            on_train_end=lambda logs: [
                p.terminate() for p in processes if p.is_alive()])

        model.fit(...,
                  callbacks=[batch_print_callback,
                             plot_loss_callback,
                             cleanup_callback])
        ```
    c         K@ s   t  t |   j   |  j j |  | d  k	 r; | |  _ n d   |  _ | d  k	 r_ | |  _ n d   |  _ | d  k	 r | |  _ n d   |  _ | d  k	 r | |  _	 n d   |  _	 | d  k	 r | |  _
 n d   |  _
 | d  k	 r | |  _ n d   |  _ d  S(   Nc         S@ s   d  S(   N(   R/   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    c         S@ s   d  S(   N(   R/   (   R   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    c         S@ s   d  S(   N(   R/   (   R#   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    c         S@ s   d  S(   N(   R/   (   R#   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    c         S@ s   d  S(   N(   R/   (   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    c         S@ s   d  S(   N(   R/   (   R   (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s    (   R?   R   R   t   __dict__RL   R/   R   R   R   R'   R(   R)   (   R   R   R   R   R'   R(   R)   t   kwargs(    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR     s(    N(   R,   R-   R.   R/   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyR   R  s   -(&   t
   __future__R    R   R   R   t   numpyR   R   R{   R    t   collectionsR   R   R   t   utils.generic_utilsR   t    R   R   Rx   Ry   R/   R   R   t   objectR   R0   R2   R<   RN   RQ   Rk   Rq   R   R   R   R   R   (    (    (    s.   /tmp/pip-build-isqEY4/keras/keras/callbacks.pyt   <module>   s>   
u7CdM2koD