code: 
  
  
  
  
  
  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_   =   "K-MEANS-CLUST/ "
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_=None  )			->						Dict:
         if seed is not None:  # useful for obtaining consistent results
                np.random.seed(lowercase_  )
         _snake_case      :							Dict     				=						data.shape[0]  # number of data points
  
         # Pick K indices from range [0, N).
         _snake_case      :							List[str]     				=						np.random.randint(0      ,		lowercase_      ,		lowercase_  )
  
         # 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.
         _snake_case      :							str     				=						data[rand_indices, :]
  
         return centroids
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_  )			->						Dict:
         return pairwise_distances(lowercase_      ,		lowercase_      ,		metric='''euclidean'''  )
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_  )			->						Tuple:
         # Compute distances between each data point and the set of centroids:
         # Fill in the blank (RHS only)
         _snake_case      :							Optional[int]     				=						centroid_pairwise_dist(lowercase_      ,		lowercase_  )
  
         # Compute cluster assignments for each data point:
         # Fill in the blank (RHS only)
         _snake_case      :							Optional[Any]     				=						np.argmin(lowercase_      ,		axis=1  )
  
         return cluster_assignment
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_  )			->						str:
         _snake_case      :							Dict     				=						[]
         for i in range(lowercase_  ):
                # Select all data points that belong to cluster i. Fill in the blank (RHS only)
                _snake_case      :							str     				=						data[cluster_assignment == i]
                # Compute the mean of the data points. Fill in the blank (RHS only)
                _snake_case      :							Optional[int]     				=						member_data_points.mean(axis=0  )
                new_centroids.append(lowercase_  )
         _snake_case      :							Tuple     				=						np.array(lowercase_  )
  
         return new_centroids
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_  )			->						List[Any]:
         _snake_case      :							Dict     				=						0.0
         for i in range(lowercase_  ):
                # Select all data points that belong to cluster i. Fill in the blank (RHS only)
                _snake_case      :							Union[str, 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)
                       _snake_case      :							Tuple     				=						pairwise_distances(
                           lowercase_      ,		[centroids[i]]      ,		metric='''euclidean'''  )
                       _snake_case      :							str     				=						distances**2
                       heterogeneity += np.sum(lowercase_  )
  
         return heterogeneity
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_  )			->						List[Any]:
         plt.figure(figsize=(7, 4)  )
         plt.plot(lowercase_      ,		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 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_=500      ,		lowercase_=None      ,		lowercase_=False  )			->						Any:
         _snake_case      :							List[Any]     				=						initial_centroids[:]
         _snake_case      :							List[str]     				=						None
  
         for itr in range(lowercase_  ):
                if verbose:
                       print(lowercase_      ,		end=''''''  )
  
                # 1. Make cluster assignments using nearest centroids
                _snake_case      :							Dict     				=						assign_clusters(lowercase_      ,		lowercase_  )
  
                # 2. Compute a new centroid for each of the k clusters, averaging all data
                #    points assigned to that cluster.
                _snake_case      :							Tuple     				=						revise_centroids(lowercase_      ,		lowercase_      ,		lowercase_  )
  
                # 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:
                       _snake_case      :							Dict     				=						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
                       _snake_case      :							Optional[Any]     				=						compute_heterogeneity(lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_  )
                       record_heterogeneity.append(lowercase_  )
  
                _snake_case      :							List[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_   =   ds.load_iris()
     lowerCAmelCase_   =   3
     lowerCAmelCase_   =   []
     lowerCAmelCase_   =   get_initial_centroids(dataset["data"], k, seed=0)
     lowerCAmelCase_ ,    lowerCAmelCase_   =   kmeans(
         dataset["data"],
         k,
         initial_centroids,
         maxiter=4_0_0,
         record_heterogeneity=heterogeneity,
         verbose=True,
     )
     plot_heterogeneity(heterogeneity, k)
  
  
  
  
  def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_=None  )			->						pd.DataFrame:
         # Fill missing values with given rules
         if fill_missing_report:
                _snake_case      :							Tuple     				=						df.fillna(value=lowercase_  )
         _snake_case      :							Tuple     				=						1
         _snake_case      :							Dict     				=						df.select_dtypes(np.number  ).columns
         _snake_case      :							int     				=						(
             df.groupby(['''Cluster''']  )[  # construct report dataframe
                 numeric_cols
             ]  # group by cluster number
             .agg(
                 [
                     ('''sum''', np.sum),
                     ('''mean_with_zeros''', lambda lowercase_  : np.mean(np.nan_to_num(lowercase_  )  )),
                     ('''mean_without_zeros''', lambda lowercase_  : x.replace(0      ,		np.NaN  ).mean()),
                     (
                         '''mean_25-75''',
                         lambda lowercase_  : np.mean(
                             np.nan_to_num(
                                 sorted(lowercase_  )[
                                     round(len(lowercase_  ) * 25 / 100  ) : round(len(lowercase_  ) * 75 / 100  )
                                 ]  )  ),
                     ),
                     ('''mean_with_na''', np.mean),
                     ('''min''', lambda lowercase_  : x.min()),
                     ('''5%''', lambda lowercase_  : x.quantile(0.05  )),
                     ('''25%''', lambda lowercase_  : x.quantile(0.25  )),
                     ('''50%''', lambda lowercase_  : x.quantile(0.50  )),
                     ('''75%''', lambda lowercase_  : x.quantile(0.75  )),
                     ('''95%''', lambda lowercase_  : x.quantile(0.95  )),
                     ('''max''', lambda lowercase_  : x.max()),
                     ('''count''', lambda lowercase_  : x.count()),
                     ('''stdev''', lambda lowercase_  : x.std()),
                     ('''mode''', lambda lowercase_  : x.mode()[0]),
                     ('''median''', lambda lowercase_  : x.median()),
                     ('''# > 0''', lambda lowercase_  : (x > 0).sum()),
                 ]  )
             .T.reset_index()
             .rename(index=lowercase_      ,		columns={'''level_0''': '''Features''', '''level_1''': '''Type'''}  )
         )  # rename columns
         # calculate the size of cluster(count of clientID's)
         _snake_case      :							Dict     				=						report[
             (report['''Features'''] == '''dummy''') & (report['''Type'''] == '''count''')
         ].copy()  # avoid SettingWithCopyWarning
         _snake_case      :							List[str]     				=						(
             '''ClusterSize'''  # rename created cluster df to match report column names
         )
         _snake_case      :							Optional[Any]     				=						'''# of Customers'''
         _snake_case      :							str     				=						pd.DataFrame(
             clustersize.iloc[:, 2:].values
             / clustersize.iloc[:, 2:].values.sum()  )
         _snake_case      :							Tuple     				=						'''% of Customers'''  # rename created cluster df to match report column names
         _snake_case      :							Tuple     				=						'''ClusterProportion'''
         _snake_case      :							List[Any]     				=						clusterproportion.columns.tolist()
         _snake_case      :							Dict     				=						cols[-2:] + cols[:-2]
         _snake_case      :							Union[str, Any]     				=						clusterproportion[cols]  # rearrange columns to match report
         _snake_case      :							Dict     				=						report.columns
         _snake_case      :							Optional[Any]     				=						pd.DataFrame(
             abs(
                 report[report['''Type'''] == '''count'''].iloc[:, 2:].values
                 - clustersize.iloc[:, 2:].values  )  )  # generating df with count of nan values
         _snake_case      :							List[str]     				=						0
         _snake_case      :							int     				=						'''# of nan'''
         _snake_case      :							List[str]     				=						report[
             report['''Type'''] == '''count'''
         ].Features.tolist()  # filling values in order to match report
         _snake_case      :							Tuple     				=						a.columns.tolist()
         _snake_case      :							List[str]     				=						cols[-2:] + cols[:-2]
         _snake_case      :							List[Any]     				=						a[cols]  # rearrange columns to match report
         _snake_case      :							Dict     				=						report.columns  # rename columns to match report
         _snake_case      :							Optional[int]     				=						report.drop(
             report[report.Type == '''count'''].index  )  # drop count values except cluster size
         _snake_case      :							List[str]     				=						pd.concat(
             [report, a, clustersize, clusterproportion]      ,		axis=0  )  # concat report with clustert size and nan values
         _snake_case      :							List[Any]     				=						report['''Features'''].isin(lowercase_  )
         _snake_case      :							Tuple     				=						report.columns.tolist()
         _snake_case      :							Any     				=						cols[0:2] + cols[-1:] + cols[2:-1]
         _snake_case      :							List[str]     				=						report[cols]
         _snake_case      :							List[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,
         }
         _snake_case      :							Optional[Any]     				=						(
             report.assign(
                 Sortera=lambda lowercase_  : x.Type.map(lowercase_  )      ,		Sortera=lambda lowercase_  : list(reversed(range(len(lowercase_  )  )  )  )      ,		)
             .sort_values(['''Sorter1''', '''Mark''', '''Sorter2''']      ,		ascending=lowercase_  )
             .drop(['''Sorter1''', '''Sorter2''']      ,		axis=1  )
         )
         _snake_case      :							Tuple     				=						''''''
         _snake_case      :							List[str]     				=						report.reset_index()
         _snake_case      :							List[str]     				=						report.drop(columns=['''index''']  )
         return report
  
  
  if __name__ == "__main__":
     import doctest
  
     doctest.testmod()
  
  
  
  
  
  
  
style_context: 
  
  
  
  
  
  import unittest
  
  from transformers import load_tool
  from transformers.tools.agent_types import AGENT_TYPE_MAPPING
  
  from .test_tools_common import ToolTesterMixin, output_types
  
  class 				A    (unittest.TestCase       ,__UpperCAmelCase				):
  
  
  
        def    __a (					self					)      ->   str:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							List[Any]     				=						load_tool('''translation'''					)
               self.tool.setup()
               _snake_case      :							Any     				=						load_tool('''translation'''     ,  remote=lowercase_					)
  
  
  
        def    __a (					self					)      ->   Optional[int]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Tuple     				=						self.tool('''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
               self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)
  
  
  
        def    __a (					self					)      ->   Union[str, Any]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Optional[int]     				=						self.remote_tool('''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
               self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)
  
  
  
        def    __a (					self					)      ->   List[Any]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Dict     				=						self.tool(text='''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
               self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)
  
  
  
        def    __a (					self					)      ->   Dict:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							List[Any]     				=						self.remote_tool(text='''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
               self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)
  
  
  
        def    __a (					self					)      ->   str:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Optional[int]     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']
               _snake_case      :							Dict     				=						self.tool(*lowercase_					)
  
               # There is a single output
               if len(self.tool.outputs					) == 1:
                      _snake_case      :							Optional[Any]     				=						[outputs]
  
               self.assertListEqual(output_types(lowercase_					)     ,  self.tool.outputs					)
  
  
  
        def    __a (					self					)      ->   Tuple:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Union[str, Any]     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']
               _snake_case      :							Dict     				=						self.tool(*lowercase_					)
  
               if not isinstance(lowercase_     ,  lowercase_					):
                      _snake_case      :							Optional[Any]     				=						[outputs]
  
               self.assertEqual(len(lowercase_					)     ,  len(self.tool.outputs					)					)
  
               for output, output_type in zip(lowercase_     ,  self.tool.outputs					):
                      _snake_case      :							List[str]     				=						AGENT_TYPE_MAPPING[output_type]
                      self.assertTrue(isinstance(lowercase_     ,  lowercase_					)					)
  
  
  
        def    __a (					self					)      ->   List[Any]:
  
  
  
               '''simple docstring'''
  
               _snake_case      :							Dict     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']
  
               _snake_case      :							Any     				=						[]
  
               for _input, input_type in zip(lowercase_     ,  self.tool.inputs					):
                      if isinstance(lowercase_     ,  lowercase_					):
                             _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input					) for _input_type in input_type]					)
                      else:
                             _inputs.append(AGENT_TYPE_MAPPING[input_type](_input					)					)
  
          # Should not raise an error
               _snake_case      :							List[Any]     				=						self.tool(*lowercase_					)
  
               if not isinstance(lowercase_     ,  lowercase_					):
                      _snake_case      :							Any     				=						[outputs]
  
               self.assertEqual(len(lowercase_					)     ,  len(self.tool.outputs					)					)
  
  
  
  
  
  
  