code: 
  
  
  
  
  
  
  """simple docstring"""
  
  from sklearn.metrics import precision_score
  
  import datasets
  
  
  lowercase__      =				"""
  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).
  """
  
  
  lowercase__      =				"""
  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]
  """
  
  
  lowercase__      =				"""
  @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      lowerCamelCase (     self							:			List[Any]			):
  				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      lowerCamelCase (     self							:			List[Any]		,    a_							:			Tuple		,    a_							:			List[Any]		,    a_							:			Union[str, Any]=None		,    a_							:			Any=1		,    a_							:			str="binary"		,    a_							:			Optional[int]=None		,    a_							:			Union[str, Any]="warn"		,    ):
  				lowerCAmelCase_     :							List[str]             =    precision_score(
  				    a_		,    a_		,    labels=a_		,    pos_label=a_		,    average=a_		,    sample_weight=a_		,    zero_division=a_		,    )
  				return {"precision": float(a_			) if score.size == 1 else score}
  
  
  
  
style_context: 
  
  
  
  
  
  
  """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""")
  
  lowercase__      =				"""K-MEANS-CLUST/ """
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=None )		->					Optional[Any]:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		if seed is not None:  # useful for obtaining consistent results
  				np.random.seed(__UpperCamelCase )
  		lowerCAmelCase_     :							List[Any]             =    data.shape[0]  # number of data points
  
  		# Pick K indices from range [0, N).
  		lowerCAmelCase_     :							Optional[Any]             =    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.
  		lowerCAmelCase_     :							List[str]             =    data[rand_indices, :]
  
  		return centroids
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					Dict:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		return pairwise_distances(__UpperCamelCase   , __UpperCamelCase   , metric="euclidean" )
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					List[str]:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		lowerCAmelCase_     :							Optional[Any]             =    centroid_pairwise_dist(__UpperCamelCase   , __UpperCamelCase )
  
  		# Compute cluster assignments for each data point:
  		# Fill in the blank (RHS only)
  		lowerCAmelCase_     :							str             =    np.argmin(__UpperCamelCase   , axis=1 )
  
  		return cluster_assignment
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )		->					Dict:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		lowerCAmelCase_     :							Tuple             =    []
  		for i in range(__UpperCamelCase ):
  				# Select all data points that belong to cluster i. Fill in the blank (RHS only)
  				lowerCAmelCase_     :							List[Any]             =    data[cluster_assignment == i]
  				# Compute the mean of the data points. Fill in the blank (RHS only)
  				lowerCAmelCase_     :							List[str]             =    member_data_points.mean(axis=0 )
  				new_centroids.append(__UpperCamelCase )
  		lowerCAmelCase_     :							Tuple             =    np.array(__UpperCamelCase )
  
  		return new_centroids
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )		->					int:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		lowerCAmelCase_     :							Union[str, Any]             =    0.0
  		for i in range(__UpperCamelCase ):
  				# Select all data points that belong to cluster i. Fill in the blank (RHS only)
  				lowerCAmelCase_     :							List[str]             =    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)
  						lowerCAmelCase_     :							int             =    pairwise_distances(
  						    __UpperCamelCase   , [centroids[i]]   , metric="euclidean" )
  						lowerCAmelCase_     :							Optional[int]             =    distances**2
  						heterogeneity += np.sum(__UpperCamelCase )
  
  		return heterogeneity
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					Dict:
  
  		"""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 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=500   , __UpperCamelCase=None   , __UpperCamelCase=False )		->					List[Any]:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		lowerCAmelCase_     :							Dict             =    initial_centroids[:]
  		lowerCAmelCase_     :							Optional[int]             =    None
  
  		for itr in range(__UpperCamelCase ):
  				if verbose:
  						print(__UpperCamelCase   , end="" )
  
  				# 1. Make cluster assignments using nearest centroids
  				lowerCAmelCase_     :							Optional[Any]             =    assign_clusters(__UpperCamelCase   , __UpperCamelCase )
  
  				# 2. Compute a new centroid for each of the k clusters, averaging all data
  				#    points assigned to that cluster.
  				lowerCAmelCase_     :							Tuple             =    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:
  						lowerCAmelCase_     :							Union[str, 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
  						lowerCAmelCase_     :							Tuple             =    compute_heterogeneity(__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )
  						record_heterogeneity.append(__UpperCamelCase )
  
  				lowerCAmelCase_     :							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
  
  					lowercase__      =				ds.load_iris()
  					lowercase__      =				3
  					lowercase__      =				[]
  					lowercase__      =				get_initial_centroids(dataset["""data"""], k, seed=0)
  					lowercase__ ,     lowercase__      =				kmeans(
  					    dataset["""data"""],
  					    k,
  					    initial_centroids,
  					    maxiter=400,
  					    record_heterogeneity=heterogeneity,
  					    verbose=True,
  					)
  					plot_heterogeneity(heterogeneity, k)
  
  def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=None )		->					pd.DataFrame:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		if fill_missing_report:
  				lowerCAmelCase_     :							str             =    df.fillna(value=__UpperCamelCase )
  		lowerCAmelCase_     :							Optional[int]             =    1
  		lowerCAmelCase_     :							Optional[int]             =    df.select_dtypes(np.number ).columns
  		lowerCAmelCase_     :							Dict             =    (
  		    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)
  		lowerCAmelCase_     :							Optional[Any]             =    report[
  		    (report["Features"] == "dummy") & (report["Type"] == "count")
  		].copy()  # avoid SettingWithCopyWarning
  		lowerCAmelCase_     :							List[Any]             =    (
  		    "ClusterSize"  # rename created cluster df to match report column names
  		)
  		lowerCAmelCase_     :							Dict             =    "# of Customers"
  		lowerCAmelCase_     :							List[str]             =    pd.DataFrame(
  		    clustersize.iloc[:, 2:].values
  		    / clustersize.iloc[:, 2:].values.sum() )
  		lowerCAmelCase_     :							Optional[Any]             =    "% of Customers"  # rename created cluster df to match report column names
  		lowerCAmelCase_     :							Dict             =    "ClusterProportion"
  		lowerCAmelCase_     :							Optional[Any]             =    clusterproportion.columns.tolist()
  		lowerCAmelCase_     :							Optional[Any]             =    cols[-2:] + cols[:-2]
  		lowerCAmelCase_     :							Dict             =    clusterproportion[cols]  # rearrange columns to match report
  		lowerCAmelCase_     :							Union[str, Any]             =    report.columns
  		lowerCAmelCase_     :							Dict             =    pd.DataFrame(
  		    abs(
  		        report[report["Type"] == "count"].iloc[:, 2:].values
  		        - clustersize.iloc[:, 2:].values ) )  # generating df with count of nan values
  		lowerCAmelCase_     :							Union[str, Any]             =    0
  		lowerCAmelCase_     :							Any             =    "# of nan"
  		lowerCAmelCase_     :							Dict             =    report[
  		    report["Type"] == "count"
  		].Features.tolist()  # filling values in order to match report
  		lowerCAmelCase_     :							Optional[Any]             =    a.columns.tolist()
  		lowerCAmelCase_     :							Optional[Any]             =    cols[-2:] + cols[:-2]
  		lowerCAmelCase_     :							str             =    a[cols]  # rearrange columns to match report
  		lowerCAmelCase_     :							Tuple             =    report.columns  # rename columns to match report
  		lowerCAmelCase_     :							List[str]             =    report.drop(
  		    report[report.Type == "count"].index )  # drop count values except cluster size
  		lowerCAmelCase_     :							Tuple             =    pd.concat(
  		    [report, a, clustersize, clusterproportion]   , axis=0 )  # concat report with clustert size and nan values
  		lowerCAmelCase_     :							List[Any]             =    report["Features"].isin(__UpperCamelCase )
  		lowerCAmelCase_     :							Tuple             =    report.columns.tolist()
  		lowerCAmelCase_     :							List[str]             =    cols[0:2] + cols[-1:] + cols[2:-1]
  		lowerCAmelCase_     :							List[str]             =    report[cols]
  		lowerCAmelCase_     :							str             =    {
  		    "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,
  		}
  		lowerCAmelCase_     :							List[str]             =    (
  		    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 )
  		)
  		lowerCAmelCase_     :							str             =    ""
  		lowerCAmelCase_     :							Any             =    report.reset_index()
  		lowerCAmelCase_     :							Any             =    report.drop(columns=["index"] )
  		return report
  
  
  if __name__ == "__main__":
  					import doctest
  
  					doctest.testmod()
  