

"""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')

__A	:       Optional[Any]        =						'K-MEANS-CLUST/ '
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__     ,				lowercase__=None ):
					"""simple docstring"""
					if seed is not None:  # useful for obtaining consistent results
										np.random.seed(lowercase__ )
					A     =   data.shape[0]  # number of data points

					# Pick K indices from range [0, N).
					A     =   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.
					A     =   data[rand_indices, :]

					return centroids
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__ ):
					"""simple docstring"""
					return pairwise_distances(lowercase__     ,				lowercase__     ,				metric="euclidean" )
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__ ):
					"""simple docstring"""
					# Compute distances between each data point and the set of centroids:
					# Fill in the blank (RHS only)
					A     =   centroid_pairwise_dist(lowercase__     ,				lowercase__ )

					# Compute cluster assignments for each data point:
					# Fill in the blank (RHS only)
					A     =   np.argmin(lowercase__     ,				axis=1 )

					return cluster_assignment
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__     ,				lowercase__ ):
					"""simple docstring"""
					A     =   []
					for i in range(lowercase__ ):
										# Select all data points that belong to cluster i. Fill in the blank (RHS only)
										A     =   data[cluster_assignment == i]
										# Compute the mean of the data points. Fill in the blank (RHS only)
										A     =   member_data_points.mean(axis=0 )
										new_centroids.append(lowercase__ )
					A     =   np.array(lowercase__ )

					return new_centroids
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__     ,				lowercase__     ,				lowercase__ ):
					"""simple docstring"""
					A     =   0.0
					for i in range(lowercase__ ):
										# Select all data points that belong to cluster i. Fill in the blank (RHS only)
										A     =   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     =   pairwise_distances(
															    lowercase__     ,				[centroids[i]]     ,				metric="euclidean" )
															A     =   distances**2
															heterogeneity += np.sum(lowercase__ )

					return heterogeneity
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__ ):
					"""simple docstring"""
					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   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__     ,				lowercase__     ,				lowercase__=500     ,				lowercase__=None     ,				lowercase__=False ):
					"""simple docstring"""
					A     =   initial_centroids[:]
					A     =   None

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

										# 1. Make cluster assignments using nearest centroids
										A     =   assign_clusters(lowercase__     ,				lowercase__ )

										# 2. Compute a new centroid for each of the k clusters, averaging all data
										#    points assigned to that cluster.
										A     =   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:
															A     =   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     =   compute_heterogeneity(lowercase__     ,				lowercase__     ,				lowercase__     ,				lowercase__ )
															record_heterogeneity.append(lowercase__ )

										A     =   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

	__A	:       Union[str, Any]        =						ds.load_iris()
	__A	:       List[Any]        =						3
	__A	:       Optional[Any]        =						[]
	__A	:       Optional[int]        =						get_initial_centroids(dataset['data'], k, seed=0)
	__A    ,       __A	:       Dict        =						kmeans(
	    dataset['data'],
	    k,
	    initial_centroids,
	    maxiter=4_00,
	    record_heterogeneity=heterogeneity,
	    verbose=True,
	)
	plot_heterogeneity(heterogeneity, k)
def   __SCREAMING_SNAKE_CASE		(		lowercase__     ,				lowercase__     ,				lowercase__=None ):
					"""simple docstring"""
					# Fill missing values with given rules
					if fill_missing_report:
										A     =   df.fillna(value=lowercase__ )
					A     =   1
					A     =   df.select_dtypes(np.number ).columns
					A     =   (
					    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)
					A     =   report[
					    (report["Features"] == "dummy") & (report["Type"] == "count")
					].copy()  # avoid SettingWithCopyWarning
					A     =   (
					    "ClusterSize"  # rename created cluster df to match report column names
					)
					A     =   "# of Customers"
					A     =   pd.DataFrame(
					    clustersize.iloc[:, 2:].values
					    / clustersize.iloc[:, 2:].values.sum() )
					A     =   "% of Customers"  # rename created cluster df to match report column names
					A     =   "ClusterProportion"
					A     =   clusterproportion.columns.tolist()
					A     =   cols[-2:] + cols[:-2]
					A     =   clusterproportion[cols]  # rearrange columns to match report
					A     =   report.columns
					A     =   pd.DataFrame(
					    abs(
					        report[report["Type"] == "count"].iloc[:, 2:].values
					        - clustersize.iloc[:, 2:].values ) )  # generating df with count of nan values
					A     =   0
					A     =   "# of nan"
					A     =   report[
					    report["Type"] == "count"
					].Features.tolist()  # filling values in order to match report
					A     =   a.columns.tolist()
					A     =   cols[-2:] + cols[:-2]
					A     =   a[cols]  # rearrange columns to match report
					A     =   report.columns  # rename columns to match report
					A     =   report.drop(
					    report[report.Type == "count"].index )  # drop count values except cluster size
					A     =   pd.concat(
					    [report, a, clustersize, clusterproportion]     ,				axis=0 )  # concat report with clustert size and nan values
					A     =   report["Features"].isin(lowercase__ )
					A     =   report.columns.tolist()
					A     =   cols[0:2] + cols[-1:] + cols[2:-1]
					A     =   report[cols]
					A     =   {
					    "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     =   (
					    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 )
					)
					A     =   ""
					A     =   report.reset_index()
					A     =   report.drop(columns=["index"] )
					return report


if __name__ == "__main__":
	import doctest

	doctest.testmod()









from hashlib import mda, shaaaa

__UpperCamelCase							:							Dict    							=					(shaaaa, mda)

class    __magic_name__						:


     def __init__(   self				:  Optional[Any]				,						lowerCamelCase__				:  int = 8      )	->   None:





      '''simple docstring'''






      UpperCamelCase__       :     int 							= 0b0
      UpperCamelCase__       :     Optional[int] 							= size


     def   UpperCAmelCase__						(   self				:  Tuple				,						lowerCamelCase__				:  str      )	->   None:





      '''simple docstring'''






      UpperCamelCase__       :     Union[str, Any] 							= self.hash_(lowerCamelCase__      )
      self.bitarray |= h


     def   UpperCAmelCase__						(   self				:  Any				,						lowerCamelCase__				:  str      )	->   bool:





      '''simple docstring'''






      UpperCamelCase__       :     Any 							= self.hash_(lowerCamelCase__      )
      return (h & self.bitarray) == h


     def __contains__(   self				:  Any				,						lowerCamelCase__				:  str      )	->   bool:





      '''simple docstring'''






      return self.exists(lowerCamelCase__      )


     def   UpperCAmelCase__						(   self				:  Union[str, Any]				,						lowerCamelCase__				:  int      )	->   str:





      '''simple docstring'''






      UpperCamelCase__       :     Optional[int] 							= bin(lowerCamelCase__      )[2:]
      return res.zfill(self.size      )


     @property
     def   UpperCAmelCase__						(   self				:  Tuple      )	->   str:





      '''simple docstring'''






      return self.format_bin(self.bitarray      )


     def   UpperCAmelCase__						(   self				:  int				,						lowerCamelCase__				:  str      )	->   int:





      '''simple docstring'''






      UpperCamelCase__       :     Union[str, Any] 							= 0b0
      for func in HASH_FUNCTIONS:
       UpperCamelCase__       :     Optional[Any] 							= (
           int.from_bytes(func(value.encode()      ).digest()				,						'''little'''      ) % self.size
       )
       res |= 2**position
      return res


     def   UpperCAmelCase__						(   self				:  Union[str, Any]				,						lowerCamelCase__				:  str      )	->   str:





      '''simple docstring'''






      return self.format_bin(self.hash_(lowerCamelCase__      )      )


     @property
     def   UpperCAmelCase__						(   self				:  str      )	->   float:





      '''simple docstring'''






      UpperCamelCase__       :     Tuple 							= bin(self.bitarray      ).count('''1'''      )
      return (n_ones / self.size) ** len(lowerCamelCase__      )


