

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












'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase__      :   Any      	=			{
    "configuration_open_llama": ["OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "OpenLlamaConfig"],
}

try:
			if not is_sentencepiece_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase__      :   Optional[int]      	=			["LlamaTokenizer"]

try:
			if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase__      :   int      	=			["LlamaTokenizerFast"]

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			lowerCAmelCase__      :   int      	=			[
			    "OpenLlamaForCausalLM",
			    "OpenLlamaModel",
			    "OpenLlamaPreTrainedModel",
			    "OpenLlamaForSequenceClassification",
			]


if TYPE_CHECKING:
			from .configuration_open_llama import OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenLlamaConfig

			try:
						if not is_sentencepiece_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from transformers import LlamaTokenizer

			try:
						if not is_tokenizers_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from transformers import LlamaTokenizerFast

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_open_llama import (
						    OpenLlamaForCausalLM,
						    OpenLlamaForSequenceClassification,
						    OpenLlamaModel,
						    OpenLlamaPreTrainedModel,
						)


else:
			import sys

			lowerCAmelCase__      :   Dict      	=			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




