o
    Mey  ã                   @   s|  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ƒ							d6d d!„ƒZ	d7d$d%„Zd8d&d'„Zd8d(d)„Z d8d*d+„Z!ed,ƒd8d-d.„ƒZ"ed/ƒd9d1d2„ƒZ#ej$j%d3ej&ej'd4�e"_ ej#j e#_ dS ):aG  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ƒr4d| v r4|dkr4tdt| ƒ d ƒ‚|du r:d	}tj	| |d
t
 ¡ ||d�} t
 ¡ dkrZt d¡ t
 d¡ d}nd}|du rgtj| d�}nt
 |¡stt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#�\}}qÍt|||| d&| d#�\}}|sî|n|}t|ƒD ]}t|||| d%|| d  d#�\}}qôt||||d  d&d|  d#�\}}|�s |n|}t|ƒD ]}t||||d  d%d| | d  d#�\}}�q&t d'¡|ƒ}|�rat ¡ |ƒ}t ||¡ tj|
|d(d)�|ƒ}n|	d*k�rmt ¡ |ƒ}n|	d+k�rxt ¡ |ƒ}|du�rƒt |¡}n|}tj||d,d-�}|dk�rØ|d.k�r³|�r¤t j!d/t"d0d1d2�}n	t j!d3t#d0d4d2�}| $|¡ n/|d	k�rÔ|�rÅt j!d5t%d0d6d2�}n	t j!d7t&d0d8d2�}| $|¡ ntd9ƒ‚|du�râ| $|¡ |�rêt
 |¡ |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.
    >   r   NzœThe `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 1000Nz™When 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_sizeZmin_sizeÚdata_formatZrequire_flattenÚweightsZ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)Z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_initializerçZõ¹ÚŠýï?çü©ñÒMbP?Zstem_bn1©ÚaxisZmomentumÚepsilonr#   Zstem_1©Úblock_idZstem_2z%dz	reduce_%dÚreluZpredictions)Z
activationr#   ZavgÚmaxÚNASNet©r#   éà   znasnet_mobile.h5ÚmodelsZ 020fb642bf7360b370c678b08e0adf61)Zcache_subdirZ	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ÚioZgfileÚexistsÚ
ValueErrorÚ
isinstanceÚtupleÚstrr   Zobtain_input_shaper   Úimage_data_formatÚloggingÚwarningZset_image_data_formatÚlayersZInputZis_keras_tensorÚConv2DÚBatchNormalizationÚ_reduction_a_cellÚrangeÚ_normal_a_cellÚ
ActivationZGlobalAveragePooling2DZvalidate_activationZDenseZGlobalMaxPooling2Dr   Zget_source_inputsr   ZModelr   Zget_fileÚNASNET_MOBILE_WEIGHT_PATHÚ NASNET_MOBILE_WEIGHT_PATH_NO_TOPZ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_formatZ	img_inputÚchannel_dimÚfiltersÚxÚpÚiÚp0ZinputsÚmodelZweights_path© rY   úID:\Projects\ConvertPro\env\Lib\site-packages\keras/applications/nasnet.pyr.   @   s6  [ÿÿÿýýÿú	ÿ

þÿùø
ÿþ
ÿ
ÿ
ÿü


ü
üÿþ




üü
üüÿ


r.   z&keras.applications.nasnet.NASNetMobilezkeras.applications.NASNetMobilec                 C   ó"   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   r0   ©rH   rI   rJ   rK   rL   rM   r   rN   rO   rP   r   rQ   ©r.   ©rG   rM   r   rN   rO   rP   rQ   rY   rY   rZ   ÚNASNetMobiled  ó   Gór`   z%keras.applications.nasnet.NASNetLargezkeras.applications.NASNetLargec                 C   r[   )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   r]   r^   r_   rY   rY   rZ   ÚNASNetLarge¼  ra   rb   r   ©r   r   c              
   C   s  t  ¡ dkrdnd}t  d|› �¡�m t d¡| ƒ}|dkr1t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  ƒ |S 1 s‚w   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_r,   r   Zseparable_conv_1_pad_©r!   r#   r   ÚsameZseparable_conv_1_Fr   )r    r#   r!   r"   r$   r%   r&   Zseparable_conv_1_bn_r'   Zseparable_conv_2_)r#   r!   r"   r$   Zseparable_conv_2_bn_N)
r   r9   Ú
name_scoper<   rB   ÚZeroPadding2Dr   Úcorrect_padZSeparableConv2Dr>   )ÚiprS   Úkernel_sizer    r+   rR   rT   Zconv_padrY   rY   rZ   Ú_separable_conv_block  sl   
þýùø	üûúùüû
Þ(Ø(rk   c           
      C   sz  t  ¡ dkrdnd}t  ¡ dkrdnd}t  |¡}| dur"t  | ¡}t  d¡��
 | du r0|} nâ|| || krÄt  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 s¾w   Y  n^|| |k�rt  d!|› �¡�. t d	¡| ƒ} tj|dddd"|› �ddd#�| ƒ} tj|ddd|› �d �| ƒ} W d  ƒ n)1 �sw   Y  W d  ƒ | S W d  ƒ | S W d  ƒ | S W d  ƒ | S W d  ƒ | S 1 �s6w   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_r,   Zadjust_relu_1_r/   rc   r   r   Zadjust_avg_pool_1_©r    r!   r#   re   FZadjust_conv_1_r   )r!   r"   r#   r$   )©r   r   rn   )r!   )©r   r   ro   )ZcroppingZadjust_avg_pool_2_Zadjust_conv_2_)r(   r%   r&   Z
adjust_bn_r'   Zadjust_projection_block_Zadjust_conv_projection_©r    r!   r#   r"   r$   )r   r9   Z	int_shaperf   r<   rB   ÚAveragePooling2Dr=   rg   Z
Cropping2DÚconcatenater>   )
rU   ri   rS   r+   rR   Zimg_dimZip_shapeZp_shapeÚp1Úp2rY   rY   rZ   Ú_adjust_blockP  sÊ   

ÿüûúù	üûúù	üûÛ€,ùø	üû õ
ÎC¿
þCî
ÏC€
½Cï
ÎC½Cru   c              
   C   sÞ  t  ¡ dkrdnd}t  d|› �¡��O t|| ||ƒ}t d¡| ƒ}tj|dddd|› �d	d
d�|ƒ}tj|ddd|› �d�|ƒ}t  d¡�) t||dd|› �d�}t||d|› �d�}tj	||gd|› �d�}W d  ƒ n1 srw   Y  t  d¡�* t||dd|› �d�}	t||dd|› �d�}
tj	|	|
gd|› �d�}W d  ƒ n1 s©w   Y  t  d¡�" tj
dddd|› �d �|ƒ}tj	||gd!|› �d�}W d  ƒ n1 sØw   Y  t  d"¡�0 tj
dddd#|› �d �|ƒ}tj
dddd$|› �d �|ƒ}tj	||gd%|› �d�}W d  ƒ n	1 �sw   Y  t  d&¡� t||d'|› �d�}tj	||gd(|› �d�}W d  ƒ n	1 �sBw   Y  tj||||||g|d)|› �d*�}W d  ƒ || fS 1 �sfw   Y  || fS )+zðAdds 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_r,   rc   re   Znormal_conv_1_Fr   rp   r%   r&   Znormal_bn_1_r'   Úblock_1©é   rx   Znormal_left1_)rj   r+   Znormal_right1_r*   Znormal_add_1_r/   NÚblock_2Znormal_left2_r   Znormal_right2_Znormal_add_2_Úblock_3Znormal_left3_rm   Znormal_add_3_Úblock_4Znormal_left4_Znormal_right4_Znormal_add_4_Úblock_5Znormal_left5_Znormal_add_5_Znormal_concat_©r(   r#   )r   r9   rf   ru   r<   rB   r=   r>   rk   Úaddrq   rr   )ri   rU   rS   r+   rR   ÚhÚx1_1Úx1_2Úx1Úx2_1Úx2_2Úx2Úx3Zx4_1Zx4_2Úx4Úx5rT   rY   rY   rZ   rA   ¬  s²   ùø	üûüÿöÿÿù	üûù	üûüûóÿüý
¹L´LrA   c              
   C   s  t  ¡ dkrdnd}t  d|› �¡��m 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¡�, t||ddd|› �d�}t||ddd|› �d�}tj||gd|› �d�}	W d  ƒ n1 s…w   Y  t  d¡�. tjdddd |› �d!�|ƒ}
t||ddd"|› �d�}tj|
|gd#|› �d�}W d  ƒ n1 sÀw   Y  t  d$¡�. tjdddd%|› �d!�|ƒ}t||ddd&|› �d�}tj||gd'|› �d�}W d  ƒ n1 sûw   Y  t  d(¡� tjdddd)|› �d!�|	ƒ}t ||g¡}W d  ƒ n	1 �s&w   Y  t  d*¡�- t|	|dd)|› �d+�}tjdddd,|› �d!�|ƒ}tj||gd-|› �d�}W d  ƒ n	1 �saw   Y  tj||||g|d.|› �d/�}|| fW  d  ƒ S 1 �s„w   Y  dS )0zéAdds 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_r,   rc   re   Zreduction_conv_1_Fr   rp   r%   r&   Zreduction_bn_1_r'   r   Zreduction_pad_1_rd   rv   rw   r   Zreduction_left1_)r    r+   )é   r‰   Zreduction_right1_Zreduction_add_1_r/   Nry   r   r   Zreduction_left2_rm   Zreduction_right2_Zreduction_add_2_rz   Zreduction_left3_Zreduction_right3_Zreduction_add3_r{   Zreduction_left4_r|   r*   Zreduction_right5_Zreduction_add4_Zreduction_concat_r}   )r   r9   rf   ru   r<   rB   r=   r>   rg   r   rh   rk   r~   ZMaxPooling2Drq   rr   )ri   rU   rS   r+   rR   r   Zh3r€   r�   r‚   rƒ   r„   r…   Zx3_1Zx3_2r†   r‡   Zx5_1Zx5_2rˆ   rT   rY   rY   rZ   r?   	  sä   ùø	üû
þýûûñüûûòüûûòüûù	ÿüûö
ý&�r?   z*keras.applications.nasnet.preprocess_inputc                 C   s   t j| |dd�S )Nr2   )r   Úmode)r   Úpreprocess_input)rT   r   rY   rY   rZ   r‹   }  s   ÿr‹   z,keras.applications.nasnet.decode_predictionsrx   c                 C   s   t j| |d�S )N)Útop)r   Údecode_predictions)ÚpredsrŒ   rY   rY   rZ   r�   „  s   r�   Ú )rŠ   ÚretÚerror)Nr
   r   r   Tr   Tr   NNr   Nr   )NTr   NNr   r   )r   rc   N)N)rx   )(Ú__doc__Ztensorflow.compat.v2ÚcompatÚv2r2   Zkerasr   Zkeras.applicationsr   Zkeras.enginer   Zkeras.layersr   Zkeras.utilsr   r   Ztensorflow.python.platformr   r:   Z tensorflow.python.util.tf_exportr	   ZBASE_WEIGHTS_PATHrC   rD   rE   rF   r<   r.   r`   rb   rk   ru   rA   r?   r‹   r�   ZPREPROCESS_INPUT_DOCÚformatZPREPROCESS_INPUT_RET_DOC_TFZPREPROCESS_INPUT_ERROR_DOCrY   rY   rY   rZ   Ú<module>   sŒ   ÿ
ó  &ÿùUÿùV
ÿ
<
\
]tý