
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 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 y d  d l Z Wn e k
 rAd Z n Xe! d  Z" d d  Z# d d  Z$ d d  Z% d d  Z& d e f d     YZ' d S(   i    (   t   absolute_import(   t   print_functionNi   (   t   backend(   t
   optimizers(   t   layers(   t   ask_to_proceed_with_overwrite(   t   Model(   t   topology(   t   Layer(   t   Input(   t   models(   t
   interfacesc         C@ ss  t  d k r t d   n  d   } d d l m } | rf t j j |  rf t |  } | sf d Sn  t  j	 | d  } t
 |  j d  | j d <t j   j d  | j d	 <t j i |  j j d
 6|  j   d 6d | j d  | j d <| j d  } t j |   rt j |   } n	 |  j } t j | |  t |  d  r[t |  j t j  rlt  j! d  q[t j i i |  j j j d
 6|  j j   d 6d 6|  j" d 6|  j# d 6|  j$ d 6|  j% d 6d | j d  | j d <t& |  j d  }	 |	 r[| j d  }
 t j' |	  } g  } x t( t) |	 |   D] \ } \ } } t j   d k rt | d  r| j* d k rt
 | j*  } qd t
 |  } n: t | d  r| j* rt
 | j*  } n d t
 |  } | j+ | j d   q2W| |
 j d <x[ t) | |  D]G \ } } |
 j, | | j- d | j. } | j- sJ| | d <q
| | (q
Wq[n  | j/   | j0   d S(    s  Save a model to a HDF5 file.

    The saved model contains:
        - the model's configuration (topology)
        - the model's weights
        - the model's optimizer's state (if any)

    Thus the saved model can be reinstantiated in
    the exact same state, without any of the code
    used for model definition or training.

    # Arguments
        model: Keras model instance to be saved.
        filepath: String, path where to save the model.
        overwrite: Whether we should overwrite any existing
            model at the target location, or instead
            ask the user with a manual prompt.

    # Raises
        ImportError: if h5py is not available.
    s   `save_model` requires h5py.c         S@ s   t  |  d  r- i |  j j d 6|  j   d 6St |   j t j k rO |  j   St |   rb |  j St |   j t j k r |  j St	 d |    d S(   s  Serialize any object to a JSON-serializable structure.

        # Arguments
            obj: the object to serialize

        # Returns
            JSON-serializable structure representing `obj`.

        # Raises
            TypeError: if `obj` cannot be serialized.
        t
   get_configt
   class_namet   configs   Not JSON Serializable:N(
   t   hasattrt	   __class__t   __name__R   t   typet
   __module__t   npt   itemt   callablet	   TypeError(   t   obj(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   get_json_type8   s    
i   (   t   __version__Nt   wt   utf8t   keras_versionR   R   R   t   defaultt   model_configt   model_weightst	   optimizers;  TensorFlow optimizers do not make it possible to access optimizer attributes or optimizer state after instantiation. As a result, we cannot save the optimizer as part of the model save file.You will have to compile your model again after loading it. Prefer using a Keras optimizer instead (see keras.io/optimizers).t   optimizer_configt   losst   metricst   sample_weight_modet   loss_weightst   training_configt   weightst   optimizer_weightst   theanot   names	   /variablet   param_t   weight_namest   dtype(    (1   t   h5pyt   Nonet   ImportErrort    R   t   ost   patht   isfileR   t   Filet   strt   encodet   attrst   KR   t   jsont   dumpsR   R   R   t   create_groupt   legacy_modelst   needs_legacy_supportt   legacy_sequential_layersR   R   t   save_weights_to_hdf5_groupR   t
   isinstanceR!   R   t   TFOptimizert   warningst   warnR#   R$   R%   R&   t   getattrt   batch_get_valuet	   enumeratet   zipR+   t   appendt   create_datasett   shapeR.   t   flusht   close(   t   modelt   filepatht	   overwriteR   R   t   proceedt   ft   model_weights_groupt   model_layerst   symbolic_weightst   optimizer_weights_groupt   weight_valuesR-   t   iR   t   valR+   t
   param_dset(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt
   save_model   st    	 		

	


(		
c         @ s.  t  d k r t d   n    s* i    n    f d   } t  j |  d d } | j j d  } | d k r{ t d   n  t j | j	 d   } t
 | d   } t j | d	 | j  | j j d
  } | d k r t j d  | j   | St j | j	 d   } | d } t j | d   } | | d  }	 | | d  }
 | d } | d } | j d | d |	 d |
 d | d |  d | k r t | t  r| j j   n
 | j   | d } g  | j d D] } | j	 d  ^ q} g  | D] } | | ^ q} | j j |  n  | j   | S(   sc  Loads a model saved via `save_model`.

    # Arguments
        filepath: String, path to the saved model.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    # Returns
        A Keras model instance. If an optimizer was found
        as part of the saved model, the model is already
        compiled. Otherwise, the model is uncompiled and
        a warning will be displayed.

    # Raises
        ImportError: if h5py is not available.
        ValueError: In case of an invalid savefile.
    s   `save_model` requires h5py.c         @ s   t  |  t  rW g  } x; |  D]3 } |   k rB | j   |  q | j |  q W| St  |  t  r i  } xA |  j   D]3 \ } } |   k r   | | | <qy | | | <qy W| S|    k r   |  S|  S(   s
  Handles custom object lookup.

        # Arguments
            obj: object, dict, or list.

        # Returns
            The same structure, where occurences
                of a custom object name have been replaced
                with the custom object.
        (   RB   t   listRJ   t   dictt   items(   R   t   deserializedt   valuet   key(   t   custom_objects(    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   convert_custom_objects   s"    t   modet   rR   s   No model found in config file.s   utf-8Rc   R    R'   s`   No training configuration found in save file: the model was *not* compiled. Compile it manually.R"   R#   R$   R%   R&   R!   R)   R-   R   N(   R/   R0   R1   R6   R9   t   gett
   ValueErrorR;   t   loadst   decodet   model_from_configR   t   load_weights_from_hdf5_groupR   RD   RE   RN   R   t   deserializet   compileRB   t
   SequentialRO   t   _make_train_functionR!   t   set_weights(   RP   Rc   Rd   RS   R   RO   R'   R"   R!   R#   R$   R%   R&   RW   t   nt   optimizer_weight_namest   optimizer_weight_values(    (   Rc   s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt
   load_model   sP    	

	



)
c         C@ s1   t  |  t  r t d   n  t j |  d | S(   sK  Instantiates a Keras model from its config.

    # Arguments
        config: Configuration dictionary.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    # Returns
        A Keras model instance (uncompiled).
    sm   `model_fom_config` expects a dictionary, not a list. Maybe you meant to use `Sequential.from_config(config)`?Rc   (   RB   R]   R   t   layer_moduleRm   (   R   Rc   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyRk     s    c         C@ s"   t  j |   } t j | d | S(   s{  Parses a yaml model configuration file and returns a model instance.

    # Arguments
        yaml_string: YAML string encoding a model configuration.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    # Returns
        A Keras model instance (uncompiled).
    Rc   (   t   yamlt   loadRv   Rm   (   t   yaml_stringRc   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   model_from_yaml(  s    c         C@ s"   t  j |   } t j | d | S(   s{  Parses a JSON model configuration file and returns a model instance.

    # Arguments
        json_string: JSON string encoding a model configuration.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    # Returns
        A Keras model instance (uncompiled).
    Rc   (   R;   Ri   Rv   Rm   (   t   json_stringRc   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   model_from_json8  s    Ro   c           B@ sx  e  Z d  Z d. d. d  Z d   Z d   Z d. d. d  Z d. d  Z d. d  Z	 e
 d    Z e
 d    Z d	   Z e
 d
    Z e j d    Z e
 d    Z e
 d    Z e
 d    Z e
 d    Z d   Z e
 d    Z d   Z e
 d    Z e
 d    Z d   Z d   Z e d  Z e d  Z d. d. d  Z d d d d. d d. e d. d. d d 
 Z  d d d. d   Z! d d d!  Z" d"   Z# d. d. d#  Z$ d. d$  Z% d d d%  Z& d d d&  Z' e( j) d d d. d. d. d. d d e d d' 
  Z* e( j) d d e d(   Z+ e( j) d d e d d)   Z, d*   Z- e. d+    Z/ d,   Z0 e. d. d-   Z1 RS(/   s  Linear stack of layers.

    # Arguments
        layers: list of layers to add to the model.

    # Note
        The first layer passed to a Sequential model
        should have a defined input shape. What that
        means is that it should have received an `input_shape`
        or `batch_input_shape` argument,
        or for some type of layers (recurrent, Dense...)
        an `input_dim` argument.

    # Example

        ```python
            model = Sequential()
            # first layer must have a defined input shape
            model.add(Dense(32, input_dim=500))
            # afterwards, Keras does automatic shape inference
            model.add(Dense(32))

            # also possible (equivalent to the above):
            model = Sequential()
            model.add(Dense(32, input_shape=(500,)))
            model.add(Dense(32))

            # also possible (equivalent to the above):
            model = Sequential()
            # here the batch dimension is None,
            # which means any batch size will be accepted by the model.
            model.add(Dense(32, batch_input_shape=(None, 500)))
            model.add(Dense(32))
        ```
    c         C@ s   g  |  _  d  |  _ g  |  _ g  |  _ t |  _ d  |  _ g  |  _ g  |  _	 t
 |  _ | sy d } | t t j |   } n  | |  _ | r x | D] } |  j |  q Wn  d  S(   Nt   sequential_(   R   R0   RO   t   inputst   outputst   Truet
   _trainablet   _initial_weightst   inbound_nodest   outbound_nodest   Falset   builtR7   R:   t   get_uidR+   t   add(   t   selfR   R+   t   prefixt   layer(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   __init__m  s     										c         C@ sI  t  | t  s( t d t |    n  |  j s| j s t | d  sX t d   n  t d | j	 d | j
 d | j d  } | |  n  t | j  d k r t d	 | j d
 t t | j   d   n  t | j d j  d k r t d   n  | j d j d g |  _ t j |  j d  |  _ t j d |  d g  d g  d g  d |  j d |  j d g  |  j D] } d ^ qnd d g d g  |  j D] } | j ^ qd |  j d j g  
nm | |  j d  } t  | t  rt d   n  | g |  _ |  j |  j d _ |  j d j g |  j d _ |  j j |  t |  _ d S(   s  Adds a layer instance on top of the layer stack.

        # Arguments
            layer: layer instance.

        # Raises
            TypeError: If `layer` is not a layer instance.
            ValueError: In case the `layer` argument does not
                know its input shape.
            ValueError: In case the `layer` argument has
                multiple output tensors, or is already connected
                somewhere else (forbidden in `Sequential` models).
        s;   The added layer must be an instance of class Layer. Found: t   batch_input_shapes`   The first layer in a Sequential model must get an `input_shape` or `batch_input_shape` argument.t   batch_shapeR.   R+   t   _inputi   sg   A layer added to a Sequential model must not already be connected somewhere else. Model received layer s    which has s"    pre-existing inbound connections.i    su   All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.t   outbound_layert   inbound_layerst   node_indicest   tensor_indicest   input_tensorst   output_tensorst   input_maskst   output_maskst   input_shapest   output_shapesN(   RB   R   R   R7   R   R   R   Rh   R	   R   R.   R+   t   lenR   R   t   get_source_inputsR~   t   NodeR0   t   _keras_shapeR]   R   R   RJ   R   R   (   R   R   t   xt   _t   output_tensor(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     sH    		!			c         C@ s   |  j  s t d   n  |  j  j   |  j  sL g  |  _ g  |  _ g  |  _ nV g  |  j  d _ |  j  d j g |  _ |  j |  j d _ |  j d j g |  j d _	 t
 |  _ d S(   s{   Removes the last layer in the model.

        # Raises
            TypeError: if there are no layers in the model.
        s!   There are no layers in the model.ii    N(   R   R   t   popR   R   R   t   outputR   R   R   R   R   (   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    				c         C@ s/   |  j  d k r |  j   n  |  j  j | |  S(   s{  Retrieve a layer that is part of the model.

        Returns a layer based on either its name (unique)
        or its index in the graph. Indices are based on
        order of horizontal graph traversal (bottom-up).

        # Arguments
            name: string, name of layer.
            index: integer, index of layer.

        # Returns
            A layer instance.
        N(   RO   R0   t   buildt	   get_layer(   R   R+   t   index(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ s/   |  j  d  k r |  j   n  |  j  j | |  S(   N(   RO   R0   R   t   call(   R   R~   t   mask(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ sd  |  j  s |  j r# t d   n  t |  j  |  j d d |  j d |  _ |  j |  j _ |  j j |  _ |  j j |  _ |  j j	 |  _	 |  j j
 |  _
 |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  |  j _ t |  _ d  S(   NsH   Sequential model cannot be built: model is empty. Add some layers first.i    R+   t   _model(   R~   R   R   R   R+   RO   t	   trainablet   supports_maskingt   _output_mask_cachet   _output_tensor_cachet   _output_shape_cachet   input_layerst   input_layers_node_indicest   input_layers_tensor_indicest   output_layerst   output_layers_node_indicest   output_layers_tensor_indicest   nodes_by_deptht   container_nodest   output_namest   input_namest   _feed_input_namest   _feed_inputst   callback_modelR   R   (   R   t   input_shape(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s.    c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   uses_learning_phase(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   #  s    c         C@ sQ  g  } |  j  rMt |  j  d t j  r |  j  d } x | j  D] } t | d  r x | j D]" } | | k r^ | j |  q^ q^ Wq? t | d  r xL | j  D]" } | | k r | j |  q q Wq? | | k r? | j |  q? q? Wn* |  j  d | k r| j |  j  d  n  x4 |  j  d D]" } | | k r$| j |  q$q$Wn  | S(   Ni    t   _flattened_layersR   i   (   R   RB   t   legacy_layerst   MergeR   R   RJ   (   R   R   t   mergeR   t   sublayer(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   )  s*    	c         C@ s4   g  } x' |  j  D] } | t | | g   7} q W| S(   N(   R   RF   (   R   t   attrt	   all_attrsR   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   _gather_list_attrD  s    c         C@ s   |  j  S(   N(   R   (   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   J  s    c         C@ s%   |  j  r | |  j  _ n  | |  _ d  S(   N(   RO   R   R   (   R   Ra   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   N  s    	c         C@ s   |  j  s g  S|  j d  S(   Nt   trainable_weights(   R   R   (   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   T  s    	c         C@ s3   |  j  d  } |  j s/ |  j  d  } | | S| S(   Nt   non_trainable_weightsR   (   R   R   (   R   R(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   [  s
    	c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   updates(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   d  s    c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   state_updates(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   j  s    c         C@ s,   |  j  d  k r |  j   n  |  j  j |  S(   N(   RO   R0   R   t   get_updates_for(   R   R~   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   p  s    c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   losses(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   u  s    c         C@ s,   |  j  d  k r |  j   n  |  j  j |  S(   N(   RO   R0   R   t   get_losses_for(   R   R~   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   {  s    c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   regularizers(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ s&   |  j  d  k r |  j   n  |  j  j S(   N(   RO   R0   R   t   constraints(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ su   t  j |   rL t  j |   } g  } x! | D] } | j | j    q+ W| S|  j d k rh |  j   n  |  j j   S(   s   Retrieves the weights of the model.

        # Returns
            A flat list of Numpy arrays
            (one array per model weight).
        N(   R>   R?   R@   RJ   t   get_weightsRO   R0   R   (   R   R   R(   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ s   t  j |   r\ t  j |   } x; | D]0 } t | j  } | j | |   | | } q% Wn  |  j d k rx |  j   n  |  j j |  d S(   s   Sets the weights of the model.

        # Arguments
            weights: Should be a list
                of Numpy arrays with shapes and types matching
                the output of `model.get_weights()`.
        N(	   R>   R?   R@   R   R(   Rq   RO   R0   R   (   R   R(   R   R   t   nb_param(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyRq     s    	c         C@ s   t  d  k r t d   n  t  j | d d } d | j k rX d | k rX | d } n  t j |   ry t j |   } n	 |  j } | r t	 j
 | |  n t	 j | |  t | d  r | j   n  d  S(   Ns   `load_weights` requires h5py.Re   Rf   t   layer_namesR    RN   (   R/   R0   R1   R6   R9   R>   R?   R@   R   R   t$   load_weights_from_hdf5_group_by_nameRl   R   RN   (   R   RP   t   by_nameRS   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   load_weights  s    	c         C@ s   t  d  k r t d   n  | rM t j j |  rM t |  } | sM d  Sn  t j |   rn t j	 |   } n	 |  j
 } t  j | d  } t j | |  | j   | j   d  S(   Ns   `save_weights` requires h5py.R   (   R/   R0   R1   R3   R4   R5   R   R>   R?   R@   R   R6   R   RA   RM   RN   (   R   RP   RQ   RR   R   RS   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   save_weights  s    	
c         K@ s   |  j    |  j j | | d | d | | |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j |  _ |  j j	 |  _	 d S(   s  Configures the learning process.

        # Arguments
            optimizer: str (name of optimizer) or optimizer object.
                See [optimizers](/optimizers).
            loss: str (name of objective function) or objective function.
                See [objectives](/objectives).
            metrics: list of metrics to be evaluated by the model
                during training and testing.
                Typically you will use `metrics=['accuracy']`.
                See [metrics](/metrics).
            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).
            **kwargs: for Theano backend, these are passed into K.function.
                Ignored for Tensorflow backend.

        # Example
            ```python
                model = Sequential()
                model.add(Dense(32, input_shape=(500,)))
                model.add(Dense(10, activation='softmax'))
                model.compile(optimizer='rmsprop',
                              loss='categorical_crossentropy',
                              metrics=['accuracy'])
            ```
        R$   R%   N(
   R   RO   Rn   R!   R#   R&   R$   t   metrics_tensorst   metrics_namesR%   (   R   R!   R#   R$   R%   t   kwargs(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyRn     s     
i    i
   i   g        i    c         K@ s   d | k r+ t  j d  | j d  } n  | rJ t d t |    n  |  j d k rh t d   n  |  j j | | d | d | d | d | d	 | d
 | d |	 d |
 d | d | 
S(   s	  Trains the model for a fixed number of epochs.

        # Arguments
            x: input data, as a Numpy array or list of Numpy arrays
                (if the model has multiple inputs).
            y: labels, as a Numpy array.
            batch_size: integer. Number of samples per gradient update.
            epochs: integer, the number of epochs to train the model.
            verbose: 0 for no logging to stdout,
                1 for progress bar logging, 2 for one log line per epoch.
            callbacks: list of `keras.callbacks.Callback` instances.
                List of callbacks to apply during training.
                See [callbacks](/callbacks).
            validation_split: float (0. < x < 1).
                Fraction of the data to use as held-out validation data.
            validation_data: tuple (x_val, y_val) or tuple
                (x_val, y_val, val_sample_weights) to be used as held-out
                validation data. Will override validation_split.
            shuffle: boolean or str (for 'batch').
                Whether to shuffle the samples at each epoch.
                'batch' is a special option for dealing with the
                limitations of HDF5 data; it shuffles in batch-sized chunks.
            class_weight: dictionary mapping classes to a weight value,
                used for scaling the loss function (during training only).
            sample_weight: Numpy array of weights for
                the training samples, used for scaling the loss function
                (during training only). You can either pass a flat (1D)
                Numpy array with the same length as the input samples
                (1:1 mapping between weights and samples),
                or in the case of temporal data,
                you can pass a 2D array with shape (samples, sequence_length),
                to apply a different weight to every timestep of every sample.
                In this case you should make sure to specify
                sample_weight_mode="temporal" in compile().
            initial_epoch: epoch at which to start training
                (useful for resuming a previous training run)

        # Returns
            A `History` object. Its `History.history` attribute is
            a record of training loss values and metrics values
            at successive epochs, as well as validation loss values
            and validation metrics values (if applicable).

        # Raises
            RuntimeError: if the model was never compiled.
        t   nb_epochs;   The `nb_epoch` argument in `fit` has been renamed `epochs`.s    Unrecognized keyword arguments: s1   The model needs to be compiled before being used.t
   batch_sizet   epochst   verboset	   callbackst   validation_splitt   validation_datat   shufflet   class_weightt   sample_weightt   initial_epochN(	   RD   RE   R   R   R7   RO   R0   t   RuntimeErrort   fit(   R   R   t   yR   R   R   R   R   R   R   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s$    2c      	   C@ sC   |  j  d k r t d   n  |  j  j | | d | d | d | S(   s  Computes the loss on some input data, batch by batch.

        # Arguments
            x: input data, as a Numpy array or list of Numpy arrays
                (if the model has multiple inputs).
            y: labels, as a Numpy array.
            batch_size: integer. Number of samples per gradient update.
            verbose: verbosity mode, 0 or 1.
            sample_weight: sample weights, as a Numpy array.

        # Returns
            Scalar test loss (if the model has no metrics)
            or list of scalars (if the model computes other metrics).
            The attribute `model.metrics_names` will give you
            the display labels for the scalar outputs.

        # Raises
            RuntimeError: if the model was never compiled.
        s1   The model needs to be compiled before being used.R   R   R   N(   RO   R0   R   t   evaluate(   R   R   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   O  s    c         C@ s8   |  j  d k r |  j   n  |  j  j | d | d | S(   sF  Generates output predictions for the input samples.

        The input samples are processed batch by batch.

        # Arguments
            x: the input data, as a Numpy array.
            batch_size: integer.
            verbose: verbosity mode, 0 or 1.

        # Returns
            A Numpy array of predictions.
        R   R   N(   RO   R0   R   t   predict(   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   l  s    c         C@ s,   |  j  d k r |  j   n  |  j  j |  S(   s  Returns predictions for a single batch of samples.

        # Arguments
            x: input data, as a Numpy array or list of Numpy arrays
                (if the model has multiple inputs).

        # Returns
            A Numpy array of predictions.
        N(   RO   R0   R   t   predict_on_batch(   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   }  s    
c         C@ s=   |  j  d k r t d   n  |  j  j | | d | d | S(   s  Single gradient update over one batch of samples.

        # Arguments
            x: input data, as a Numpy array or list of Numpy arrays
                (if the model has multiple inputs).
            y: labels, as a Numpy array.
            class_weight: dictionary mapping classes to a weight value,
                used for scaling the loss function (during training only).
            sample_weight: sample weights, as a Numpy array.

        # Returns
            Scalar training loss (if the model has no metrics)
            or list of scalars (if the model computes other metrics).
            The attribute `model.metrics_names` will give you
            the display labels for the scalar outputs.

        # Raises
            RuntimeError: if the model was never compiled.
        s1   The model needs to be compiled before being used.R   R   N(   RO   R0   R   t   train_on_batch(   R   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s
    c         C@ s7   |  j  d k r t d   n  |  j  j | | d | S(   s  Evaluates the model over a single batch of samples.

        # Arguments
            x: input data, as a Numpy array or list of Numpy arrays
                (if the model has multiple inputs).
            y: labels, as a Numpy array.
            sample_weight: sample weights, as a Numpy array.

        # Returns
            Scalar test loss (if the model has no metrics)
            or list of scalars (if the model computes other metrics).
            The attribute `model.metrics_names` will give you
            the display labels for the scalar outputs.

        # Raises
            RuntimeError: if the model was never compiled.
        s1   The model needs to be compiled before being used.R   N(   RO   R0   R   t   test_on_batch(   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    c         C@ sM   |  j  | | |  } | j   d k  s9 | j   d k rI t j d  n  | S(   s  Generates class probability predictions for the input samples.

        The input samples are processed batch by batch.

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

        # Returns
            A Numpy array of probability predictions.
        g        g      ?s   Network returning invalid probability values. The last layer might not normalize predictions into probabilities (like softmax or sigmoid would).(   R   t   mint   maxRD   RE   (   R   R   R   R   t   preds(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   predict_proba  s    $c         C@ sU   |  j  | d | d | } | j d d k r> | j d d  S| d k j d  Sd S(	   s  Generate class predictions for the input samples.

        The input samples are processed batch by batch.

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

        # Returns
            A numpy array of class predictions.
        R   R   ii   t   axisg      ?t   int32N(   R   RL   t   argmaxt   astype(   R   R   R   R   t   proba(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   predict_classes  s    c         C@ sj   |  j  d k r t d   n  |  j  j | | | d | d | d | d | d | d |	 d |
 d	 | d
 | 	S(   s  Fits the model on data generated 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 `samples_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 of 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.
                Number of samples to use from validation generator
                at the end of every epoch.
            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
            pickle_safe: Ff 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.

        # Raises
            RuntimeError: if the model was never compiled.

        # 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
                        x, y = process_line(line)
                        yield (x, y)
                    f.close()

            model.fit_generator(generate_arrays_from_file('/my_file.txt'),
                                samples_per_epoch=10000, epochs=10)
        ```
        s1   The model needs to be compiled before being used.R   R   R   t   validation_stepsR   t
   max_q_sizet   workerst   pickle_safeR   N(   RO   R0   R   t   fit_generator(   R   t	   generatort   steps_per_epochR   R   R   R   R   R   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    Qc      	   C@ sC   |  j  d k r t d   n  |  j  j | | d | d | d | S(   s  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
            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 no metrics)
            or list of scalars (if the model computes other metrics).
            The attribute `model.metrics_names` will give you
            the display labels for the scalar outputs.

        # Raises
            RuntimeError: if the model was never compiled.
        s1   The model needs to be compiled before being used.R   R   R   N(   RO   R0   R   t   evaluate_generator(   R   R   t   stepsR   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   K  s    c         C@ sG   |  j  d k r |  j   n  |  j  j | | d | d | d | d | S(   s  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
            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
            A Numpy array of predictions.
        R   R   R   R   N(   RO   R0   R   t   predict_generator(   R   R   R   R   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR   s  s    c         C@ sq   t  |  j d t j  r# |  j   Sg  } x8 |  j D]- } | j i | j j d 6| j   d 6 q3 Wt	 j
 |  S(   Ni    R   R   (   RB   R   R   R   t   legacy_get_configRJ   R   R   R   t   copyt   deepcopy(   R   R   R   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s    
c         C@ sk   d | d k s$ | d d d k r1 |  j  |  S|    } x* | D]" } t j |  } | j |  qA W| S(   NR   i    R   (   t   legacy_from_configRv   Rm   R   (   t   clsR   RO   t   confR   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   from_config  s    $	c         C@ sE  g  } t  |  j d t j  r t |  j d d  s; t  g  } xE |  j d j D]3 } i | j j d 6| j   d 6} | j	 |  qR W|  j d j   } | | d <| j	 i d d 6| d 6 n5 | j	 i |  j d j j d 6|  j d j   d 6 x< |  j d D]- } | j	 i | j j d 6| j   d 6 qWt
 j |  S(   s   Retrieves the model configuration as a Python list.

        # Returns
            A list of dicts (each dict is a layer config).
        i    R   R   R   R   i   (   RB   R   R   R   R   t   AssertionErrorR   R   R   RJ   R   R  (   R   R   R   R   t   layer_configt   merge_config(    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR     s"    
c         @ s    s i    n  d   } |    }   f d   } | d } | |  } | d d k r g  } | d } x3 | j  d  D]" }	 t j |	  }
 | j |
  qv W| | d <t j j |  } | j |  n | |  } | j |  x7 | d D]+ } | |  } | |  } | j |  q W| S(	   Nc         S@ sE   d |  k rA |  d } |  j  d  } | |  d <i | d 6|  d 6S|  S(   NR   R+   t   custom_nameR   (   Rg   (   R  R   R+   (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   normalize_legacy_config  s    


c         @ sD   |  d j  d  } |   k r'   | St j |   } |   | <| S(   NR   R+   (   Rg   Rv   Rm   (   t
   layer_dataR+   R   (   t   layer_cache(    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   get_or_create_layer  s    
i    R   R   R   R   i   (   R   Rv   Rm   RJ   R   R   R  R   (   R  R   R  R
  RO   R  t   first_layert   merge_inputst   first_layer_configt   merge_input_configt   merge_inputR   R   R  (    (   R  s+   /tmp/pip-build-isqEY4/keras/keras/models.pyR    s.    		
	


N(2   R   R   t   __doc__R0   R   R   R   R   R   R   t   propertyR   R   R   R   t   setterR   R   R   R   R   R   R   R   R   R   Rq   R   R   R   R   Rn   R   R   R   R   R   R   R   R   R   t    legacy_generator_methods_supportR   R   R   R   t   classmethodR  R   R  (    (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyRo   H  sz   #	P	!						,	F	U%	
	((   t
   __future__R    R   RD   R   R;   R3   Rw   t   numpyR   R2   R   R:   R   R   Rv   t   utils.io_utilsR   t   engine.trainingR   t   engineR   t   engine.topologyR   R	   t   legacyR   R
   R>   R   R/   R1   R0   R   R\   Ru   Rk   Rz   R|   Ro   (    (    (    s+   /tmp/pip-build-isqEY4/keras/keras/models.pyt   <module>   s8   
l