a
    Sicf                     @   s  d Z ddlZddl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
ZdddddddddZddddddddddddddddddddddddddddddd dddddddd d!ddddddd"d!d#dddddddd#d$dddddgZd%d&d'd(d)d*Zd%d+d'd,d)d*Ze Zd-Zg d.Zddd7d8Zded;d<Zed=d>dfd?d@ZedAdBdgdCdDZedEdFdhdGdHZ edIdJdidKdLZ!edMdNdjdOdPZ"edQdRdkdSdTZ#edUdVdldWdXZ$edYdZdmd[d\Z%ej&d@d]e_ ej&dDd]e_ ej&dHd]e _ ej&dLd]e!_ ej&dPd]e"_ ej&dTd]e#_ ej&dXd]e$_ ej&d\d]e%_ ed^dnd_d`Z'edadodbdcZ(e
j(j e(_ dS )pzEfficientNet models for Keras.

Reference:
  - [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](
      https://arxiv.org/abs/1905.11946) (ICML 2019)
    N)backend)imagenet_utils)training)VersionAwareLayers)
data_utils)layer_utils)keras_exportz2https://storage.googleapis.com/keras-applications/)Z 902e53a9f72be733fc0bcb005b3ebbacZ 50bc09e76180e00e4465e1a485ddc09d)Z 1d254153d4ab51201f1646940f018540Z 74c4e6b3e1f6a1eea24c589628592432)Z b15cce36ff4dcbd00b6dd88e7857a6adZ 111f8e2ac8aa800a7a99e3239f7bfb39)Z ffd1fdc53d0ce67064dc6a9c7960ede0Z af6d107764bb5b1abb91932881670226)Z 18c95ad55216b8f92d7e70b3a046e2fcZ ebc24e6d6c33eaebbd558eafbeedf1ba)Z ace28f2a6363774853a83a0b21b9421aZ 38879255a25d3c92d5e44e04ae6cec6f)Z 165f6e37dce68623721b423839de8be5Z 9ecce42647a20130c1f39a5d4cb75743)Z 8c03f828fec3ef71311cd463b6759d99Z cbcfe4450ddf6f3ad90b1b398090fe4a)b0b1b2Zb3Zb4Zb5Zb6Zb7             Tg      ?)kernel_sizerepeats
filters_infilters_outexpand_ratioid_skipstridesse_ratio            (   P   p         i@  VarianceScaling       @fan_outtruncated_normal)scalemodedistribution)
class_nameconfiggUUUUUU?uniforma
  Instantiates the {name} architecture.

  Reference:
  - [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](
      https://arxiv.org/abs/1905.11946) (ICML 2019)

  This function returns a Keras image classification model,
  optionally loaded with weights pre-trained on ImageNet.

  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 EfficientNet, input preprocessing is included as part of the model
  (as a `Rescaling` layer), and thus
  `tf.keras.applications.efficientnet.preprocess_input` is actually a
  pass-through function. EfficientNet models expect their inputs to be float
  tensors of pixels with values in the [0-255] range.

  Args:
    include_top: Whether to include the fully-connected
        layer at the top of the network. Defaults to True.
    weights: One of `None` (random initialization),
          'imagenet' (pre-training on ImageNet),
          or the path to the weights file to be loaded. Defaults to 'imagenet'.
    input_tensor: Optional Keras tensor
        (i.e. output of `layers.Input()`)
        to use as image input for the model.
    input_shape: Optional shape tuple, only to be specified
        if `include_top` is False.
        It should have exactly 3 inputs channels.
    pooling: Optional pooling mode for feature extraction
        when `include_top` is `False`. Defaults to None.
        - `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. Defaults to 1000 (number of
        ImageNet classes).
    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.
        Defaults to 'softmax'.
        When loading pretrained weights, `classifier_activation` can only
        be `None` or `"softmax"`.

  Returns:
    A `keras.Model` instance.
)gZd;O?gy&1?g?皙?   swishdefaultefficientnetimagenet  softmaxc                    s  |dkrt }|
dv s*tjj|
s*td|
dkrF|	rF|dkrFtdtj||dt	 |	|
d}|d	u rvt
j|d
}nt|st
j||d}n|}t	 dkrdnd}|ffdd	} fdd|}t
d|}t
j|d|}|
dkr
t
dtjt |}t
jt|ddd|}t
j|dddddtdd|}t
j|dd|}t
j|dd |}t|}d!}ttfd"d#|D }t|D ]\}}|d$ d!ksJ ||d% |d%< ||d& |d&< t|d$D ]`}|d!krd|d'< |d& |d%< t|||| | fd(d) |d t!|d* i|}|d7 }qqt
j|d+dd,dtd-d.|}t
j|d/d|}t
j|d0d |}|	rt
j"d1d |}|d!krt
j#|d2d |}t$||
 t
j%||t&d3d4|}n6|d5krt
j"d1d |}n|d6krt
j'd7d |}|d	ur.t()|}n|}t*j+|||d }|
dkr|	rld8}t,|d9d	  d! }nd:}t,|d9d	  d }|| }t-j.|t/| d;|d<}|0| n|
d	ur|0|
 |S )=aT	  Instantiates the EfficientNet architecture using given scaling coefficients.

    Args:
      width_coefficient: float, scaling coefficient for network width.
      depth_coefficient: float, scaling coefficient for network depth.
      default_size: integer, default input image size.
      dropout_rate: float, dropout rate before final classifier layer.
      drop_connect_rate: float, dropout rate at skip connections.
      depth_divisor: integer, a unit of network width.
      activation: activation function.
      blocks_args: list of dicts, parameters to construct block modules.
      model_name: string, model name.
      include_top: whether to include the fully-connected
          layer at the top of the network.
      weights: one of `None` (random initialization),
            'imagenet' (pre-training on ImageNet),
            or the path to the weights file to be loaded.
      input_tensor: optional Keras tensor
          (i.e. output of `layers.Input()`)
          to use as image input for the model.
      input_shape: optional shape tuple, only to be specified
          if `include_top` is False.
          It should have exactly 3 inputs channels.
      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.

    Returns:
      A `keras.Model` instance.

    Raises:
      ValueError: in case of invalid argument for `weights`,
        or invalid input shape.
      ValueError: if `classifier_activation` is not `softmax` or `None` when
        using a pretrained top layer.
    r.   >   Nr0   zThe `weights` argument should be either `None` (random initialization), `imagenet` (pre-training on ImageNet), or the path to the weights file to be loaded.r0   r1   zWIf using `weights` as `"imagenet"` with `include_top` as true, `classes` should be 1000r   )default_sizemin_sizedata_formatrequire_flattenweightsN)shape)tensorr8   channels_lastr   r   c                    sB   |  9 } t |t| |d  | | }|d|  k r:||7 }t|S )z2Round number of filters based on depth multiplier.r   g?)maxint)filtersdivisorZnew_filters)width_coefficient [/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/applications/efficientnet.pyround_filtersT  s    z#EfficientNet.<locals>.round_filtersc                    s   t t |  S )z2Round number of repeats based on depth multiplier.)r<   mathceil)r   )depth_coefficientr@   rA   round_repeats_  s    z#EfficientNet.<locals>.round_repeatsgp?)axis      ?Zstem_conv_padpaddingnamer   validFZ	stem_conv)r   rJ   use_biaskernel_initializerrK   Zstem_bnrG   rK   Zstem_activationrK   r   c                 3   s   | ]} |d  V  qdS )r   Nr@   ).0args)rF   r@   rA   	<genexpr>      zEfficientNet.<locals>.<genexpr>r   r   r   r   rK   z
block{}{}_a   i   sameZtop_convrJ   rM   rN   rK   Ztop_bnZtop_activationavg_poolZtop_dropoutpredictions)
activationrN   rK   avgr;   max_poolz.h5z	_notop.h5models)cache_subdir	file_hash)1DEFAULT_BLOCKS_ARGStfiogfileexists
ValueErrorr   obtain_input_shaper   image_data_formatlayersInputis_keras_tensor	RescalingNormalizationrC   sqrtIMAGENET_STDDEV_RGBZeroPadding2Dcorrect_padConv2DCONV_KERNEL_INITIALIZERBatchNormalization
Activationcopydeepcopyfloatsum	enumeraterangepopblockformatchrGlobalAveragePooling2DDropoutvalidate_activationDenseDENSE_KERNEL_INITIALIZERGlobalMaxPooling2Dr   get_source_inputsr   ModelWEIGHTS_HASHESr   get_fileBASE_WEIGHTS_PATHload_weights)r?   rE   r3   Zdropout_rateZdrop_connect_rateZdepth_divisorrZ   Zblocks_args
model_nameinclude_topr7   input_tensorinput_shapepoolingclassesclassifier_activation	img_inputbn_axisrB   xbblocksirR   jinputsmodelfile_suffixr`   	file_nameweights_pathr@   )rE   rF   r?   rA   EfficientNet   s    D	

	









r            c                 C   sB  t  dkrdnd}|| }|dkrptj|dddt|d d| }tj||d d	|}tj||d
 d|}n| }|dkrtjt	|||d d|}d}nd}tj
|||dt|d d|}tj||d d	|}tj||d d|}d|	  k rdkrn ntdt||	 }tj|d d|}|dkrF|ddf}n
dd|f}tj||d d|}tj|dd|t|d d|}tj|dddt|d d|}tj||g|d d}tj|dddt|d d|}tj||d d	|}|
r>|dkr>||kr>|dkr(tj|d|d d |}tj|| g|d! d}|S )"a  An inverted residual block.

    Args:
        inputs: input tensor.
        activation: activation function.
        drop_rate: float between 0 and 1, fraction of the input units to drop.
        name: string, block label.
        filters_in: integer, the number of input filters.
        filters_out: integer, the number of output filters.
        kernel_size: integer, the dimension of the convolution window.
        strides: integer, the stride of the convolution.
        expand_ratio: integer, scaling coefficient for the input filters.
        se_ratio: float between 0 and 1, fraction to squeeze the input filters.
        id_skip: boolean.

    Returns:
        output tensor for the block.
    r:   r   r   rV   FZexpand_convrW   Z	expand_bnrO   Zexpand_activationrP   r   Z
dwconv_padrI   rL   Zdwconv)r   rJ   rM   depthwise_initializerrK   bnrZ   r   Z
se_squeezeZ
se_reshapeZ	se_reduce)rJ   rZ   rN   rK   sigmoidZ	se_expandZ	se_exciteZproject_convZ
project_bn)Nr   r   r   drop)noise_shaperK   add)r   rh   ri   rr   rs   rt   ru   rp   r   rq   DepthwiseConv2Dr;   r<   r   Reshapemultiplyr   r   )r   rZ   Z	drop_raterK   r   r   r   r   r   r   r   r   r=   r   Zconv_padZ
filters_seseZse_shaper@   r@   rA   r}     s    




r}   z.keras.applications.efficientnet.EfficientNetB0z!keras.applications.EfficientNetB0c                 K   s    t dd| ||||||d|S )N)rH   rH      r+   Zefficientnetb0r   r   r7   r   r   r   r   r   r   r   r7   r   r   r   r   r   kwargsr@   r@   rA   EfficientNetB0H  s    r   z.keras.applications.efficientnet.EfficientNetB1z!keras.applications.EfficientNetB1c                 K   s    t dd| ||||||d|S )N)rH   皙?   r+   Zefficientnetb1r   r   r   r@   r@   rA   EfficientNetB1g  s    r   z.keras.applications.efficientnet.EfficientNetB2z!keras.applications.EfficientNetB2c                 K   s    t dd| ||||||d|S )N)r   333333?i  333333?Zefficientnetb2r   r   r   r@   r@   rA   EfficientNetB2  s    r   z.keras.applications.efficientnet.EfficientNetB3z!keras.applications.EfficientNetB3c                 K   s    t dd| ||||||d|S )N)r   ffffff?i,  r   Zefficientnetb3r   r   r   r@   r@   rA   EfficientNetB3  s    r   z.keras.applications.efficientnet.EfficientNetB4z!keras.applications.EfficientNetB4c                 K   s    t dd| ||||||d|S )N)r   ?i|  皙?Zefficientnetb4r   r   r   r@   r@   rA   EfficientNetB4  s    r   z.keras.applications.efficientnet.EfficientNetB5z!keras.applications.EfficientNetB5c                 K   s    t dd| ||||||d|S )N)g?g@i  r   Zefficientnetb5r   r   r   r@   r@   rA   EfficientNetB5  s    r   z.keras.applications.efficientnet.EfficientNetB6z!keras.applications.EfficientNetB6c                 K   s    t dd| ||||||d|S )N)r   g@i        ?Zefficientnetb6r   r   r   r@   r@   rA   EfficientNetB6  s    r   z.keras.applications.efficientnet.EfficientNetB7z!keras.applications.EfficientNetB7c                 K   s    t dd| ||||||d|S )N)r"   g@iX  r   Zefficientnetb7r   r   r   r@   r@   rA   EfficientNetB7!  s    r   rP   z0keras.applications.efficientnet.preprocess_inputc                 C   s   | S )a  A placeholder method for backward compatibility.

    The preprocessing logic has been included in the efficientnet model
    implementation. Users are no longer required to call this method to
    normalize the input data. This method does nothing and only kept as a
    placeholder to align the API surface between old and new version of model.

    Args:
      x: A floating point `numpy.array` or a `tf.Tensor`.
      data_format: Optional data format of the image tensor/array. Defaults to
        None, in which case the global setting
        `tf.keras.backend.image_data_format()` is used (unless you changed it,
        it defaults to "channels_last").{mode}

    Returns:
      Unchanged `numpy.array` or `tf.Tensor`.
    r@   )r   r5   r@   r@   rA   preprocess_inputJ  s    r   z2keras.applications.efficientnet.decode_predictionsc                 C   s   t j| |dS )N)top)r   decode_predictions)predsr   r@   r@   rA   r   `  s    r   )r+   r+   r,   r-   r.   r/   Tr0   NNNr1   r2   )
r-   r   r   r   r   r   r   r   r   T)Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )Tr0   NNNr1   r2   )N)r   ))__doc__rv   rC   Ztensorflow.compat.v2compatv2rb   kerasr   Zkeras.applicationsr   keras.enginer   keras.layersr   keras.utilsr   r    tensorflow.python.util.tf_exportr   r   r   ra   rs   r   ri   BASE_DOCSTRINGro   r   r}   r   r   r   r   r   r   r   r   r~   r   r   r@   r@   r@   rA   <module>   s  %J
	?             
 m          
s                                                        