




'''simple docstring'''







from math import cos, sin



def 					lowerCamelCase__							(			__lowercase							):
     snake_case					   = float(__lowercase							)
     return [[scaling_factor * int(x == y							) for x in range(2							)] for y in range(2							)]



def 					lowerCamelCase__							(			__lowercase							):
     snake_case					   = cos(__lowercase							), sin(__lowercase							)
     return [[c, -s], [s, c]]



def 					lowerCamelCase__							(			__lowercase							):
     snake_case					   = cos(__lowercase							), sin(__lowercase							)
     snake_case					   = c * s
     return [[c * c, cs], [cs, s * s]]



def 					lowerCamelCase__							(			__lowercase							):
     snake_case					   = cos(__lowercase							), sin(__lowercase							)
     snake_case					   = c * s
     return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]


print(F"""    {scaling(5) = }""")
print(F"""  {rotation(45) = }""")
print(F"""{projection(45) = }""")







print(F"""{reflection(45) = }""")









'''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			:      Any			=					"""K-MEANS-CLUST/ """



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase    ,      __lowercase=None							):
     if seed is not None:  # useful for obtaining consistent results
          np.random.seed(__lowercase							)
     snake_case :			Optional[int]					   = data.shape[0]  # number of data points

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

     return centroids



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase							):
     return pairwise_distances(__lowercase    ,      __lowercase    ,      metric="""euclidean"""							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase							):
     # Compute distances between each data point and the set of centroids:
     # Fill in the blank (RHS only)
     snake_case :			Union[str, Any]					   = centroid_pairwise_dist(__lowercase    ,      __lowercase							)

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

     return cluster_assignment



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase    ,      __lowercase							):
     snake_case :			List[Any]					   = []
     for i in range(__lowercase							):
          # Select all data points that belong to cluster i. Fill in the blank (RHS only)
          snake_case :			List[str]					   = data[cluster_assignment == i]
          # Compute the mean of the data points. Fill in the blank (RHS only)
          snake_case :			int					   = member_data_points.mean(axis=0							)
          new_centroids.append(__lowercase							)
     snake_case :			Union[str, Any]					   = np.array(__lowercase							)

     return new_centroids



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

     return heterogeneity



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase							):
     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 					lowerCamelCase__							(			__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase=500    ,      __lowercase=None    ,      __lowercase=False							):
     snake_case :			Tuple					   = initial_centroids[:]
     snake_case :			Dict					   = None

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

          # 1. Make cluster assignments using nearest centroids
          snake_case :			List[Any]					   = 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 :			Optional[int]					   = 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 :			Tuple					   = 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 :			Any					   = compute_heterogeneity(__lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase							)
               record_heterogeneity.append(__lowercase							)

          snake_case :			Any					   = 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			:      Optional[int]			=					ds.load_iris()
      lowercase			:      str			=					3
      lowercase			:      Any			=					[]
      lowercase			:      Dict			=					get_initial_centroids(dataset["""data"""], k, seed=0)
      lowercase,  lowercase			:      str			=					kmeans(
          dataset["""data"""],
          k,
          initial_centroids,
          maxiter=400,
          record_heterogeneity=heterogeneity,
          verbose=True,
      )
      plot_heterogeneity(heterogeneity, k)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase    ,      __lowercase=None							):
     # Fill missing values with given rules
     if fill_missing_report:
          snake_case :			List[str]					   = df.fillna(value=__lowercase							)
     snake_case :			List[Any]					   = 1
     snake_case :			Optional[int]					   = 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 :			List[str]					   = report[
         (report["""Features"""] == """dummy""") & (report["""Type"""] == """count""")
     ].copy()  # avoid SettingWithCopyWarning
     snake_case :			Optional[Any]					   = (
         """ClusterSize"""  # rename created cluster df to match report column names
     )
     snake_case :			Optional[int]					   = """# of Customers"""
     snake_case :			List[str]					   = pd.DataFrame(
         clustersize.iloc[:, 2:].values
         / clustersize.iloc[:, 2:].values.sum()							)
     snake_case :			List[str]					   = """% of Customers"""  # rename created cluster df to match report column names
     snake_case :			List[Any]					   = """ClusterProportion"""
     snake_case :			Tuple					   = clusterproportion.columns.tolist()
     snake_case :			Optional[int]					   = cols[-2:] + cols[:-2]
     snake_case :			Tuple					   = clusterproportion[cols]  # rearrange columns to match report
     snake_case :			Tuple					   = report.columns
     snake_case :			List[str]					   = pd.DataFrame(
         abs(
             report[report["""Type"""] == """count"""].iloc[:, 2:].values
             - clustersize.iloc[:, 2:].values							)							)  # generating df with count of nan values
     snake_case :			Tuple					   = 0
     snake_case :			int					   = """# of nan"""
     snake_case :			int					   = report[
         report["""Type"""] == """count"""
     ].Features.tolist()  # filling values in order to match report
     snake_case :			Optional[Any]					   = a.columns.tolist()
     snake_case :			Dict					   = cols[-2:] + cols[:-2]
     snake_case :			Optional[Any]					   = a[cols]  # rearrange columns to match report
     snake_case :			Tuple					   = report.columns  # rename columns to match report
     snake_case :			Optional[Any]					   = report.drop(
         report[report.Type == """count"""].index							)  # drop count values except cluster size
     snake_case :			List[Any]					   = pd.concat(
         [report, a, clustersize, clusterproportion]    ,      axis=0							)  # concat report with clustert size and nan values
     snake_case :			Optional[int]					   = report["""Features"""].isin(__lowercase							)
     snake_case :			Any					   = report.columns.tolist()
     snake_case :			Union[str, Any]					   = cols[0:2] + cols[-1:] + cols[2:-1]
     snake_case :			List[Any]					   = report[cols]
     snake_case :			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 :			List[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 :			str					   = """"""
     snake_case :			Dict					   = report.reset_index()
     snake_case :			Optional[int]					   = report.drop(columns=["""index"""]							)
     return report


if __name__ == "__main__":
      import doctest

      doctest.testmod()



