a
    Sic]                     @   sD  d Z ddlm  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ed Zed Zed Zed Ze Zd5ddZeddd6ddZeddd7d d!Zd8d$d%Zd9d&d'Zd:d(d)Z d;d*d+Z!ed,d<d-d.Z"ed/d=d1d2Z#ej$j%d3ej&ej'd4e"_ ej#j e#_ dS )>a  NASNet-A models for Keras.

NASNet refers to Neural Architecture Search Network, a family of models
that were designed automatically by learning the model architectures
directly on the dataset of interest.

Here we consider NASNet-A, the highest performance model that was found
for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset,
obtaining state of the art performance on CIFAR-10 and ImageNet 2012.
Only the NASNet-A models, and their respective weights, which are suited
for ImageNet 2012 are provided.

The below table describes the performance on ImageNet 2012:
--------------------------------------------------------------------------------
      Architecture       | Top-1 Acc | Top-5 Acc |  Multiply-Adds |  Params (M)
--------------------------------------------------------------------------------
|   NASNet-A (4 @ 1056)  |   74.0 %  |   91.6 %  |       564 M    |     5.3    |
|   NASNet-A (6 @ 4032)  |   82.7 %  |   96.2 %  |      23.8 B    |    88.9    |
--------------------------------------------------------------------------------

Reference:
  - [Learning Transferable Architectures for Scalable Image Recognition](
      https://arxiv.org/abs/1707.07012) (CVPR 2018)
    N)backend)imagenet_utils)training)VersionAwareLayers)
data_utils)layer_utils)
tf_logging)keras_exportzDhttps://storage.googleapis.com/tensorflow/keras-applications/nasnet/zNASNet-mobile.h5zNASNet-mobile-no-top.h5zNASNet-large.h5zNASNet-large-no-top.h5     `   T   imagenet  softmaxc              	   C   s  |dv st jj|std|dkr:|r:|
dkr:tdt| trhd| v rh|dkrhtdt|  d |du rtd	}tj	| |d
t
 ||d} t
 dkrtd t
d d}nd}|du rtj| d}nt
|stj|| d}n|}|d|d   dkrtd| t
 dkr dnd}|d }tj|ddddddd|}tj|ddd d!|}d}t||||d  d"d#\}}t|||| d$d#\}}t|D ]}t|||d%| d#\}}qt|||| d&| d#\}}|s|n|}t|D ]*}t|||| d%|| d  d#\}}qt||||d  d&d|  d#\}}|sJ|n|}t|D ]2}t||||d  d%d| | d  d#\}}qVtd'|}|rt |}t|| tj|
|d(d)|}n.|	d*krt |}n|	d+krt |}|durt|}n|}tj||d,d-}|dkr|d.krp|rRt j!d/t"d0d1d2}nt j!d3t#d0d4d2}|$| nJ|d	kr|rt j!d5t%d0d6d2}nt j!d7t&d0d8d2}|$| ntd9n|dur|$| |rt
| |S ):a  Instantiates a NASNet model.

    Reference:
    - [Learning Transferable Architectures for Scalable Image Recognition](
        https://arxiv.org/abs/1707.07012) (CVPR 2018)

    For image classification use cases, see
    [this page for detailed examples](
      https://keras.io/api/applications/#usage-examples-for-image-classification-models).

    For transfer learning use cases, make sure to read the
    [guide to transfer learning & fine-tuning](
      https://keras.io/guides/transfer_learning/).

    Note: each Keras Application expects a specific kind of input preprocessing.
    For NasNet, call `tf.keras.applications.nasnet.preprocess_input`
    on your inputs before passing them to the model.
    `nasnet.preprocess_input` will scale input pixels between -1 and 1.

    Args:
      input_shape: Optional shape tuple, the input shape
        is by default `(331, 331, 3)` for NASNetLarge and
        `(224, 224, 3)` for NASNetMobile.
        It should have exactly 3 input channels,
        and width and height should be no smaller than 32.
        E.g. `(224, 224, 3)` would be one valid value.
      penultimate_filters: Number of filters in the penultimate layer.
        NASNet models use the notation `NASNet (N @ P)`, where:
            -   N is the number of blocks
            -   P is the number of penultimate filters
      num_blocks: Number of repeated blocks of the NASNet model.
        NASNet models use the notation `NASNet (N @ P)`, where:
            -   N is the number of blocks
            -   P is the number of penultimate filters
      stem_block_filters: Number of filters in the initial stem block
      skip_reduction: Whether to skip the reduction step at the tail
        end of the network.
      filter_multiplier: Controls the width of the network.
        - If `filter_multiplier` < 1.0, proportionally decreases the number
            of filters in each layer.
        - If `filter_multiplier` > 1.0, proportionally increases the number
            of filters in each layer.
        - If `filter_multiplier` = 1, default number of filters from the
             paper are used at each layer.
      include_top: Whether to include the fully-connected
        layer at the top of the network.
      weights: `None` (random initialization) or
          `imagenet` (ImageNet weights)
      input_tensor: Optional Keras tensor (i.e. output of
        `layers.Input()`)
        to use as image input for the model.
      pooling: Optional pooling mode for feature extraction
        when `include_top` is `False`.
        - `None` means that the output of the model
            will be the 4D tensor output of the
            last convolutional block.
        - `avg` means that global average pooling
            will be applied to the output of the
            last convolutional block, and thus
            the output of the model will be a
            2D tensor.
        - `max` means that global max pooling will
            be applied.
      classes: Optional number of classes to classify images
        into, only to be specified if `include_top` is True, and
        if no `weights` argument is specified.
      default_size: Specifies the default image size of the model
      classifier_activation: A `str` or callable. The activation function to use
        on the "top" layer. Ignored unless `include_top=True`. Set
        `classifier_activation=None` to return the logits of the "top" layer.
        When loading pretrained weights, `classifier_activation` can only
        be `None` or `"softmax"`.

    Returns:
      A `keras.Model` instance.
    >   Nr   zThe `weights` argument should be either `None` (random initialization), `imagenet` (pre-training on ImageNet), or the path to the weights file to be loaded.r   r   zWIf using `weights` as `"imagenet"` with `include_top` as true, `classes` should be 1000NzWhen specifying the input shape of a NASNet and loading `ImageNet` weights, the input_shape argument must be static (no None entries). Got: `input_shape=z`.K      )default_sizemin_sizedata_formatrequire_flattenweightschannels_lasta  The NASNet family of models is only available for the input data format "channels_last" (width, height, channels). However your settings specify the default data format "channels_first" (channels, width, height). You should set `image_data_format="channels_last"` in your Keras config located at ~/.keras/keras.json. The model being returned right now will expect inputs to follow the "channels_last" data format.channels_first)shape)tensorr      r   r   zwFor NASNet-A models, the `penultimate_filters` must be a multiple of 24 * (`filter_multiplier` ** 2). Current value: %d      r    r   r   validFZ
stem_conv1	he_normal)stridespaddinguse_biasnamekernel_initializerZڊ?MbP?Zstem_bn1axismomentumepsilonr'   Zstem_1block_idZstem_2z%dz	reduce_%drelupredictions)
activationr'   avgmaxNASNetr'      znasnet_mobile.h5modelsZ 020fb642bf7360b370c678b08e0adf61)cache_subdir	file_hashznasnet_mobile_no_top.h5Z 1ed92395b5b598bdda52abe5c0dbfd63znasnet_large.h5Z 11577c9a518f0070763c2b964a382f17znasnet_large_no_top.h5Z d81d89dc07e6e56530c4e77faddd61b5zDImageNet weights can only be loaded with NASNetLarge or NASNetMobile)'tfiogfileexists
ValueError
isinstancetuplestrr   obtain_input_shaper   image_data_formatloggingwarningset_image_data_formatlayersInputis_keras_tensorConv2DBatchNormalization_reduction_a_cellrange_normal_a_cell
ActivationGlobalAveragePooling2Dvalidate_activationDenseGlobalMaxPooling2Dr   get_source_inputsr   Modelr   get_fileNASNET_MOBILE_WEIGHT_PATH NASNET_MOBILE_WEIGHT_PATH_NO_TOPload_weightsNASNET_LARGE_WEIGHT_PATHNASNET_LARGE_WEIGHT_PATH_NO_TOP)input_shapepenultimate_filters
num_blocksstem_block_filtersskip_reductionfilter_multiplierinclude_topr   input_tensorpoolingclassesr   classifier_activationZold_data_format	img_inputchannel_dimfiltersxpip0inputsmodelweights_path rs   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/applications/nasnet.pyr6   A   s:   [	


















r6   z&keras.applications.nasnet.NASNetMobilezkeras.applications.NASNetMobilec                 C   s"   t | ddddd|||||d|dS )a
  Instantiates a Mobile NASNet model in ImageNet mode.

    Reference:
    - [Learning Transferable Architectures for Scalable Image Recognition](
        https://arxiv.org/abs/1707.07012) (CVPR 2018)

    Optionally loads weights pre-trained on ImageNet.
    Note that the data format convention used by the model is
    the one specified in your Keras config at `~/.keras/keras.json`.

    Note: each Keras Application expects a specific kind of input preprocessing.
    For NASNet, call `tf.keras.applications.nasnet.preprocess_input` on your
    inputs before passing them to the model.

    Args:
        input_shape: Optional shape tuple, only to be specified
            if `include_top` is False (otherwise the input shape
            has to be `(224, 224, 3)` for NASNetMobile
            It should have exactly 3 inputs channels,
            and width and height should be no smaller than 32.
            E.g. `(224, 224, 3)` would be one valid value.
        include_top: Whether to include the fully-connected
            layer at the top of the network.
        weights: `None` (random initialization) or
            `imagenet` (ImageNet weights). For loading `imagenet` weights,
            `input_shape` should be (224, 224, 3)
        input_tensor: Optional Keras tensor (i.e. output of
            `layers.Input()`)
            to use as image input for the model.
        pooling: Optional pooling mode for feature extraction
            when `include_top` is `False`.
            - `None` means that the output of the model
                will be the 4D tensor output of the
                last convolutional layer.
            - `avg` means that global average pooling
                will be applied to the output of the
                last convolutional layer, and thus
                the output of the model will be a
                2D tensor.
            - `max` means that global max pooling will
                be applied.
        classes: Optional number of classes to classify images
            into, only to be specified if `include_top` is True, and
            if no `weights` argument is specified.
        classifier_activation: A `str` or callable. The activation function to
            use on the "top" layer. Ignored unless `include_top=True`. Set
            `classifier_activation=None` to return the logits of the "top"
            layer.  When loading pretrained weights, `classifier_activation` can
            only be `None` or `"softmax"`.

    Returns:
        A Keras model instance.

    Raises:
        ValueError: In case of invalid argument for `weights`,
            or invalid input shape.
        RuntimeError: If attempting to run this model with a
            backend that does not support separable convolutions.
    i      r   Fr   r8   r_   r`   ra   rb   rc   rd   r   re   rf   rg   r   rh   r6   r^   rd   r   re   rf   rg   rh   rs   rs   rt   NASNetMobilee  s    Gry   z%keras.applications.nasnet.NASNetLargezkeras.applications.NASNetLargec                 C   s"   t | ddddd|||||d|dS )a
  Instantiates a NASNet model in ImageNet mode.

    Reference:
    - [Learning Transferable Architectures for Scalable Image Recognition](
        https://arxiv.org/abs/1707.07012) (CVPR 2018)

    Optionally loads weights pre-trained on ImageNet.
    Note that the data format convention used by the model is
    the one specified in your Keras config at `~/.keras/keras.json`.

    Note: each Keras Application expects a specific kind of input preprocessing.
    For NASNet, call `tf.keras.applications.nasnet.preprocess_input` on your
    inputs before passing them to the model.

    Args:
        input_shape: Optional shape tuple, only to be specified
            if `include_top` is False (otherwise the input shape
            has to be `(331, 331, 3)` for NASNetLarge.
            It should have exactly 3 inputs channels,
            and width and height should be no smaller than 32.
            E.g. `(224, 224, 3)` would be one valid value.
        include_top: Whether to include the fully-connected
            layer at the top of the network.
        weights: `None` (random initialization) or
            `imagenet` (ImageNet weights).  For loading `imagenet` weights,
            `input_shape` should be (331, 331, 3)
        input_tensor: Optional Keras tensor (i.e. output of
            `layers.Input()`)
            to use as image input for the model.
        pooling: Optional pooling mode for feature extraction
            when `include_top` is `False`.
            - `None` means that the output of the model
                will be the 4D tensor output of the
                last convolutional layer.
            - `avg` means that global average pooling
                will be applied to the output of the
                last convolutional layer, and thus
                the output of the model will be a
                2D tensor.
            - `max` means that global max pooling will
                be applied.
        classes: Optional number of classes to classify images
            into, only to be specified if `include_top` is True, and
            if no `weights` argument is specified.
        classifier_activation: A `str` or callable. The activation function to
            use on the "top" layer. Ignored unless `include_top=True`. Set
            `classifier_activation=None` to return the logits of the "top"
            layer.  When loading pretrained weights, `classifier_activation` can
            only be `None` or `"softmax"`.

    Returns:
        A Keras model instance.

    Raises:
        ValueError: in case of invalid argument for `weights`,
            or invalid input shape.
        RuntimeError: If attempting to run this model with a
            backend that does not support separable convolutions.
    r
   r   r   Tr   r   rv   rw   rx   rs   rs   rt   NASNetLarge  s    Grz   r   r   r   c              
   C   s  t  dkrdnd}t d|  td| }|dkr^tjt||d| d|}d	}nd
}tj|||d| |ddd|}tj	|ddd| d|}td|}tj||d| d
ddd|}tj	|ddd| d|}W d   n1 s0    Y  |S )aF  Adds 2 blocks of [relu-separable conv-batchnorm].

    Args:
        ip: Input tensor
        filters: Number of output filters per layer
        kernel_size: Kernel size of separable convolutions
        strides: Strided convolution for downsampling
        block_id: String block_id

    Returns:
        A Keras tensor
    r   r   r   zseparable_conv_block_%sr1   r!   zseparable_conv_1_pad_%sr%   r'   r"   samezseparable_conv_1_%sFr#   )r$   r'   r%   r&   r(   r)   r*   zseparable_conv_1_bn_%sr+   zseparable_conv_2_%s)r'   r%   r&   r(   zseparable_conv_2_bn_%sN)
r   rE   
name_scoperI   rQ   ZeroPadding2Dr   correct_padSeparableConv2DrM   )iprk   kernel_sizer$   r0   rj   rl   conv_padrs   rs   rt   _separable_conv_block  sf    
	"r   c           
      C   s*  t  dkrdnd}t  dkr$dnd}t |}| durDt | }t d | du rb|} n|| || krt d|  tjd	d
| d| } tjdddd| d| }tj|d dddd| dd|}tjdd| }	tj	dd|	}	tjdddd| d|	}	tj|d dddd| dd|	}	tj
||	g|d} tj|ddd| d | } W d   n1 st0    Y  n|| |krt d!| X td	| } tj|dddd"| ddd#| } tj|ddd| d | } W d   n1 s0    Y  W d   n1 s0    Y  | S )$a  Adjusts the input `previous path` to match the shape of the `input`.

    Used in situations where the output number of filters needs to be changed.

    Args:
        p: Input tensor which needs to be modified
        ip: Input tensor whose shape needs to be matched
        filters: Number of output filters to be matched
        block_id: String block_id

    Returns:
        Adjusted Keras tensor
    r   r   r   r   NZadjust_blockzadjust_reduction_block_%sr1   zadjust_relu_1_%sr7   r{   r!   r"   zadjust_avg_pool_1_%sr$   r%   r'   r}   Fzadjust_conv_1_%sr#   )r%   r&   r'   r(   )r   r   r   )r%   )r   r   r   )croppingzadjust_avg_pool_2_%szadjust_conv_2_%s)r,   r)   r*   zadjust_bn_%sr+   zadjust_projection_block_%szadjust_conv_projection_%sr$   r%   r'   r&   r(   )r   rE   	int_shaper~   rI   rQ   AveragePooling2DrL   r   
Cropping2DconcatenaterM   )
rm   r   rk   r0   rj   img_dimZip_shapeZp_shapep1p2rs   rs   rt   _adjust_blockQ  s    

		&	Dr   c              
   C   s  t  dkrdnd}t d| | t|| ||}td| }tj|dddd| d	d
d|}tj|ddd| d|}t dL t||dd| d}t||d| d}tj	||gd| d}W d   n1 s0    Y  t dN t||dd| d}	t||dd| d}
tj	|	|
gd| d}W d   n1 sB0    Y  t d@ tj
dddd| d |}tj	||gd!| d}W d   n1 s0    Y  t d"Z tj
dddd#| d |}tj
dddd$| d |}tj	||gd%| d}W d   n1 s0    Y  t d&8 t||d'| d}tj	||gd(| d}W d   n1 sh0    Y  tj||||||g|d)| d*}W d   n1 s0    Y  || fS )+zAdds a Normal cell for NASNet-A (Fig. 4 in the paper).

    Args:
        ip: Input tensor `x`
        p: Input tensor `p`
        filters: Number of output filters
        block_id: String block_id

    Returns:
        A Keras tensor
    r   r   r   znormal_A_block_%sr1   r{   r}   znormal_conv_1_%sFr#   r   r)   r*   znormal_bn_1_%sr+   block_1   r   znormal_left1_%s)r   r0   znormal_right1_%sr/   znormal_add_1_%sr7   Nblock_2znormal_left2_%sr   znormal_right2_%sznormal_add_2_%sblock_3znormal_left3_%sr   znormal_add_3_%sblock_4znormal_left4_%sznormal_right4_%sznormal_add_4_%sblock_5znormal_left5_%sznormal_add_5_%sznormal_concat_%sr,   r'   )r   rE   r~   r   rI   rQ   rL   rM   r   addr   r   )r   rm   rk   r0   rj   hx1_1x1_2x1x2_1x2_2x2x3Zx4_1Zx4_2x4x5rl   rs   rs   rt   rP     s    	
4666
6&rP   c              
   C   s  t  dkrdnd}t d|  t|| ||}td| }tj|dddd| d	d
d|}tj|ddd| d|}tjt	
|dd| d|}t dR t||ddd| d}t||ddd| d}tj||gd| d}	W d   n1 s0    Y  t dV tjdddd | d!|}
t||ddd"| d}tj|
|gd#| d}W d   n1 sn0    Y  t d$V tjdddd%| d!|}t||ddd&| d}tj||gd'| d}W d   n1 s0    Y  t d(8 tjdddd)| d!|	}t||g}W d   n1 s40    Y  t d*T t|	|dd)| d+}tjdddd,| d!|}tj||gd-| d}W d   n1 s0    Y  tj||||g|d.| d/}|| fW  d   S 1 s0    Y  dS )0zAdds a Reduction cell for NASNet-A (Fig. 4 in the paper).

    Args:
      ip: Input tensor `x`
      p: Input tensor `p`
      filters: Number of output filters
      block_id: String block_id

    Returns:
      A Keras tensor
    r   r   r   zreduction_A_block_%sr1   r{   r}   zreduction_conv_1_%sFr#   r   r)   r*   zreduction_bn_1_%sr+   r    zreduction_pad_1_%sr|   r   r   r!   zreduction_left1_%s)r$   r0   )   r   zreduction_right1_%szreduction_add_1_%sr7   Nr   r   r"   zreduction_left2_%sr   zreduction_right2_%szreduction_add_2_%sr   zreduction_left3_%szreduction_right3_%szreduction_add3_%sr   zreduction_left4_%sr   r/   zreduction_right5_%szreduction_add4_%szreduction_concat_%sr   )r   rE   r~   r   rI   rQ   rL   rM   r   r   r   r   r   MaxPooling2Dr   r   )r   rm   rk   r0   rj   r   h3r   r   r   r   r   r   Zx3_1Zx3_2r   r   Zx5_1Zx5_2r   rl   rs   rs   rt   rN   
  s    	
466.6
rN   z*keras.applications.nasnet.preprocess_inputc                 C   s   t j| |ddS )Nr<   )r   mode)r   preprocess_input)rl   r   rs   rs   rt   r   ~  s    r   z,keras.applications.nasnet.decode_predictionsr   c                 C   s   t j| |dS )N)top)r   decode_predictions)predsr   rs   rs   rt   r     s    r    )r   reterror)Nr
   r   r   Tr   Tr   NNr   Nr   )NTr   NNr   r   )NTr   NNr   r   )r   r{   N)N)N)N)N)r   )(__doc__Ztensorflow.compat.v2compatv2r<   kerasr   Zkeras.applicationsr   keras.enginer   keras.layersr   keras.utilsr   r   tensorflow.python.platformr   rF    tensorflow.python.util.tf_exportr	   BASE_WEIGHTS_PATHrY   rZ   r\   r]   rI   r6   ry   rz   r   r   rP   rN   r   r   PREPROCESS_INPUT_DOCformatPREPROCESS_INPUT_RET_DOC_TFPREPROCESS_INPUT_ERROR_DOCrs   rs   rs   rt   <module>   s                
  &       U       V 
<
\
]
t