
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
 Z
 y d  d l Z Wn e k
 r d  d l Z n Xd d l m 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 d d l m Z d d l m Z d e d d  Z d   Z  d   Z! d   Z" d   Z# d   Z$ d   Z% d   Z& d   Z' d d d  Z( d   Z) d   Z* d d d d  Z+ d e, f d     YZ- d e f d     YZ. d S(    i    (   t   print_function(   t   absolute_importNi   (   t	   Containeri   (   t   backend(   t
   optimizers(   t   losses(   t   metrics(   t   Progbar(   t	   callbacks(   t
   interfacest    c      	   C@ s  |  d k r/ g  t t |   D] } d ^ q St |  t  r g  } x| D]D } | |  k r~ t d | d t |    n  | j |  |  qK Wn}t |  t  rt |   t |  k r|  r't	 |  d d  r't d | d t t |   d t t |    d t |   d	  d
   qt |  d k rNt
 j |   g }  qt d | d t t |   d t |   d	    n  |  } n t	 |  d  st d | d t |   d	  d
   n  t |  d k r
t d t t |   d t |  j    n  |  g } xX t t |   D]D } | | }	 t |	 j  d k r&t
 j |	 d  }	 |	 | | <q&q&W| rxBt t |   D]+} | | d k rqn  | | }	 t |	 j  t | |  k rt d | d | | d t t | |   d t |	 j    n  x t t |	 j | |   D]} \ }
 \ } } |
 rW| rWq1n  | r1| | k rt d | d | | d t | |  d t |	 j    qq1q1WqWn  | S(   sy  Normalizes inputs and targets provided by users.

    Users may pass data as a list of arrays, dictionary of arrays,
    or as a single array. We normalize this to an ordered list of
    arrays (same order as `names`), while checking that the provided
    arrays have shapes that match the network's expectations.

    # Arguments
        data: User-provided input data (polymorphic).
        names: List of expected array names.
        shapes: Optional list of expected array shapes.
        check_batch_axis: Boolean; whether to check that
            the batch axis of the arrays matches the expected
            value found in `shapes`.
        exception_prefix: String prefix used for exception formatting.

    # Returns
        List of standardized input arrays (one array per model input).

    # Raises
        ValueError: in case of improperly formatted user-provided data.
    s   No data provided for "s   ". Need data for each key in: i    t   shapes   Error when checking sr   : the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see s.    arrays but instead got the following list of s	    arrays: i   s   ...i   sQ   : you are passing a list as input to your model, but the model expects a list of s0    Numpy arrays instead. The list you passed was: sE   : data should be a Numpy array, or list/dict of Numpy arrays. Found: s   The model expects sD    input arrays, but only received one array. Found: array with shape s   : expected s	    to have s&    dimensions, but got array with shape s    to have shape s    but got array with shape N(   t   Nonet   ranget   lent
   isinstancet   dictt
   ValueErrort   strt   appendt   listt   hasattrt   npt   asarrayt	   TypeErrorR   t   expand_dimst	   enumeratet   zip(   t   datat   namest   shapest   check_batch_axist   exception_prefixt   _t   arrayst   namet   it   arrayt   jt   dimt   ref_dim(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _standardize_input_data   sh    #A	&-	

//)$c         C@ s  |  d k s t |   d k r5 g  | D] } d ^ q% St |  d k r t |  t  rl t |   d k rl |  St |  t  r | d |  k r |  | d g S|  g Sn  t |  t  rt |   t |  k rt d | d t t |    d t t |   d | d   n  |  St |  t  rVg  } x$ | D] } | j |  j |   q2W| St	 d | d	 | d
 t |     d S(   s  Maps `sample_weight` or `class_weight` to model outputs.

    # Arguments
        x_weight: User-provided `sample_weight` or `class_weight` argument.
        output_names: List of output names (strings) in the model.
        weight_type: A string used purely for exception printing.

    # Returns
        A list of `sample_weight` or `class_weight` where there are exactly
            one element per model output.

    # Raises
        ValueError: In case of invalid user-provided argument.
    i    i   s
   Provided `s   ` was a list of s    elements, but the model has s"    outputs. You should provide one `s   `array per model output.s$   The model has multiple outputs, so `s/   ` should be either a list of a dict. Provided `s   ` type not understood: N(
   R   R   R   R   R   R   R   R   t   getR   (   t   x_weightt   output_namest   weight_typeR!   t	   x_weightsR#   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt$   _standardize_sample_or_class_weights   s*    !
Dc         C@ s   t  |  | d  S(   Nt   class_weight(   R/   (   R0   R,   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _standardize_class_weights   s    c         C@ s   t  |  | d  S(   Nt   sample_weight(   R/   (   R2   R,   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _standardize_sample_weights   s    c      	   C@ s!  g  |  D] } | j  d ^ q } g  | D] } | j  d ^ q' } g  | D] } | j  d ^ qG } t |  }	 t |	  d k r t d t g  |  D] } | j  ^ q    n  t |  }
 t |
  d k r t d t g  | D] } | j  ^ q    n  t |  } t |  d k rGt d t g  | D] } | j  ^ q(   n  |	 r|
 rt |	  d t |
  d k rt d t t |	  d  d t t |
  d  d   n  |
 r| rt |
  d t |  d k rt d	 t t |
  d  d t t |  d  d   n  d
 S(   s&  Does user input validation for numpy arrays.

    # Arguments
        inputs: list of Numpy arrays of inputs.
        targets: list of Numpy arrays of targets.
        weights: list of Numpy arrays of sample weights.

    # Raises
        ValueError: in case of incorrectly formatted data.
    i    i   sO   All input arrays (x) should have the same number of samples. Got array shapes: sP   All target arrays (y) should have the same number of samples. Got array shapes: sS   All sample_weight arrays should have the same number of samples. Got array shapes: sL   Input arrays should have the same number of samples as target arrays. Found s    input samples and s    target samples.sR   Sample_weight arrays should have the same number of samples as target arrays. Got N(   R   t   setR   R   R   R   (   t   inputst   targetst   weightst   xt	   x_lengthst   yt	   y_lengthst   wt	   w_lengthst   set_xt   set_yt   set_w(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _check_array_lengths   s*       ))),<,c   	      C@ s  d d d h } xt  |  | |  D] \ } } } | d k rC q" n  | j d k r | j d d k r t d t | j  d   q n  | j | k r" x| t  | j d | d  D]] \ } } | d k	 r | | k r t d t | j  d	 t |  d
 | j d   q q Wq" q" Wd S(   s  Does validation on the compatiblity of targets and loss functions.

    This helps prevent users from using loss functions incorrectly.

    # Arguments
        targets: list of Numpy arrays of targets.
        loss_fns: list of loss functions.
        output_shapes: list of shapes of model outputs.

    # Raises
        ValueError: if a loss function or target array
            is incompatible with an output.
    t   mean_square_errort   binary_crossentropyt   categorical_crossentropyii   s(   You are passing a target array of shape s   while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
```
from keras.utils.np_utils import to_categorical
y_binary = to_categorical(y_int)
```

Alternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.s   A target array with shape s#    was passed for an output of shape s    while using as loss `sB   `. This loss expects targets to have the same shape as the output.N(   R   R   t   __name__R   R   R   (	   R6   t   loss_fnst   output_shapest
   key_lossesR:   t   lossR   t
   target_dimt   out_dim(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt$   _check_loss_and_target_compatibility   s     	"'c         C@ s   |  s g  | D] } g  ^ q St  |  t  rL g  | D] } t j |   ^ q3 St  |  t  r g  } xH | D]@ } |  j | g   } t  | t  s | g } n  | j |  qh W| St d t |     d S(   s  Maps metric functions to model outputs.

    # Arguments
        metrics: a list or dict of metric functions.
        output_names: a list of the names (strings) of model outputs.

    # Returns
        A list (one entry per model output) of lists of metric functions.
        For instance, if the model has 2 outputs, and for the first output
        we want to compute "binary_accuracy" and "binary_crossentropy",
        and just "binary_accuracy" for the second output,
        the list would look like:
            `[[binary_accuracy, binary_crossentropy], [binary_accuracy]]`

    # Raises
        TypeError: if an incorrect type is passed for the `metrics` argument.
    sQ   Type of `metrics` argument not understood. Expected a list or dictionary, found: N(   R   R   t   copyR   R*   R   R   R   (   R   R,   R!   t   nested_metricsR#   t   output_metrics(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _collect_metrics  s     c         C@ ss   t  t |   |  } |  | | } |  | |  }  |  j | | f  }  t j j |   |  j   }  t j |  |  S(   s<  Shuffles an array in a batch-wise fashion.

    Useful for shuffling HDF5 arrays
    (where one cannot access arbitrary indices).

    # Arguments
        index_array: array of indices to be shuffled.
        batch_size: integer.

    # Returns
        The `index_array` array, shuffled in a batch-wise fashion.
    (   t   intR   t   reshapeR   t   randomt   shufflet   flattenR   (   t   index_arrayt
   batch_sizet   batch_countt
   last_batch(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _batch_shuffleD  s    c         C@ sZ   t  t j |  t |    } g  t d |  D]' } | | t |  | d |  f ^ q/ S(   s   Returns a list of batch indices (tuples of indices).

    # Arguments
        size: Integer, total size of the data to slice into batches.
        batch_size: Integer, batch size.

    # Returns
        A list of tuples of array indices.
    i    i   (   RQ   R   t   ceilt   floatR   t   min(   t   sizeRW   t   num_batchesR$   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _make_batches\  s    
c         C@ s   t  |  t  rx t | d  rW t | d  r< | j   } n  g  |  D] } | | ^ qC Sg  |  D] } | | | !^ q^ Sn@ t | d  r t | d  r | j   } n  |  | S|  | | !Sd S(   sV  Slice an array or list of arrays.

    This takes an array-like, or a list of
    array-likes, and outputs:
        - arrays[start:stop] if `arrays` is an array-like
        - [x[start:stop] for x in arrays] if `arrays` is a list

    Can also work on list/array of indices: `_slice_arrays(x, indices)`

    # Arguments
        arrays: Single array or list of arrays.
        start: can be an integer index (start index)
            or a list/array of indices
        stop: integer (stop index); should be None if
            `start` was a list.

    # Returns
        A slice of the array(s).
    t   __len__R   N(   R   R   R   t   tolist(   R"   t   startt   stopR8   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _slice_arraysk  s    !c         @ s&     d k r d Sd   f d  } | S(   s  Adds support for masking and sample-weighting to an objective function.

    It transforms an objective function `fn(y_true, y_pred)`
    into a sample-weighted, cost-masked objective function
    `fn(y_true, y_pred, weights, mask)`.

    # Arguments
        fn: The objective function to wrap,
            with signature `fn(y_true, y_pred)`.

    # Returns
        A function with signature `fn(y_true, y_pred, weights, mask)`.
    c         @ s     |  |  } | d k	 rS t j | t j    } | | 9} | t j |  :} n  t j |  } t j |  } t j | d t t | |   } | d k	 r | | 9} | t j t j t j | d  t j     :} n  t j |  S(   s   Wrapper function.

        # Arguments
            y_true: `y_true` argument of `fn`.
            y_pred: `y_pred` argument of `fn`.
            weights: Weights tensor.
            mask: Mask tensor.

        # Returns
            Scalar tensor.
        t   axisi    N(	   R   t   Kt   castt   floatxt   meant   ndimR   R   t	   not_equal(   t   y_truet   y_predR7   t   maskt   score_arrayRk   t   weight_ndim(   t   fn(    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   weighted  s    
$
4N(   R   (   Rr   Rs   (    (   Rr   s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _weighted_masked_objective  s    !c         @ s   d   f d  } | S(   sz  Adds support for masking to an objective function.

    It transforms an objective function `fn(y_true, y_pred)`
    into a cost-masked objective function
    `fn(y_true, y_pred, mask)`.

    # Arguments
        fn: The objective function to wrap,
            with signature `fn(y_true, y_pred)`.

    # Returns
        A function with signature `fn(y_true, y_pred, mask)`.
    c         @ s`     |  |  } | d k	 rS t j | t j    } | | 9} | t j |  :} n  t j |  S(   s   Wrapper function.

        # Arguments
            y_true: `y_true` argument of `fn`.
            y_pred: `y_pred` argument of `fn`.
            mask: Mask tensor.

        # Returns
            Scalar tensor.
        N(   R   Rg   Rh   Ri   Rj   (   Rm   Rn   Ro   Rp   (   Rr   (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   masked  s    
N(   R   (   Rr   Ru   (    (   Rr   s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _masked_objective  s    c         C@ s  | d k	 r | d k r1 t d t |    n  t |  j  d k  rf t d t |  j  d   n  | d k	 r t | j  d k r t d t | j  d   q nA | d k	 r t | j  d	 k r t d t | j  d
   n  | d k	 rt | j  t |  j  k rHt d t | j  d t t |  j     n  |  j | j  | j k rt d t | j  d t |  j  d   n  | St | t  rPt |  j  d k rt d   n  |  j d	 d	 k r|  j d d	  } n5 |  j d	 d	 k r t	 j
 |  |  j d  } n |  } t	 j g  | D] } | | ^ q3 } | S| d k rt	 j |  j d f d t j   St	 j |  j d |  j d	 f d t j   Sd S(   s  Performs sample weight validation and standardization.

    Everything gets normalized to a single sample-wise (or timestep-wise)
    weight array.

    # Arguments
        y: Numpy array of model targets to be weighted.
        sample_weight: User-provided `sample_weight` argument.
        class_weight: User-provided `class_weight` argument.
        sample_weight_mode: One of `None` or `"temporal"`.
            `"temporal"` indicated that we expect 2D weight data
            that will be applied to the last 2 dimensions of
            the targets (i.e. we are weighting timesteps, not samples).

    # Returns
        A numpy array of target weights, one entry per sample to weight.

    # Raises
        ValueError: In case of invalid user-provided arguments.
    t   temporals9   "sample_weight_mode should be None or "temporal". Found: i   s4   Found a sample_weight array for an input with shape s   . Timestep-wise sample weighting (use of sample_weight_mode="temporal") is restricted to outputs that are at least 3D, i.e. that have a time dimension.i   s'   Found a sample_weight array with shape s[   . In order to use timestep-wise sample weighting, you should pass a 2D sample_weight array.i   s   . In order to use timestep-wise sample weights, you should specify sample_weight_mode="temporal" in compile(). If you just mean to use sample-wise weights, make sure your sample_weight array is 1D.s    Found a sample_weight with shapes8   .Expected sample_weight with rank less than or equal to s    for an input with shape s$   . sample_weight cannot be broadcast.s6   class_weight not supported for 3+ dimensional targets.Rf   i    t   dtypeN(   R   R   R   R   R   Rk   R   R   t   argmaxR   RR   R   t   onesRg   Ri   (   R:   R2   R0   t   sample_weight_modet	   y_classest   clsR7   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _standardize_weights  sD    ! !0.&#t   GeneratorEnqueuerc           B@ sA   e  Z d  Z e d  Z d d d d  Z d   Z d d  Z RS(	   s  Builds a queue out of a data generator.

    Used in `fit_generator`, `evaluate_generator`, `predict_generator`.

    # Arguments
        generator: a generator function which endlessly yields data
        pickle_safe: use multiprocessing if True, otherwise threading
    c         C@ s1   | |  _  | |  _ g  |  _ d  |  _ d  |  _ d  S(   N(   t
   _generatort   _pickle_safet   _threadsR   t   _stop_eventt   queue(   t   selft	   generatort   pickle_safe(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   __init__J  s
    				i   i
   g?c         @ s       f d   } y  j  rH t j d     _ t j    _ n t j    _ t j    _ xt t |  D]f }  j  r t j	 j
   t j d |  } t | _ n t j d |  }  j j |  | j   qs WWn  j     n Xd S(   s  Kicks off threads which add data from the generator into the queue.

        # Arguments
            workers: number of worker threads
            max_q_size: queue size (when full, threads could block on put())
            wait_time: time to sleep in-between calls to put()
        c          @ s   x  j  j   s yQ  j s3  j j     k  rU t  j  }   j j |   n t j	   Wq t
 k
 r  j  j     q Xq Wd  S(   N(   R   t   is_setR   R   t   qsizet   nextR   t   putt   timet   sleept	   ExceptionR4   (   t   generator_output(   t
   max_q_sizeR   t	   wait_time(    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   data_generator_taskZ  s    t   maxsizet   targetN(   R   t   multiprocessingt   QueueR   t   EventR   t	   threadingR   R   RS   t   seedt   Processt   Truet   daemont   ThreadR   R   Rc   Rd   (   R   t   workersR   R   R   R!   t   thread(    (   R   R   R   s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyRc   Q  s$    			
c         C@ s   |  j  d  k	 o |  j  j   S(   N(   R   R   R   (   R   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt
   is_running}  s    c         C@ s   |  j    r |  j j   n  xC |  j D]8 } | j   r& |  j rN | j   q^ | j |  q& q& W|  j r |  j d k	 r |  j j
   q n  g  |  _ d |  _ d |  _ d S(   s   Stop running threads and wait for them to exit, if necessary.

        Should be called by the same thread which called start().

        # Arguments
            timeout: maximum time to wait on thread.join()
        N(   R   R   R4   R   t   is_aliveR   t	   terminatet   joinR   R   t   close(   R   t   timeoutR   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyRd     s    				N(	   RE   t
   __module__t   __doc__t   FalseR   Rc   R   R   Rd   (    (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyR   @  s
   ,	t   Modelc           B@ sp  e  Z d  Z e e e d  Z d   Z d   Z d   Z e d d d e e e e e d d	 
 Z	 d d d
  Z
 d d d  Z e e e e d  Z e e d d d e d e e e e d d  Z d d e d  Z d d d  Z e e d  Z e d  Z d   Z e j d d e e e e d d e d d 
  Z e j d d e d   Z e j d d e d d   Z RS(   sL   The `Model` class adds training & evaluation routines to a `Container`.
    c   -      @ su  | p	 i  } t  j |    _ |   _ |   _ |   _ t | t  r xA | D]9 } |   j k rO t	 d | d t
   j    qO qO Wg  } x  j D]W } | | k r t j d | d | d d d n  | j t j | j |    q Wn t | t  ryt |  t   j  k rTt	 d t
 t   j   d	 t
 |    n  g  | D] }	 t j |	  ^ q[} n7 t j |  }
 g  t t   j   D] } |
 ^ q} |   _ g  | D] } t |  ^ q} g  } g    _ g    _ g    _ g    _ x t t |   D] } | | d) k r;| j |  q  j j   j |    j j   j |    j j   j |    j j   j |  qW  j   j d
 d) } | d) k rg    j D] } d) ^ q} n  t | t  s| g } n  | d) k r0g  t t   j   D] } d ^ q} nt | t  rxA | D]9 } |   j k rFt	 d | d t
   j    qFqFWg  } x   j D] } | j | j | d   qWn} t | t  rt |  t   j  k rt	 d t
 t   j   d t
 |    n  | } n t d t
 |  d   g  } g  } t | t  rtxA | D]9 } |   j k rXt	 d | d t
   j    qXqXWxt   j  D] \ } } | | k rd) } | j d)  n | | k rt	 d | d   n  | j |  d k r7t j  d d d | d  } | j d  n) t j  d d d | d  } | j d)  | j |  qWnt | t  rt |  t   j  k rt	 d t
 t   j   d t
 |    n  xt t   j   D] } | | k rd) } | j d)  nx | | }   j | } | d k r[t j  d d d | d  } | j d  n) t j  d d d | d  } | j d)  | j |  qWn x t   j  D] \ } } | | k r| j d)  | j d)  q| d k r| j t j  d d d | d   | j d  q| j t j  d d d | d   | j d)  qW|   _! g    _" xC t t   j   D], } | | k rx  j" j   j! |  qxqxWg    _# g    _$ x t t   j   D] } | | k r  j# j d)  q  j | }   j | } t j  d t |  d | d d t j%   j |  d t j&   j |   }   j# j |    j$ j |  qW|   _' d g   _( g    _) d) } x t t   j   D] } | | k rqn    j# | }   j | } | | } | | } | | } | | } | | | | |  } t   j  d k rm	  j) j |    j( j   j | d  n  | d) k r	| | } q| | | 7} qW| d) k r	  j s	t* d   q	d  } n  x   j D] }  | |  7} q	Wt+ |   j  }!   f d!   }" xt t   j   D]{} | | k r2
q
n    j# | }   j | } |! | }# x<|# D]4}$ |$ d" k s{
|$ d# k r  j | }% d) }& |% d$ d k s
  j | t j, k r
t- j. }& n+   j | t j/ k r
t- j0 }& n	 t- j1 }& t2 |&  }' |" | d# |' | | d
 | |  q]
t- j |$  }( t2 |(  }) |) | | d
 | | }* i |* |( j3 6}* x- t4 j5 |*  D] \ } }+ |" | | |+  qqWq]
Wq
W|   _6 |   _7 g    _8 x@ t t   j7   D]) } | | k r  j8 j | |  qqW|   _9 d)   _: d)   _; d)   _<   j= }, |, rht j>   d% k rR|, j? d& d'    qh|, j? d& d(    n  |,   _@ d) S(*   si  Configures the model for training.

        # Arguments
            optimizer: str (name of optimizer) or optimizer object.
                See [optimizers](/optimizers).
            loss: str (name of objective function) or objective function.
                See [losses](/losses).
                If the model has multiple outputs, you can use a different loss
                on each output by passing a dictionary or a list of losses.
            metrics: list of metrics to be evaluated by the model
                during training and testing.
                Typically you will use `metrics=['accuracy']`.
                To specify different metrics for different outputs of a
                multi-output model, you could also pass a dictionary,
                such as `metrics={'output_a': 'accuracy'}`.
            loss_weights: Optional list or dictionary specifying scalar
                coefficients (Python floats) to weight the loss contributions
                of different model outputs.
                If a list, it is expected to have a 1:1 mapping
                to the model's outputs. If a tensor, it is expected to map
                output names (strings) to scalar coefficients.
            sample_weight_mode: if you need to do timestep-wise
                sample weighting (2D weights), set this to `"temporal"`.
                `None` defaults to sample-wise weights (1D).
                If the model has multiple outputs, you can use a different
                `sample_weight_mode` on each output by passing a
                dictionary or a list of modes.
            **kwargs: when using the Theano backend, these arguments
                are passed into K.function. Ignored for Tensorflow backend.

        # Raises
            ValueError: In case of invalid arguments for
                `optimizer`, `loss`, `metrics` or `sample_weight_mode`.
        s#   Unknown entry in loss dictionary: "s%   ". Only expected the following keys: s   Output "s{   " missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to "s   " during training.t
   stackleveli   sW   When passing a list as loss, it should have one entry per model outputs. The model has s    outputs, but you passed loss=Ro   g      ?s+   Unknown entry in loss_weights dictionary: "s_   When passing a list as loss_weights, it should have one entry per model outputs. The model has s&    outputs, but you passed loss_weights=s+   Could not interpret loss_weights argument: s    - expected a list of dicts.s1   Unknown entry in sample_weight_mode dictionary: "s-   " missing from sample_weight_modes dictionaryRw   Rk   R#   t   _sample_weightsi   se   When passing a list as sample_weight_mode, it should have one entry per model outputs. The model has s,    outputs, but you passed sample_weight_mode=t   _targett   sparseRx   RI   t   _losss@   The model cannot be compiled because it has no loss to optimize.g        c         @ sT   t    j  d k r0   j |  j d | } n    j j |    j j |  d S(   s#   Helper function used in loop below.i   R!   N(   R   R,   t   output_layersR#   t   metrics_namesR   t   metrics_tensors(   t	   layer_numt   metric_namet   metric_tensor(   R   (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   append_metric  s    t   accuracyt   accit   theanot   keyc         S@ s   |  j  r |  j  S|  j S(   N(   R#   t	   auto_name(   R8   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   <lambda>  s    c         S@ s   |  j  S(   N(   R#   (   R8   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyR     s    N(A   R   R*   t	   optimizerR{   RI   t   loss_weightsR   R   R,   R   R   t   warningst   warnR   R   R   R   t   outputsR   t   loss_functionsRt   t   _feed_outputst   _feed_output_namest   _feed_output_shapest   _feed_loss_fnsR   t   internal_output_shapest   compute_maskR5   R   R   Rg   t   placeholdert   sample_weight_modest   _feed_sample_weight_modesR6   t   _feed_targetst	   is_sparseRx   R   R   R   t   RuntimeErrorRP   RC   t   metrics_modulet   binary_accuracyt   sparse_categorical_crossentropyt   sparse_categorical_accuracyt   categorical_accuracyRv   RE   t   sixt	   iteritemst
   total_losst   sample_weightst   _feed_sample_weightst   _function_kwargst   train_functiont   test_functiont   predict_functiont   trainable_weightsR   t   sortt   _collected_trainable_weights(-   R   R   RI   R   R   R{   t   kwargsR#   R   t   lt   loss_functionR!   Rr   t   weighted_lossest   skip_indicesR$   t   maskst   loss_weights_listR   R   t   weightt   modeR   R   R   Rm   Rn   t   weighted_lossR2   Ro   t   loss_weightt   output_losst   loss_tensorRN   R   RO   t   metrict   output_shapet   acc_fnt	   masked_fnt	   metric_fnt   masked_metric_fnt   metric_resultt   tensorR   (    (   R   s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   compile  s   $			&%(					+ 	


				
		



			
&	&								c         C@ s   t  |  d  s t d   n  |  j d  k r |  j |  j |  j } |  j ry t t	 j
   t  ry | t	 j
   g 7} n  |  j j |  j |  j |  j  } |  j | } t	 j | |  j g |  j d | |  j |  _ n  d  S(   NR   s,   You must compile your model before using it.t   updates(   R   R   R   R   t   _feed_inputsR   R   t   uses_learning_phaseR   Rg   t   learning_phaseRQ   R   t   get_updatesR   t   constraintsR   R   t   functionR   R   (   R   R5   t   training_updatesR   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _make_train_function  s    		c         C@ s   t  |  d  s t d   n  |  j d  k r |  j |  j |  j } |  j ry t t	 j
   t  ry | t	 j
   g 7} n  t	 j | |  j g |  j d |  j |  j |  _ n  d  S(   NR   s,   You must compile your model before using it.R   (   R   R   R   R   R   R   R   R   R   Rg   R   RQ   R   R   R   t   state_updatesR   (   R   R5   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _make_test_function  s    	c         C@ s   t  |  d  s d  |  _ n  |  j d  k r |  j rb t t j   t  rb |  j t j   g } n	 |  j } t	 |  d i   } t j
 | |  j d |  j | |  _ n  d  S(   NR   R   R   (   R   R   R   R   R   Rg   R   RQ   R   t   getattrR   R   R   (   R   R5   R   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _make_predict_function  s    			i    id   i   i    c         C@ s  t  } | rN |	 rN t } | rN t d | d j d |	 d j d f  qN n  | r{ t | d d  r{ | d j d } n | } d } t j |  } t j   |  _	 t j
   g | p g  |  j	 g } | r | t j   g 7} n  t j |  } | p g  } t |  d  r#|  j r#|  j } n |  } | j |  | j i | d 6| d 6| d 6| d	 6| d
 6| pkg  d 6 | j   t  | _ x | D] } |	 | _ qWx>t | |  D]-} | j |  |
 d k rt | |  } n |
 rt j j |  n  t | |  } i  } xt |  D]\ } \ } } | | | !} yG t | d t  rrt | d  |  | d g } n t | |  } Wn t k
 rt d   n Xi  } | | d <t |  | d <| j | |  | |  } t | t   s| g } n  x' t! | |  D] \ } } | | | <q	W| j" | |  | t |  d k r| r|  j# | |	 d | d	 d } t | t   s| g } n  x. t! | |  D] \ } } | | d | <qWqqqW| j$ | |  | j rPqqW| j%   |  j	 S(   s  Abstract fit function for `f(ins)`.

        Assume that f returns a list, labeled by out_labels.

        # Arguments
            f: Keras function returning a list of tensors
            ins: list of tensors to be fed to `f`
            out_labels: list of strings, display names of
                the outputs of `f`
            batch_size: integer batch size
            epochs: number of times to iterate over the data
            verbose: verbosity mode, 0, 1 or 2
            callbacks: list of callbacks to be called during training
            val_f: Keras function to call for validation
            val_ins: list of tensors to be fed to `val_f`
            shuffle: whether to shuffle the data at the beginning of each epoch
            callback_metrics: list of strings, the display names of the metrics
                passed to the callbacks. They should be the
                concatenation of list the display names of the outputs of
                 `f` and the list of display names of the outputs of `f_val`.
            initial_epoch: epoch at which to start training
                (useful for resuming a previous training run)

        # Returns
            `History` object.
        s+   Train on %d samples, validate on %d samplesi    R   i   t   callback_modelRW   t   epochst   samplest   verboset   do_validationR   t   batchisP   TypeError while preparing batch. If using HDF5 input data, pass shuffle="batch".R^   i   t   val_(&   R   R   t   printR   R   R   t   aranget   cbkst   Historyt   historyt
   BaseLoggert   ProgbarLoggert   CallbackListR  t	   set_modelt
   set_paramst   on_train_begint   stop_trainingt   validation_dataR   t   on_epoch_beginRZ   RS   RT   R`   R   R   R\   Re   R   R   t   on_batch_beginR   R   t   on_batch_endt
   _test_loopt   on_epoch_endt   on_train_end(   R   t   ft   inst
   out_labelsRW   R  R  R   t   val_ft   val_insRT   t   callback_metricst   initial_epochR  t   num_train_samplesRV   R  t   cbkt   epocht   batchest
   epoch_logst   batch_indext   batch_startt	   batch_endt	   batch_idst	   ins_batcht
   batch_logst   outsR   t   ot   val_outs(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt	   _fit_loop  s    *#	
	!
		
c      	   C@ s  | r- t  | d d  r- | d j d } n | } d } g  } | d k r] t d |  } n  t | |  } t j |  }	 x=t |  D]/\ }
 \ } } |	 | | !} | r t | d t  r t	 | d  |  | d g } n t	 | |  } | |  } t | t
  s| g } n  |
 d k rmxG | D]< } | f | j d } | j t j | d t j    q*Wn  x+ t |  D] \ } } | | | | | +qzW| d k r | j |  q q Wt |  d k r| d S| S(   s  Abstract method to loop over some data in batches.

        # Arguments
            f: Keras function returning a list of tensors.
            ins: list of tensors to be fed to `f`.
            batch_size: integer batch size.
            verbose: verbosity mode.

        # Returns
            Array of predictions (if the model has a single output)
            or list of arrays of predictions
            (if the model has multiple outputs).
        i    R   i   i   R   iRx   (   R   R   R   R`   R   R  R   R   R\   Re   R   R   t   zerosRg   Ri   t   updateR   (   R   R  R  RW   R  R  R/  t   progbarR'  RV   R)  R*  R+  R,  R-  t
   batch_outst	   batch_outR   R$   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _predict_loop  s8    !)c      	   C@ s  | r- t  | d d  r- | d j d } n | } d } g  } | d k r] t d |  } n  t | |  } t j |  }	 xJt |  D]<\ }
 \ } } |	 | | !} t | d t  r t	 | d  |  | d g } n t	 | |  } | |  } t | t
  rr|
 d k r8x$ t |  D] } | j d  qWn  xm t |  D]& \ } } | | c | t |  7<qEWn6 |
 d k r| j d  n  | d c | t |  7<| d k r | j |  q q Wx* t t |   D] } | | c | :<qWt |  d k r| d S| S(   s4  Abstract method to loop over some data in batches.

        # Arguments
            f: Keras function returning a list of tensors.
            ins: list of tensors to be fed to `f`.
            batch_size: integer batch size.
            verbose: verbosity mode.

        # Returns
            Scalar 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.
        i    R   i   i   R   ig        (   R   R   R   R`   R   R  R   R   R\   Re   R   R   R   R4  R   (   R   R  R  RW   R  R  R/  R5  R'  RV   R)  R*  R+  R,  R-  R6  R7  R$   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyR    s>    !!c         C@ s  t  |  d  s t d   n  g  } x t |  j |  j  D]k \ } }	 |	 j d k rm | j | d  d  q: t t |	 j d   d  k r | j d   q: | j |  q: Wt
 | |  j |  j d t d d } t
 | |  j | d t d d	 } t | |  j  }
 t | |  j  } g  t | |
 | |  j  D]' \ } } } } t | | | |  ^ q+}
 t | | |
  t | |  j |  j  |  j r| r| d
 j d
 | d
 k rt d t | d
 j d
  d   qn  | | |
 f S(   NR   sW   You must compile a model before training/testing. Use `model.compile(optimizer, loss)`.R   ii   R   R    s   model inputs   model targeti    sz   In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: s    samples(   i   (   R   R   R   R   R   RE   R   R  R   R   R)   t   _feed_input_namest   _feed_input_shapesR   R   R3   R1   R   R~   RA   RL   t   statefulR   R   R   (   R   R8   R:   R2   R0   R   RW   RG   R   t   loss_fnR   t   class_weightst   reft   swt   cwR   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   _standardize_user_data  s@    "			C
(g        c   !      K@ s  d | k r1 t  j d d d | j d  } n  | rP t d t |    n  |  j | | d | d |
 d t d	 | \ } } } | rxt } t |  d k r | \ } } d } n: t |  d
 k r | \ } } } n t
 d t |    |  j | | d | d t d	 | \ } } } |  j   |  j } |  j rgt t j   t  rg| | | d g } q| | | } n| rd | k  od k  n rt } t t | d  d |  } t | d |  t | |  } } t | d |  t | |  } } t | d |  t | |  } } |  j   |  j } |  j rnt t j   t  rn| | | d g } q| | | } n t } d } d } |  j rt t j   t  r| | | d g } n | | | } |  j   |  j } |  j } g  } xp t |  D]b \ } } | } | j |  d k rZ| |  j |  } | d t | d  7} n  | j |  qW| } | rt j |  g  | D] } d | ^ q}  n t j |  }  |  j | | d | d	 | d | d | d | d | d | d |	 d |  d | 
S(   s  Trains the model for a fixed number of epochs (iterations on a dataset).

        # Arguments
            x: Numpy array of training data,
                or list of Numpy arrays if the model has multiple inputs.
                If all inputs in the model are named,
                you can also pass a dictionary
                mapping input names to Numpy arrays.
            y: Numpy array of target data,
                or list of Numpy arrays if the model has multiple outputs.
                If all outputs in the model are named,
                you can also pass a dictionary
                mapping output names to Numpy arrays.
            batch_size: integer. Number of samples per gradient update.
            epochs: integer, the number of times to iterate
                over the training data arrays.
                verbose: 0, 1, or 2. Verbosity mode.
                0 = silent, 1 = verbose, 2 = one log line per epoch.
            callbacks: list of callbacks to be called during training.
                See [callbacks](/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.
            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.
                This could be a tuple (x_val, y_val)
                or a tuple (x_val, y_val, val_sample_weights).
            shuffle: boolean, whether to shuffle the training data
                before each epoch.
            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.
            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().
            initial_epoch: epoch at which to start training
                (useful for resuming a previous training run)

        # Returns
            A `History` instance. Its `history` attribute contains
            all information collected during training.

        # Raises
            ValueError: In case of mismatch between the provided input data
                and what the model expects.
        t   nb_epochs;   The `nb_epoch` argument in `fit` has been renamed `epochs`.R   i   s    Unrecognized keyword arguments: R2   R0   R   RW   i   s   When passing validation_data, it must contain 2 (x_val, y_val) or 3 (x_val, y_val, val_sample_weights) items, however it contains %d itemsg        g      ?i    i   R!   R	  R  R  R  R   R   R!  RT   R"  R#  N(   R   R   t   popR   R   RA  R   R   R   R   R   R   R   R   R   Rg   R   RQ   Re   R   R   R   R   t   countR   RM   R2  (!   R   R8   R:   RW   R  R  R   t   validation_splitR  RT   R0   R2   R#  R   R   R  t   val_xt   val_yt   val_sample_weightt   val_sample_weightsR   R!  t   split_atR  R  R  t   deduped_out_labelsR$   t   labelt	   new_labelt   dup_idxt   nR"  (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   fit(  s    H			
	"""
	
		-c   	   	   C@ s   |  j  | | d | d t d | \ } } } |  j rd t t j   t  rd | | | d g } n | | | } |  j   |  j } |  j	 | | d | d | S(   s  Returns the loss value & metrics values for the model in test mode.

        Computation is done in batches.

        # Arguments
            x: Numpy array of test data,
                or list of Numpy arrays if the model has multiple inputs.
                If all inputs in the model are named,
                you can also pass a dictionary
                mapping input names to Numpy arrays.
            y: Numpy array of target data,
                or list of Numpy arrays if the model has multiple outputs.
                If all outputs in the model are named,
                you can also pass a dictionary
                mapping output names to Numpy arrays.
            batch_size: integer. Number of samples per gradient update.
            verbose: verbosity mode, 0 or 1.
            sample_weight: Array of weights to weight the contribution
                of different samples to the loss and metrics.

        # 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.
        R2   R   RW   g        R  (
   RA  R   R   R   Rg   R   RQ   R   R   R  (	   R   R8   R:   RW   R  R2   R   R  R  (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   evaluate  s    	
	c      	   C@ s   t  | |  j |  j d t } |  j r | d j d | k r | d j d | d k r t d t | d j d  d t |  d   q n  |  j r t	 t
 j   t  r | d g } n | } |  j   |  j } |  j | | d | d | S(	   s  Generates output predictions for the input samples.

        Computation is done in batches.

        # Arguments
            x: the input data, as a Numpy array
                (or list of Numpy arrays if the model has multiple outputs).
            batch_size: integer.
            verbose: verbosity mode, 0 or 1.

        # 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.
        R   i    sz   In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: s    samples. Batch size: t   .g        RW   R  (   R)   R9  R:  R   R;  R   R   R   R   R   Rg   R   RQ   R  R   R8  (   R   R8   RW   R  R  R  (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   predict  s    			26
	c      	   C@ s   |  j  | | d | d | d t \ } } } |  j rd t t j   t  rd | | | d g } n | | | } |  j   |  j |  } t	 |  d k r | d S| S(   s  Runs a single gradient update on a single batch of data.

        # Arguments
            x: Numpy array of training data,
                or list of Numpy arrays if the model has multiple inputs.
                If all inputs in the model are named,
                you can also pass a dictionary
                mapping input names to Numpy arrays.
            y: Numpy array of target data,
                or list of Numpy arrays if the model has multiple outputs.
                If all outputs in the model are named,
                you can also pass a dictionary
                mapping output names to Numpy arrays.
            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().
            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.

        # 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.
        R2   R0   R   g      ?i   i    (
   RA  R   R   R   Rg   R   RQ   R   R   R   (   R   R8   R:   R2   R0   R   R  R   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   train_on_batch&  s    $	
c         C@ s   |  j  | | d | d t \ } } } |  j r^ t t j   t  r^ | | | d g } n | | | } |  j   |  j |  } t	 |  d k r | d S| S(   sl  Test the model on a single batch of samples.

        # Arguments
            x: Numpy array of test data,
                or list of Numpy arrays if the model has multiple inputs.
                If all inputs in the model are named,
                you can also pass a dictionary
                mapping input names to Numpy arrays.
            y: Numpy array of target data,
                or list of Numpy arrays if the model has multiple outputs.
                If all outputs in the model are named,
                you can also pass a dictionary
                mapping output names to Numpy arrays.
            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().

        # 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.
        R2   R   g        i   i    (
   RA  R   R   R   Rg   R   RQ   R   R   R   (   R   R8   R:   R2   R   R  R   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   test_on_batchY  s    	
c         C@ s   t  | |  j |  j  } |  j rG t t j   t  rG | d g } n | } |  j   |  j	 |  } t
 |  d k r | d S| S(   s   Returns predictions for a single batch of samples.

        # Arguments
            x: Input samples, as a Numpy array.

        # Returns
            Numpy array(s) of predictions.
        g        i   i    (   R)   R9  R:  R   R   Rg   R   RQ   R  R   R   (   R   R8   R  R   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   predict_on_batch  s    	
i
   c   (      C@ s  d } | } t  |  } |  j   | r5 |  j   n  t | d  pP t | d  } | ro | ro t d   n  |  j } | g  | D] } d | ^ q } t j   |  _ t j	   g | p g  |  j g } | r | t j
 d d  g 7} n  t j |  } t |  d  r |  j r |  j } n |  } | j |  | j i | d	 6| d 6| d
 6| d 6| d 6 | j   | r | r t |  d k r| \ } } d } n: t |  d k r| \ } } } n t d t |    |  j | | |  \ } } } x$ | D] } | | | g | _ q Wn  d } z1t | d | } | j d |	 d |
  t | _ x| | k  rU| j |  d } d } x| | k  r*d } x? | j   r| j j   s| j j   } Pqt j |  qWt | d  st d t |    n  t |  d k r(| \ } } d }  n: t |  d k rL| \ } } }  n t d t |    i  }! t  | t!  r| d j" d }" n< t  | t#  rt! | j$    d j" d }" n | j" d }" | |! d <|" |! d <| j% | |!  |  j& | | d |  d | }# t  |# t!  s$|# g }# n  x' t' | |#  D] \ }$ }% |% |! |$ <q4W| j( | |!  i  }& | d 7} | d 7} | | k r| r| r|  j) | | d |	 d |
 d | }' n$ |  j* | | d |" d | d
 d }' t  |' t!  s|' g }' n  x. t' | |'  D] \ }$ }% |% |& d |$ <qWqqW| j+ | |&  | d 7} | j r]Pq]q]WWd | d k	 rs| j,   n  X| j-   |  j S(   s  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.

        # Arguments
            generator: a generator.
                The output of the generator must be either
                - a tuple (inputs, targets)
                - a tuple (inputs, targets, sample_weights).
                All arrays should contain the same number of samples.
                The generator is expected to loop over its data
                indefinitely. An epoch finishes when `steps_per_epoch`
                samples 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 unique samples if your dataset
                divided by the batch size.
            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.
            class_weight: dictionary mapping class indices to a weight
                for the class.
            max_q_size: maximum size for the generator queue
            workers: maximum number of processes to spin up
                when using process based threading
            pickle_safe: if True, use process based threading.
                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.
            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.
        g{Gz?R   t   __next__s\   When using a generator for validation data, you must specify a value for `validation_steps`.R	  t
   count_modet   stepsR  R  R  R  R   i   i   sb   validation_data should be a tuple `(val_x, val_y, val_sample_weight)` or `(val_x, val_y)`. Found: R   R   R   i    Ra   sR   output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: R  R^   R2   R0   i   RW   N(.   t   boolR   R   R   R   R   R  R  R  R  R  R  R  R  R  R  R   R   R   RA  R  R   Rc   R   R  R  R   R   t   emptyR*   R   R   R   R   R   R   t   valuesR  RT  R   R  t   evaluate_generatorRQ  R  Rd   R  ((   R   R   t   steps_per_epochR  R  R   R  t   validation_stepsR0   R   R   R   R#  R   R&  R  t   val_genR  RO  R"  R  RF  RG  RH  RI  R%  t   enqueuert
   steps_doneR)  R   R8   R:   R2   R.  RW   R/  R   R0  R(  R1  (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   fit_generator  s    R
	!#	
			 

	

		
	
c         C@ sv  |  j    d } d } g  } g  }	 d }
 zt | d | }
 |
 j d | d |  xy| | k  rd } x? |
 j   r |
 j j   s |
 j j   } Pqk t j	 |  qk Wt
 | d  s t d t |    n  t |  d k r | \ } } d } n: t |  d	 k r| \ } } } n t d t |    |  j | | d
 | } t | t  rmt | d  } n: t | t  rt t | j    d  } n t |  } | j |  | d 7} |	 j |  qV WWd |
 d k	 r|
 j   n  Xt | t  st j t j |  d |	 Sg  } xM t t |   D]9 } | j t j g  | D] } | | ^ qJd |	  q1W| Sd S(   s4  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)
            steps: Total number of steps (batches of samples)
                to yield from `generator` before stopping.
            max_q_size: maximum size for the generator queue
            workers: maximum number of processes to spin up
                when using process based threading
            pickle_safe: if True, use process based threading.
                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 the generator yields
                data in an invalid format.
        i    g{Gz?R   R   R   Ra   sN   output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: i   i   R2   i   NR7   (   R   R   R   Rc   R   R   R[  R*   R   R   R   R   R   R   RU  R   R   R   R\  R   Rd   R   t   averageR   R   (   R   R   RY  R   R   R   Rb  R   t   all_outst   batch_sizesRa  R   R8   R:   R2   R/  RW   t   averagesR$   t   out(    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyR]    sZ    "
	
)c         C@ s  |  j    d } d } g  }	 d }
 zt | d | }
 |
 j d | d |  | d k rk t d |  } n  xp| | k  rd } x? |
 j   r |
 j j   s |
 j j   } Pq t	 j
 |  q Wt | t  r/t |  d k r | \ } } q5t |  d	 k r| \ } } } q5t d
 t |    n | } |  j |  } t | t  s_| g } n  |	 sx | D] } |	 j g   qlWn  x+ t |  D] \ } } |	 | j |  qW| d 7} | d k rn | j |  qn qn WWd |
 d k	 r|
 j   n  Xt |	  d k r:| d k r&|	 d d St j |	 d  Sn  | d k r]g  |	 D] } | ^ qMSg  |	 D] } t j |  ^ qdSd S(   sb  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.
            steps: Total number of steps (batches of samples)
                to yield from `generator` before stopping.
            max_q_size: Maximum size for the generator queue.
            workers: Maximum number of processes to spin up
                when using process based threading
            pickle_safe: If `True`, use process based threading.
                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.
        i    g{Gz?R   R   R   i   R   i   i   sR   output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: N(   R  R   R   Rc   R   R   R   R[  R*   R   R   R   t   tupleR   R   R   RV  R   R   R   R4  Rd   R   t   concatenate(   R   R   RY  R   R   R   R  Rb  R   Re  Ra  R5  R   R8   R!   R/  Rh  R$   (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   predict_generator  sZ     

(   RE   R   R   R   R   R   R   R  R   R2  R8  R  RA  RP  RQ  RS  RT  RU  RV  R	   t    legacy_generator_methods_supportR   Rc  R]  Rk  (    (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyR     s`    ?					|4;*,,2*	_(/   t
   __future__R    R   R   RM   R   t   numpyR   R   R   R   R   t   ImportErrorR   t   topologyR   R
   R   Rg   R   R   R   R   t   utils.generic_utilsR   R   R  t   legacyR	   R   R   R)   R/   R1   R3   RA   RL   RP   RZ   R`   Re   Rt   Rv   R~   t   objectR   R   (    (    (    s4   /tmp/pip-build-isqEY4/keras/keras/engine/training.pyt   <module>   sL   k	/			)	2	%		%	5	(R[