Repository navigation
Expand file tree
/
Copy pathutils2.py
More file actions
166 lines (126 loc) · 6.02 KB
/
Copy pathutils2.py
File metadata and controls
166 lines (126 loc) · 6.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.metrics import silhouette_score, confusion_matrix
from scipy.cluster.hierarchy import dendrogram
from utils1 import set_plot_properties
def plot_inertia_and_silhouette(data, k_min=2, k_max=15):
"""
Plot the inertia (dispersion) and silhouette score for different numbers of clusters.
Args:
data (numpy.ndarray or pandas.DataFrame): The input data for clustering.
k_min (int, optional): The minimum number of clusters to evaluate. Defaults to 2.
k_max (int, optional): The maximum number of clusters to evaluate. Defaults to 15.
Returns:
None
"""
dispersions = []
scores = []
k_clusters = range(k_min, k_max + 1)
for k in k_clusters:
kmeans = KMeans(n_clusters=k, random_state=0).fit(data)
dispersions.append(kmeans.inertia_) # Calculate the dispersion (inertia) for each number of clusters
kmeans.predict(data)
scores.append(silhouette_score(data, kmeans.labels_, metric='euclidean')) # Calculate the silhouette score
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(k_clusters, dispersions, marker='o') # Plot the inertia (dispersion)
set_plot_properties(ax1, 'Number of clusters', 'Dispersion (inertia)')
ax2.plot(k_clusters, scores, marker='o') # Plot the silhouette score
set_plot_properties(ax2, 'Number of clusters', 'Silhouette score')
plt.show()
def plot_dendrogram(data, linkage_method, cut_line=None):
"""
Plot a dendrogram for hierarchical clustering.
Args:
data (numpy.ndarray or pandas.DataFrame): The input data for clustering.
linkage_method (str): The linkage method used for clustering.
cut_line (float, optional): The threshold value to cut the dendrogram. Defaults to None.
Returns:
None
"""
# Fit the AgglomerativeClustering model
model = AgglomerativeClustering(linkage=linkage_method, distance_threshold=0, n_clusters=None).fit(data)
# Create the plot
fig, ax = plt.subplots()
plt.title('Hierarchical Clustering Dendrogram')
# Create the counts of samples under each node
counts = np.zeros(model.children_.shape[0])
n_samples = len(model.labels_)
for i, merge in enumerate(model.children_):
current_count = 0
for child_idx in merge:
if child_idx < n_samples:
current_count += 1 # Leaf node
else:
current_count += counts[child_idx - n_samples]
counts[i] = current_count
# Create the linkage matrix
linkage_matrix = np.column_stack([model.children_, model.distances_, counts]).astype(float)
# Plot the dendrogram
dendrogram(linkage_matrix, truncate_mode='level', p=50)
# Add a cut line if provided
if cut_line is not None:
plt.axhline(y=cut_line, color='black', linestyle='-')
# Display the plot
plt.show()
def clusters_comparison(data, solution1, solution2):
"""
Compare the clusters of two solutions using a confusion matrix.
Args:
data (pandas.DataFrame): The input data containing the cluster assignments for both solutions.
solution1 (str): The column name representing the cluster assignments of the first solution.
solution2 (str): The column name representing the cluster assignments of the second solution.
Returns:
pandas.DataFrame: The confusion matrix comparing the clusters of the two solutions.
"""
# Determine the number of unique clusters in each solution
length1, length2 = len(data[solution1].unique()), len(data[solution2].unique())
# Determine the maximum number of clusters
n = max(length1, length2)
# Compute the confusion matrix
confusion = confusion_matrix(data[solution1], data[solution2])
# Create a DataFrame for the confusion matrix with appropriate row and column labels
df = pd.DataFrame(
confusion,
index=['{} {} Cluster'.format(solution1, i) for i in np.arange(0, n)],
columns=['{} {} Cluster'.format(solution2, i) for i in np.arange(0, n)]
)
# Return the subset of the confusion matrix corresponding to the number of clusters in each solution
return df.iloc[:length1, :length2]
def groupby_mean(data, variable, n_features=30):
"""
Group the data by a variable and calculate the mean for each group.
Args:
data (pandas.DataFrame): The input data.
variable (str): The variable used for grouping.
n_features (int, optional): The number of features to include in the result. Defaults to 30.
Returns:
pandas.DataFrame: The transposed DataFrame containing the mean values for each group.
"""
# Group the data by the specified variable and calculate the mean for each group
grouped_data = data.groupby(variable).mean()
# Select the first n_features + 1 columns (including the variable column) and transpose the DataFrame
result = grouped_data.iloc[:, :n_features + 1].T
# Return the transposed DataFrame
return result
def visualize_dimensionality_reduction(transformation, targets):
"""
Visualize the dimensionality reduction results using a scatter plot.
Args:
transformation (numpy.ndarray): The transformed data points after dimensionality reduction.
targets (numpy.ndarray or list): The target labels or cluster assignments.
Returns:
None
"""
# Convert object labels to categorical variables
labels, targets_categorical = np.unique(targets, return_inverse=True)
# Create a scatter plot of the t-SNE output
cmap = plt.cm.tab10
norm = plt.Normalize(vmin=0, vmax=len(labels) - 1)
plt.scatter(transformation[:, 0], transformation[:, 1], c=targets_categorical, cmap=cmap, norm=norm)
# Create a legend with the class labels and corresponding colors
handles = [plt.scatter([], [], c=cmap(norm(i)), label=label) for i, label in enumerate(labels)]
plt.legend(handles=handles, title='Clusters')
# Display the plot
plt.show()