


from sklearn.metrics import precision_score

import datasets


SCREAMING_SNAKE_CASE__       			=				"""
Precision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:
Precision = TP / (TP + FP)
where TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).
"""


SCREAMING_SNAKE_CASE__       			=				"""
Args:
    predictions (`list` of `int`): Predicted class labels.
    references (`list` of `int`): Actual class labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.

        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.
    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to 'warn'.

        - 0: Returns 0 when there is a zero division.
        - 1: Returns 1 when there is a zero division.
        - 'warn': Raises warnings and then returns 0 when there is a zero division.

Returns:
    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.

Examples:

    Example 1-A simple binary example
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'precision': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['precision'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(results)
        {'precision': 0.23529411764705882}

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'precision': 0.3333333333333333}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)
        >>> print([round(res, 2) for res in results['precision']])
        [0.67, 0.0, 0.0]
"""


SCREAMING_SNAKE_CASE__       			=				"""
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
"""







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,   _KWARGS_DESCRIPTION     )
class     __lowerCamelCase     (  datasets.Metric     ):


							"""simple docstring"""

							def 				A__      (  self  )     ->       Any:






								'''simple docstring'''






								return datasets.MetricInfo(
								    description=_DESCRIPTION						,       citation=_CITATION						,       inputs_description=_KWARGS_DESCRIPTION						,       features=datasets.Features(
								        {
								            "predictions": datasets.Sequence(datasets.Value("int32"  )  ),
								            "references": datasets.Sequence(datasets.Value("int32"  )  ),
								        }
								        if self.config_name == "multilabel"
								        else {
								            "predictions": datasets.Value("int32"  ),
								            "references": datasets.Value("int32"  ),
								        }  )						,       reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html"]						,       )




							def 				A__      (  self						,       UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase=None						,       UpperCAmelCase=1						,       UpperCAmelCase="binary"						,       UpperCAmelCase=None						,       UpperCAmelCase="warn"						,       )     ->       Any:






								'''simple docstring'''






								lowercase_			 = precision_score(
								    UpperCAmelCase						,       UpperCAmelCase						,       labels=UpperCAmelCase						,       pos_label=UpperCAmelCase						,       average=UpperCAmelCase						,       sample_weight=UpperCAmelCase						,       zero_division=UpperCAmelCase						,       )
								return {"precision": float(UpperCAmelCase  ) if score.size == 1 else score}





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

SCREAMING_SNAKE_CASE__       			=				"""K-MEANS-CLUST/ """




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		List[str]  ,			__lowerCamelCase:		List[Any]  ,			__lowerCamelCase:		Tuple=None  ):







	'''simple docstring'''



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

	# Pick K indices from range [0, N).
	lowercase_			 = np.random.randint(0  ,			__lowerCamelCase  ,			__lowerCamelCase  )

	# 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.
	lowercase_			 = data[rand_indices, :]

	return centroids




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		Union[str, Any]  ,			__lowerCamelCase:		Union[str, Any]  ):







	'''simple docstring'''



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




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		List[str]  ,			__lowerCamelCase:		int  ):







	'''simple docstring'''



	lowercase_			 = centroid_pairwise_dist(__lowerCamelCase  ,			__lowerCamelCase  )

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

	return cluster_assignment




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		Dict  ,			__lowerCamelCase:		str  ,			__lowerCamelCase:		str  ):







	'''simple docstring'''



	lowercase_			 = []
	for i in range(__lowerCamelCase  ):
		# Select all data points that belong to cluster i. Fill in the blank (RHS only)
		lowercase_			 = data[cluster_assignment == i]
		# Compute the mean of the data points. Fill in the blank (RHS only)
		lowercase_			 = member_data_points.mean(axis=0  )
		new_centroids.append(__lowerCamelCase  )
	lowercase_			 = np.array(__lowerCamelCase  )

	return new_centroids




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		str  ,			__lowerCamelCase:		str  ,			__lowerCamelCase:		List[Any]  ,			__lowerCamelCase:		Optional[Any]  ):







	'''simple docstring'''



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

	return heterogeneity




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		List[Any]  ,			__lowerCamelCase:		Union[str, Any]  ):







	'''simple docstring'''



	plt.figure(figsize=(7, 4)  )
	plt.plot(__lowerCamelCase  ,			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_  (				__lowerCamelCase:		int  ,			__lowerCamelCase:		Dict  ,			__lowerCamelCase:		Any  ,			__lowerCamelCase:		str=500  ,			__lowerCamelCase:		Union[str, Any]=None  ,			__lowerCamelCase:		Optional[int]=False  ):







	'''simple docstring'''



	lowercase_			 = initial_centroids[:]
	lowercase_			 = None

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

		# 1. Make cluster assignments using nearest centroids
		lowercase_			 = assign_clusters(__lowerCamelCase  ,			__lowerCamelCase  )

		# 2. Compute a new centroid for each of the k clusters, averaging all data
		#    points assigned to that cluster.
		lowercase_			 = revise_centroids(__lowerCamelCase  ,			__lowerCamelCase  ,			__lowerCamelCase  )

		# 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:
			lowercase_			 = 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
			lowercase_			 = compute_heterogeneity(__lowerCamelCase  ,			__lowerCamelCase  ,			__lowerCamelCase  ,			__lowerCamelCase  )
			record_heterogeneity.append(__lowerCamelCase  )

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

							SCREAMING_SNAKE_CASE__       			=				ds.load_iris()
							SCREAMING_SNAKE_CASE__       			=				3
							SCREAMING_SNAKE_CASE__       			=				[]
							SCREAMING_SNAKE_CASE__       			=				get_initial_centroids(dataset["""data"""], k, seed=0)
							SCREAMING_SNAKE_CASE__			,      SCREAMING_SNAKE_CASE__       			=				kmeans(
							    dataset["""data"""],
							    k,
							    initial_centroids,
							    maxiter=4_0_0,
							    record_heterogeneity=heterogeneity,
							    verbose=True,
							)
							plot_heterogeneity(heterogeneity, k)




def SCREAMING_SNAKE_CASE_  (				__lowerCamelCase:		pd.DataFrame  ,			__lowerCamelCase:		np.ndarray  ,			__lowerCamelCase:		str=None  ):







	'''simple docstring'''



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


if __name__ == "__main__":
							import doctest

							doctest.testmod()

