




'''simple docstring'''


import warnings

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import pairwise_distances

warnings.filterwarnings('ignore')

lowerCAmelCase_			:     List[Any]							    =     'K-MEANS-CLUST/ '



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Dict   ,						UpperCamelCase__						:				str   ,						UpperCamelCase__						:				int=None							):




     """simple docstring"""


     if seed is not None:  # useful for obtaining consistent results
          np.random.seed(UpperCamelCase__							)
     a_    :       Dict    	=     data.shape[0]  # number of data points

     # Pick K indices from range [0, N).
     a_    :       List[str]    	=     np.random.randint(0   ,						UpperCamelCase__   ,						UpperCamelCase__							)

     # Keep centroids as dense format, as many entries will be nonzero due to averaging.
     # As long as at least one document in a cluster contains a word,
     # it will carry a nonzero weight in the TF-IDF vector of the centroid.
     a_    :       int    	=     data[rand_indices, :]

     return centroids



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				List[Any]   ,						UpperCamelCase__						:				List[Any]							):




     """simple docstring"""


     return pairwise_distances(UpperCamelCase__   ,						UpperCamelCase__   ,						metric="""euclidean"""							)



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[int]   ,						UpperCamelCase__						:				List[str]							):




     """simple docstring"""


     a_    :       Optional[Any]    	=     centroid_pairwise_dist(UpperCamelCase__   ,						UpperCamelCase__							)

     # Compute cluster assignments for each data point:
     # Fill in the blank (RHS only)
     a_    :       Optional[int]    	=     np.argmin(UpperCamelCase__   ,						axis=1							)

     return cluster_assignment



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[int]   ,						UpperCamelCase__						:				Tuple   ,						UpperCamelCase__						:				Tuple							):




     """simple docstring"""


     a_    :       Union[str, Any]    	=     []
     for i in range(UpperCamelCase__							):
          # Select all data points that belong to cluster i. Fill in the blank (RHS only)
          a_    :       List[str]    	=     data[cluster_assignment == i]
          # Compute the mean of the data points. Fill in the blank (RHS only)
          a_    :       int    	=     member_data_points.mean(axis=0							)
          new_centroids.append(UpperCamelCase__							)
     a_    :       List[Any]    	=     np.array(UpperCamelCase__							)

     return new_centroids



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[int]   ,						UpperCamelCase__						:				Dict   ,						UpperCamelCase__						:				Any   ,						UpperCamelCase__						:				int							):




     """simple docstring"""


     a_    :       Optional[int]    	=     0.0
     for i in range(UpperCamelCase__							):
          # Select all data points that belong to cluster i. Fill in the blank (RHS only)
          a_    :       Any    	=     data[cluster_assignment == i, :]

          if member_data_points.shape[0] > 0:  # check if i-th cluster is non-empty
               # Compute distances from centroid to data points (RHS only)
               a_    :       Optional[int]    	=     pairwise_distances(
                   UpperCamelCase__   ,						[centroids[i]]   ,						metric="""euclidean"""							)
               a_    :       str    	=     distances**2
               heterogeneity += np.sum(UpperCamelCase__							)

     return heterogeneity



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[Any]   ,						UpperCamelCase__						:				int							):




     """simple docstring"""


     plt.figure(figsize=(7, 4)							)
     plt.plot(UpperCamelCase__   ,						linewidth=4							)
     plt.xlabel("""# Iterations"""							)
     plt.ylabel("""Heterogeneity"""							)
     plt.title(F"Heterogeneity of clustering over time, K={k:d}"							)
     plt.rcParams.update({"""font.size""": 16}							)
     plt.show()



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Any   ,						UpperCamelCase__						:				Union[str, Any]   ,						UpperCamelCase__						:				List[str]   ,						UpperCamelCase__						:				Optional[Any]=500   ,						UpperCamelCase__						:				Dict=None   ,						UpperCamelCase__						:				int=False							):




     """simple docstring"""


     a_    :       List[str]    	=     initial_centroids[:]
     a_    :       str    	=     None

     for itr in range(UpperCamelCase__							):
          if verbose:
               print(UpperCamelCase__   ,						end=""""""							)

          # 1. Make cluster assignments using nearest centroids
          a_    :       str    	=     assign_clusters(UpperCamelCase__   ,						UpperCamelCase__							)

          # 2. Compute a new centroid for each of the k clusters, averaging all data
          #    points assigned to that cluster.
          a_    :       Union[str, Any]    	=     revise_centroids(UpperCamelCase__   ,						UpperCamelCase__   ,						UpperCamelCase__							)

          # Check for convergence: if none of the assignments changed, stop
          if (
              prev_cluster_assignment is not None
              and (prev_cluster_assignment == cluster_assignment).all()
          ):
               break

          # Print number of new assignments
          if prev_cluster_assignment is not None:
               a_    :       Optional[Any]    	=     np.sum(prev_cluster_assignment != cluster_assignment							)
               if verbose:
                    print(
                        F"    {num_changed:5d} elements changed their cluster assignment."							)

        # Record heterogeneity convergence metric
          if record_heterogeneity is not None:
               # YOUR CODE HERE
               a_    :       List[Any]    	=     compute_heterogeneity(UpperCamelCase__   ,						UpperCamelCase__   ,						UpperCamelCase__   ,						UpperCamelCase__							)
               record_heterogeneity.append(UpperCamelCase__							)

          a_    :       str    	=     cluster_assignment[:]

     return centroids, cluster_assignment


# Mock test below
if False:  # change to true to run this test case.
       from sklearn import datasets as ds

       lowerCAmelCase_			:     Optional[Any]							    =     ds.load_iris()
       lowerCAmelCase_			:     Dict							    =     3
       lowerCAmelCase_			:     Dict							    =     []
       lowerCAmelCase_			:     Any							    =     get_initial_centroids(dataset['data'], k, seed=0)
       lowerCAmelCase_			:     Tuple							    =     kmeans(
           dataset['data'],
           k,
           initial_centroids,
           maxiter=400,
           record_heterogeneity=heterogeneity,
           verbose=True,
       )
       plot_heterogeneity(heterogeneity, k)



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				pd.DataFrame   ,						UpperCamelCase__						:				np.ndarray   ,						UpperCamelCase__						:				List[Any]=None							):




     """simple docstring"""


     if fill_missing_report:
          a_    :       Optional[Any]    	=     df.fillna(value=UpperCamelCase__							)
     a_    :       Dict    	=     1
     a_    :       Dict    	=     df.select_dtypes(np.number							).columns
     a_    :       List[str]    	=     (
         df.groupby(["""Cluster"""]							)[  # construct report dataframe
             numeric_cols
         ]  # group by cluster number
         .agg(
             [
                 ("""sum""", np.sum),
                 ("""mean_with_zeros""", lambda UpperCamelCase__							: np.mean(np.nan_to_num(UpperCamelCase__							)							)),
                 ("""mean_without_zeros""", lambda UpperCamelCase__							: x.replace(0   ,						np.NaN							).mean()),
                 (
                     """mean_25-75""",
                     lambda UpperCamelCase__							: np.mean(
                         np.nan_to_num(
                             sorted(UpperCamelCase__							)[
                                 round(len(UpperCamelCase__							) * 25 / 100							) : round(len(UpperCamelCase__							) * 75 / 100							)
                             ]							)							),
                 ),
                 ("""mean_with_na""", np.mean),
                 ("""min""", lambda UpperCamelCase__							: x.min()),
                 ("""5%""", lambda UpperCamelCase__							: x.quantile(0.05							)),
                 ("""25%""", lambda UpperCamelCase__							: x.quantile(0.25							)),
                 ("""50%""", lambda UpperCamelCase__							: x.quantile(0.50							)),
                 ("""75%""", lambda UpperCamelCase__							: x.quantile(0.75							)),
                 ("""95%""", lambda UpperCamelCase__							: x.quantile(0.95							)),
                 ("""max""", lambda UpperCamelCase__							: x.max()),
                 ("""count""", lambda UpperCamelCase__							: x.count()),
                 ("""stdev""", lambda UpperCamelCase__							: x.std()),
                 ("""mode""", lambda UpperCamelCase__							: x.mode()[0]),
                 ("""median""", lambda UpperCamelCase__							: x.median()),
                 ("""# > 0""", lambda UpperCamelCase__							: (x > 0).sum()),
             ]							)
         .T.reset_index()
         .rename(index=UpperCamelCase__   ,						columns={"""level_0""": """Features""", """level_1""": """Type"""}							)
     )  # rename columns
     # calculate the size of cluster(count of clientID's)
     a_    :       Union[str, Any]    	=     report[
         (report["""Features"""] == """dummy""") & (report["""Type"""] == """count""")
     ].copy()  # avoid SettingWithCopyWarning
     a_    :       int    	=     (
         """ClusterSize"""  # rename created cluster df to match report column names
     )
     a_    :       Tuple    	=     """# of Customers"""
     a_    :       str    	=     pd.DataFrame(
         clustersize.iloc[:, 2:].values
         / clustersize.iloc[:, 2:].values.sum()							)
     a_    :       Dict    	=     """% of Customers"""  # rename created cluster df to match report column names
     a_    :       List[Any]    	=     """ClusterProportion"""
     a_    :       Dict    	=     clusterproportion.columns.tolist()
     a_    :       Dict    	=     cols[-2:] + cols[:-2]
     a_    :       Any    	=     clusterproportion[cols]  # rearrange columns to match report
     a_    :       int    	=     report.columns
     a_    :       Optional[Any]    	=     pd.DataFrame(
         abs(
             report[report["""Type"""] == """count"""].iloc[:, 2:].values
             - clustersize.iloc[:, 2:].values							)							)  # generating df with count of nan values
     a_    :       Optional[Any]    	=     0
     a_    :       Union[str, Any]    	=     """# of nan"""
     a_    :       List[Any]    	=     report[
         report["""Type"""] == """count"""
     ].Features.tolist()  # filling values in order to match report
     a_    :       Union[str, Any]    	=     a.columns.tolist()
     a_    :       int    	=     cols[-2:] + cols[:-2]
     a_    :       Dict    	=     a[cols]  # rearrange columns to match report
     a_    :       Tuple    	=     report.columns  # rename columns to match report
     a_    :       str    	=     report.drop(
         report[report.Type == """count"""].index							)  # drop count values except cluster size
     a_    :       Optional[int]    	=     pd.concat(
         [report, a, clustersize, clusterproportion]   ,						axis=0							)  # concat report with clustert size and nan values
     a_    :       Any    	=     report["""Features"""].isin(UpperCamelCase__							)
     a_    :       Optional[int]    	=     report.columns.tolist()
     a_    :       Dict    	=     cols[0:2] + cols[-1:] + cols[2:-1]
     a_    :       List[str]    	=     report[cols]
     a_    :       Optional[Any]    	=     {
         """ClusterSize""": 9,
         """ClusterProportion""": 8,
         """mean_with_zeros""": 7,
         """mean_with_na""": 6,
         """max""": 5,
         """50%""": 4,
         """min""": 3,
         """25%""": 2,
         """75%""": 1,
         """# of nan""": 0,
         """# > 0""": -1,
         """sum_with_na""": -2,
     }
     a_    :       int    	=     (
         report.assign(
             Sortera=lambda UpperCamelCase__							: x.Type.map(UpperCamelCase__							)   ,						Sortera=lambda UpperCamelCase__							: list(reversed(range(len(UpperCamelCase__							)							)							)							)   ,						)
         .sort_values(["""Sorter1""", """Mark""", """Sorter2"""]   ,						ascending=UpperCamelCase__							)
         .drop(["""Sorter1""", """Sorter2"""]   ,						axis=1							)
     )
     a_    :       Optional[Any]    	=     """"""
     a_    :       Optional[Any]    	=     report.reset_index()
     a_    :       Union[str, Any]    	=     report.drop(columns=["""index"""]							)
     return report


if __name__ == "__main__":
       import doctest

       doctest.testmod()






'''simple docstring'''


import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import EfficientNetForImageClassification, EfficientNetModel
 from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Dict	,	lowercase__      :     Any	,	lowercase__      :     Tuple=13	,	lowercase__      :     Any=32	,	lowercase__      :     List[str]=3	,	lowercase__      :     Any=[3, 3, 5]	,	lowercase__      :     int=[32, 16, 24]	,	lowercase__      :     str=[16, 24, 40]	,	lowercase__      :     Optional[Any]=[1, 1, 2]	,	lowercase__      :     int=[1, 1, 2]	,	lowercase__      :     Tuple=[1, 6, 6]	,	lowercase__      :     Optional[Any]=True	,	lowercase__      :     Union[str, Any]=True	,	lowercase__      :     List[str]=37	,	lowercase__      :     Optional[int]="gelu"	,	lowercase__      :     str=10	,	):


           '''simple docstring'''

           a_    :       Dict    	=     parent
           a_    :       Any    	=     batch_size
           a_    :       str    	=     image_size
           a_    :       Tuple    	=     num_channels
           a_    :       Dict    	=     kernel_sizes
           a_    :       List[Any]    	=     in_channels
           a_    :       int    	=     out_channels
           a_    :       Union[str, Any]    	=     strides
           a_    :       List[Any]    	=     num_block_repeats
           a_    :       List[Any]    	=     expand_ratios
           a_    :       Dict    	=     is_training
           a_    :       Optional[int]    	=     hidden_act
           a_    :       List[Any]    	=     num_labels
           a_    :       List[str]    	=     use_labels






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

           a_    :       int    	=     None
           if self.use_labels:
                a_    :       int    	=     ids_tensor([self.batch_size]	,	self.num_labels					)

           a_    :       List[Any]    	=     self.get_config()
           return config, pixel_values, labels






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           return EfficientNetConfig(
               num_channels=self.num_channels	,	kernel_sizes=self.kernel_sizes	,	in_channels=self.in_channels	,	out_channels=self.out_channels	,	strides=self.strides	,	num_block_repeats=self.num_block_repeats	,	expand_ratios=self.expand_ratios	,	hidden_act=self.hidden_act	,	num_labels=self.num_labels	,	)






      def        lowercase_	(   self      :     int	,	lowercase__      :     Any	,	lowercase__      :     Any	,	lowercase__      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Tuple    	=     EfficientNetModel(config=lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       Optional[int]    	=     model(lowercase__					)
           # expected last hidden states: B, C, H // 4, W // 4
           self.parent.assertEqual(
               result.last_hidden_state.shape	,	(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)	,	)






      def        lowercase_	(   self      :     Optional[Any]	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Any	,	lowercase__      :     str					):


           '''simple docstring'''

           a_    :       Dict    	=     EfficientNetForImageClassification(lowercase__					)
           model.to(lowercase__					)
           model.eval()
           a_    :       str    	=     model(lowercase__	,	labels=lowercase__					)
           self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)					)






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           a_    :       Union[str, Any]    	=     self.prepare_config_and_inputs()
           a_	,    a_	,    a_    :       Optional[Any]    	=     config_and_inputs
           a_    :       str    	=     {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					Any             =				(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
      __magic_name__     :					List[Any]             =				(
          {'''feature-extraction''': EfficientNetModel, '''image-classification''': EfficientNetForImageClassification}
          if is_torch_available()
          else {}
      )

      __magic_name__     :					int             =				False
      __magic_name__     :					Dict             =				False
      __magic_name__     :					Dict             =				False
      __magic_name__     :					Union[str, Any]             =				False
      __magic_name__     :					Optional[int]             =				False






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     EfficientNetModelTester(self					)
           a_    :       Union[str, Any]    	=     ConfigTester(
               self	,	config_class=lowercase__	,	has_text_modality=lowercase__	,	hidden_size=37					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           self.create_and_test_config_common_properties()
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           return






      @unittest.skip(reason="""EfficientNet does not use inputs_embeds"""					)
      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""					)
      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           pass






      @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""					)
      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           a_	,    a_    :       Dict    	=     self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_    :       Tuple    	=     model_class(lowercase__					)
                a_    :       int    	=     inspect.signature(model.forward					)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                a_    :       Any    	=     [*signature.parameters.keys()]

                a_    :       Dict    	=     ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]	,	lowercase__					)






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Tuple    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__					)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__      :     Optional[int]	,	lowercase__      :     List[Any]	,	lowercase__      :     Tuple					):
                a_    :       str    	=     model_class(lowercase__					)
                model.to(lowercase__					)
                model.eval()

                with torch.no_grad():
                     a_    :       Tuple    	=     model(**self._prepare_for_class(lowercase__	,	lowercase__					)					)

                a_    :       Tuple    	=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                a_    :       Tuple    	=     sum(config.num_block_repeats					) * 4
                self.assertEqual(len(lowercase__					)	,	lowercase__					)

                # EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]					)	,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]	,	)

           a_	,    a_    :       Any    	=     self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_    :       Any    	=     True
                check_hidden_states_output(lowercase__	,	lowercase__	,	lowercase__					)

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                a_    :       Any    	=     True

                check_hidden_states_output(lowercase__	,	lowercase__	,	lowercase__					)






      def        lowercase_	(   self      :     Union[str, Any]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase__					)






      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           pass






      @slow
      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                a_    :       List[str]    	=     EfficientNetModel.from_pretrained(lowercase__					)
                self.assertIsNotNone(lowercase__					)






      @is_pipeline_test
      @require_vision
      @slow
      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           super().test_pipeline_image_classification()



def    _SCREAMING_SNAKE_CASE    (			):




     """simple docstring"""


     a_    :       List[str]    	=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
     return image







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      @cached_property
      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""					) if is_vision_available() else None






      @slow
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""					).to(lowercase__					)

           a_    :       Any    	=     self.default_image_processor
           a_    :       List[str]    	=     prepare_img()
           a_    :       str    	=     image_processor(images=lowercase__	,	return_tensors="""pt"""					).to(lowercase__					)

           # forward pass
           with torch.no_grad():
                a_    :       Tuple    	=     model(**lowercase__					)

           # verify the logits
           a_    :       Dict    	=     torch.Size((1, 1000)					)
           self.assertEqual(outputs.logits.shape	,	lowercase__					)

           a_    :       List[Any]    	=     torch.tensor([0.0001, 0.0002, 0.0002]					).to(lowercase__					)
           self.assertTrue(torch.allclose(outputs.logits[0, :3]	,	lowercase__	,	atol=1e-4					)					)
