
    BVh0[                     6   d 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 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Z# G d dejH                        Z%d Z&d Z'd Z(d Z)y)zHome of the `Sequential` model.    N)tf2)ops)tensor_util)layers)
base_layer)
functional)input_layer)training_utils)model_serialization)generic_utils)layer_utils)
tf_inspect)tf_utils)module)	np_arrays)
tf_logging)base)nestzuAll layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.c                       e Zd ZdZej
                  d fd	       Ze fd       Zej
                  d        Z	ej
                  d        Z
ej
                  	 dd       Zej                  d fd	       Zd fd	Zd	 Zd
 ZddZddZ fdZedd       Zed        Zej0                  d        Zed        Zd Z fdZ xZS )
Sequentiala  `Sequential` groups a linear stack of layers into a `tf.keras.Model`.

  `Sequential` provides training and inference features on this model.

  Examples:

  >>> # Optionally, the first layer can receive an `input_shape` argument:
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,)))
  >>> # Afterwards, we do automatic shape inference:
  >>> model.add(tf.keras.layers.Dense(4))

  >>> # This is identical to the following:
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.Input(shape=(16,)))
  >>> model.add(tf.keras.layers.Dense(8))

  >>> # Note that you can also omit the `input_shape` argument.
  >>> # In that case the model doesn't have any weights until the first call
  >>> # to a training/evaluation method (since it isn't yet built):
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Dense(8))
  >>> model.add(tf.keras.layers.Dense(4))
  >>> # model.weights not created yet

  >>> # Whereas if you specify the input shape, the model gets built
  >>> # continuously as you are adding layers:
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,)))
  >>> model.add(tf.keras.layers.Dense(4))
  >>> len(model.weights)
  4

  >>> # When using the delayed-build pattern (no input shape specified), you can
  >>> # choose to manually build your model by calling
  >>> # `build(batch_input_shape)`:
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Dense(8))
  >>> model.add(tf.keras.layers.Dense(4))
  >>> model.build((None, 16))
  >>> len(model.weights)
  4

  ```python
  # Note that when using the delayed-build pattern (no input shape specified),
  # the model gets built the first time you call `fit`, `eval`, or `predict`,
  # or the first time you call the model on some input data.
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Dense(8))
  model.add(tf.keras.layers.Dense(1))
  model.compile(optimizer='sgd', loss='mse')
  # This builds the model for the first time:
  model.fit(x, y, batch_size=32, epochs=10)
  ```
  c                 H   t         t        j                  |   |d       d| _        d| _        d| _        d| _        d| _        d| _	        i | _
        t               | _        d| _        d| _        |r2t        |t         t"        f      s|g}|D ]  }| j%                  |        yy)zCreates a `Sequential` model instance.

    Args:
      layers: Optional list of layers to add to the model.
      name: Optional name for the model.
    F)nameautocastTN)superr   
Functional__init__supports_masking _compute_output_and_mask_jointly_auto_track_sub_layers_inferred_input_shape_has_explicit_input_shape_input_dtype_layer_call_argspecsset_created_nodes_graph_initialized_use_legacy_deferred_behavior
isinstancelisttupleadd)selfr   r   layer	__class__s       Y/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/engine/sequential.pyr   zSequential.__init__g   s     
*

/E 0 # D,0D)"'D!%D%*D"D "D%D $D */D& u. %     c                 r    t         t        | 
  }|r"t        |d   t        j
                        r|dd  S |d d  S )Nr      )r   r   r   r(   r	   
InputLayer)r,   r   r.   s     r/   r   zSequential.layers   s=     :t+F*VAY(>(>?ABZ!9r0   c                    t        |d      r@|j                  d   }t        |t        j                        r|}t        j                  d       t        |t        j                        r0t        |t        j                        s-t        j                  |      }nt        dt        |      z         t        j                   |g       | j#                  |      st%        d|j&                  d      d| _        d}| j+                  dg        | j,                  st        |t        j                        rd	}nIt/        j0                  |      \  }}|r/t        j2                  |||j&                  d
z         } ||       d	}|rt5        j6                  |j8                  d   j:                        }t=        |      dk7  rt%        t>              || _        tA        jB                  | j:                  d         | _"        d	| _        d	| _#        n`| j:                  rT || j:                  d         }t=        t5        j6                  |            dk7  rt%        t>              |g| _        d	| _        |s| jH                  r.| jK                  | jD                  | j:                         d	| _$        n-| j,                  jM                  |       | jO                  |g       tQ        jR                  |jT                        | jV                  |<   y)a  Adds a layer instance on top of the layer stack.

    Args:
        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).
    _keras_historyr   zPlease add `keras.layers.InputLayer` instead of `keras.Input` to Sequential model. `keras.Input` is intended to be used by Functional model.z;The added layer must be an instance of class Layer. Found: zGAll layers added to a Sequential model should have unique names. Name "za" is already the name of a layer in this model. Update the `name` argument to pass a unique name.F_self_tracked_trackablesT_inputbatch_shapedtyper   r2   N),hasattrr5   r(   r	   r3   loggingwarningr   Moduler   Layerr   ModuleWrapper	TypeErrorstrr   assert_no_legacy_layers_is_layer_name_unique
ValueErrorr   built_maybe_create_attributer6   r
   get_input_shape_and_dtypeInputr   flatten_inbound_nodesoutputslenSINGLE_LAYER_OUTPUT_ERROR_MSGr   get_source_inputsinputsr!   r&   _init_graph_networkappend#_handle_deferred_layer_dependenciesr   getfullargspeccallr#   )	r,   r-   origin_layer
set_inputsr9   r:   xrM   output_tensors	            r/   r+   zSequential.add   sz   $ u&'))!,l	L+"8"8	9 	!
 %'z//0((/  "%e*- . . $$eW-%%e, 49::@ A A
 DJJ  !;R@((	E;11	2
+EEeLU%Uh9NP!
 (*	,,u33B7??@w<189
9!33DLLOD
)-&	 DLLO,m	T\\-(	)Q	.677#_dldjT,,
t{{DLL9 $d
##**51
..w7'1'@'@'LDe$r0   c                    | j                   st        d      | j                  j                         }| j                  j                  |       | j                   s+d| _        d| _        d| _        d| _        d| _	        d| _
        y| j                  rag | j                   d   _        | j                   d   j                  g| _        | j                  | j                  | j
                         d| _        yy)znRemoves the last layer in the model.

    Raises:
        TypeError: if there are no layers in the model.
    z!There are no layers in the model.NFr;   T)r   rB   r6   popr#   rM   rQ   rG   r    r!   r&   _outbound_nodesoutputrR   )r,   r-   s     r/   r\   zSequential.pop   s     ;;9::))--/E!!%(;;dldkdj#'d ',d$ %d		 	 (*dkk"o%kk"o,,-dl
t{{DLL9dj	 
!r0   c                 |   || j                   sy t        j                         rt        j                         sy | j
                  sF| j                  s8t        |      }| j                  |}nt        | j                  |      }||| j                  k7  rt        j                         5  t        j                  ||| j                   d   j                  dz         }|}t               }| j                   D ]a  }t        || j                          	  ||      }t#        t%        j&                  |            dk7  rt)        t*              t-        ||       |}|}	c || _        	 | j/                  |	       d| _        d d d        || _        y y y y y #  d| _        Y  d d d        y xY w#  d| _        Y 6xY w# 1 sw Y   :xY w)Nr   r7   r8   Tr2   )r   r   enabledr   #executing_eagerly_outside_functionsr!   r'   r*   r    relax_input_shape
init_scoper	   rJ   r   r$   clear_previously_created_nodesr%   rN   r   rK   rF   rO    track_nodes_created_by_last_callrR   r&   )
r,   input_shapeinput_dtype	new_shaperQ   layer_inputcreated_nodesr-   layer_outputrM   s
             r/   '_build_graph_network_for_inferred_shapez2Sequential._build_graph_network_for_inferred_shape	  s    $++;;= G G I**.. +&k		#	#	+	%d&@&@+N	

I1K1K$K ^^ 5	6$$#;;q>&&13& +%-{{ !#e +5$2E2EF";/l  4<<-.!3<==,UMB&K"GC!#D !.$
6 $$VW5&*D#g5	6l &/"s %L
 / +@ 48d0E5	6 5	6h615D.k5	6 5	6s>   )A$F2FA	F2 F$	F!F2!F2$	F/-F22F;c                 &   | j                   r.| j                  | j                  | j                         d| _        y |t	        d      | j                  |       | j                  s%t        |      }|| _        t        t        | /  |       d| _        y )Nz+You must provide an `input_shape` argument.T)r&   rR   rQ   rM   rF   rl   rG   r*   _build_input_shaper   r   build)r,   rf   r.   s     r/   ro   zSequential.buildV  s~    
t{{DLL9 DJ 
	FGG
22;?ZZK("-j$%k2DJr0   c                 B   | j                   st        j                  |      szt        |t        j
                        s`d| _        t        j                  t        |      | _
        t        j                         rLt        j                  dt        |      d|d       n&| j!                  |j"                  |j$                         | j&                  rH| j(                  s&| j+                  | j,                  | j.                         t0        t2        | k  |||      S |}| j6                  D ]w  }i }| j8                  |   j:                  }d|v r||d<   d|v r||d<    ||fi |}t=        t        j>                  |            dk7  rtA        tB              |}tE        |d	d       }y |S )
NTzVLayers in a Sequential model should only have a single input tensor, but we receive a z input: z7
Consider rewriting this model with the Functional API.)trainingmaskrr   rq   r2   _keras_mask)#r!   r   
is_tf_typer(   r   ndarrayr'   r   map_structure_get_shape_tuplern   r   r`   r=   r>   typerl   shaper:   r&   rG   rR   rQ   rM   r   r   rV   r   r#   argsrN   rK   rF   rO   getattr)	r,   rQ   rq   rr   rM   r-   kwargsargspecr.   s	           r/   rV   zSequential.calld  so   ))##F+J
)##5%
 .2*"&"4"45Ev"N;;=
// %)L&: ;
 	44V\\6<<PZZ  dll;:t)&8$)OOG 3 f))%055g	7	v	w	%zf''g	T\\'"	#q	(677fWmT2d#3$ Nr0   c                 N    |}| j                   D ]  }|j                  |      } |S N)r   compute_output_shape)r,   rf   ry   r-   s       r/   r   zSequential.compute_output_shape  s/    E 0((/e0Lr0   c                 B    | j                  ||      }t        |dd       S )N)rr   rs   )rV   r{   )r,   rQ   rr   rM   s       r/   compute_maskzSequential.compute_mask  s%     iiTi*G7M400r0   c                     t        j                  d       | j                  |||      }|j                         dk  s|j	                         dkD  rt        j                  d       |S )ay  Generates class probability predictions for the input samples.

    The input samples are processed batch by batch.

    Args:
        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.
    zq`model.predict_proba()` is deprecated and will be removed after 2021-01-01. Please use `model.predict()` instead.g        g      ?zNetwork returning invalid probability values. The last layer might not normalize predictions into probabilities (like softmax or sigmoid would).)warningswarnpredictminmaxr=   r>   )r,   rY   
batch_sizeverbosepredss        r/   predict_probazSequential.predict_proba  s\     MM : ; LLJ0Eyy{R599;+oo 9 : Lr0   c                     t        j                  d       | j                  |||      }|j                  d   dkD  r|j	                  d      S |dkD  j                  d      S )af  Generate class predictions for the input samples.

    The input samples are processed batch by batch.

    Args:
        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.
    a  `model.predict_classes()` is deprecated and will be removed after 2021-01-01. Please use instead:* `np.argmax(model.predict(x), axis=-1)`,   if your model does multi-class classification   (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype("int32")`,   if your model does binary classification   (e.g. if it uses a `sigmoid` last-layer activation).)r   r   r;   r2   )axisg      ?int32)r   r   r   ry   argmaxastype)r,   rY   r   r   probas        r/   predict_classeszSequential.predict_classes  sc     MM K L LLz7LCE{{2\\r\""ck!!'**r0   c                    g }t         t        | 
  D ]&  }|j                  t	        j
                  |             ( | j                  t        j                  |      d}| j                  s| j                  | j                  |d<   |S )N)r   r   build_input_shape)r   r   r   rS   r   serialize_keras_objectr   copydeepcopy_is_graph_networkrn   )r,   layer_configsr-   configr.   s       r/   
get_configzSequential.get_config  s    Mz4/ H =??FG	H 		--.F !!d&=&=&I$($;$;f !Mr0   c                 ,   d|v r|d   }|j                  d      }|d   }nd }d }|} | |      }|D ]*  }t        j                  ||      }|j                  |       , |j                  s)|r't        |t        t        f      r|j                  |       |S )Nr   r   r   )r   )custom_objects)	getlayer_moduledeserializer+   rQ   r(   r*   r)   ro   )	clsr   r   r   r   r   modellayer_configr-   s	            r/   from_configzSequential.from_config  s    F^d **%89X&mdmTNE% &&|6DFeii LL.$udm4kk#$Lr0   c                     t        | d      r| j                  S | j                  r2t        | j                  d   d      r| j                  d   j                  S y )N_manual_input_specr   
input_spec)r<   r   r   r   r,   s    r/   r   zSequential.input_spec  sH    t)*$$${{wt{{1~|<[[^&&&r0   c                     || _         y r   )r   )r,   values     r/   r   zSequential.input_spec  s
    #Dr0   c                 ,    t        j                  |       S r   )r   SequentialSavedModelSaverr   s    r/   _trackable_saved_model_saverz'Sequential._trackable_saved_model_saver  s    88>>r0   c                 f    | j                   D ]"  }|j                  |j                  k(  s||us" y y)NFT)r   r   )r,   r-   	ref_layers      r/   rE   z Sequential._is_layer_name_unique  s4    [[ 		y~~	%)5*@ r0   c                 X    | j                   ry t        t        j                  |           y r   )r&   r   r   r   _assert_weights_created)r,   r.   s    r/   r   z"Sequential._assert_weights_created  s$     
*

>@r0   )NNr   )    r   )__name__
__module____qualname____doc__	trackable no_automatic_dependency_trackingr   propertyr   r+   r\   rl   r   defaultro   rV   r   r   r   r   r   classmethodr   r   setterr   rE   r   __classcell__)r.   s   @r/   r   r   .   s3   6p --" ."H 	 	 --UM .UMn -- .0 -- ;?J/ .J/X  *X12+:  &   $ $ ? ?A Ar0   r   c                     t        | d      rD| j                  }t        |t              r|S |j                  t        |j                               S y y )Nry   )r<   ry   r(   r*   rankas_list)try   s     r/   rw   rw     sE    QGGE%lzz5==?##	r0   c                 t    | |y t        |       t        |      k7  ry t        d t        | |      D              S )Nc              3   4   K   | ]  \  }}||k7  rd n|  y wr    ).0d1d2s      r/   	<genexpr>z$relax_input_shape.<locals>.<genexpr>$  s     LFBrRxtR'Ls   )rN   r*   zip)shape_1shape_2s     r/   rb   rb     s9    _\S\!	Lc'76KL	LLr0   c                    | j                   D ]K  }|j                  }t        j                  |      D ]%  }|j                  D cg c]  }||vr|
 c}|_        ' M | j                   D cg c]	  }||vs| c}| _         yc c}w c c}w )zARemove nodes from `created_nodes` from the layer's inbound_nodes.N)rL   inbound_layersr   rK   r]   )r-   rj   nodeprev_layers
prev_layerns         r/   rd   rd   '  s    "" %d%%Kll;/ %
//$%m# $%j %% %%A-)?aA%$%As   B )	B3Bc                    | j                   sy|j                  | j                   d          | j                   d   j                  }t        j                  |      D ]-  }|j
                  s|j                  |j
                  d          / y)zFAdds to `created_nodes` the nodes created by the last call to `layer`.Nr;   )rL   r+   r   r   rK   r]   )r-   rj   r   r   s       r/   re   re   3  sw    			
E((,-$$R(77+LL- 8j!!
222678r0   )*r   r   r   tensorflow.pythonr   tensorflow.python.frameworkr   r   tensorflow.python.kerasr   r   tensorflow.python.keras.enginer   r   r	   r
   *tensorflow.python.keras.saving.saved_modelr   tensorflow.python.keras.utilsr   r   r   r   tensorflow.python.moduler   tensorflow.python.ops.numpy_opsr   tensorflow.python.platformr   r=   tensorflow.python.trackabler   r   tensorflow.python.utilr   rO   r   r   rw   rb   rd   re   r   r0   r/   <module>r      s|     &   ! + 3 : 5 5 6 9 J 7 5 4 2 + 5 < 9 '"C 
cA&& cALM	A8r0   