-
Notifications
You must be signed in to change notification settings - Fork 2
/
sktidy.py
318 lines (263 loc) · 10.2 KB
/
sktidy.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.cluster import KMeans
import statsmodels.api as sm
from sklearn.utils.validation import check_is_fitted
def tidy_lr(model, X, y):
"""
Returns a tidy dataframe for sklearn LinearRegression model with feature \
names, coefficients/intercept and p-values
Parameters
----------
model : sklearn.linear_model.LinearRegression
The fitted sklearn LinearRegression model
X: pandas.core.frame.DataFrame
The feature pandas dataframe to which the LinearRegression object was \
fitted with m rows and n columns
y: pandas.core.series.Series
The target pandas Series to which the LinearRegression object was \
fitted with m rows
Returns
-------
df : pandas.core.frame.DataFrame
A pandas dataframe with n+1 rows, where n is the number of \
columns(features) in the input dataframe `X` that was
fitted to the model and 3 columns, describing feature names, \
coefficients/intercept and p-values
Examples
--------
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn import datasets
>>> import pandas as pd
>>> import sktidy
>>> # Load data and traning the linear regression model
>>> X = datasets.load_iris(return_X_y = True, as_frame = True)[0]
>>> y = datasets.load_iris(return_X_y = True, as_frame = True)[1]
>>> my_lr = LinearRegression()
>>> my_lr.fit(X,y)
>>> # Get tidy output for the trained sklearn LinearRegression model
>>> tidy_lr(model = my_lr, X = X, y = y)
"""
# raise error when model is not a sklearn LinearRegression object
if not isinstance(model, LinearRegression):
raise TypeError(
"Input model should be of type \
'sklearn.linear_model.LinearRegression'."
)
# raise error when X is not a pandas dataframe object
if not isinstance(X, pd.core.frame.DataFrame):
raise TypeError(
"Input X should be of type \
'pandas.core.frame.DataFrame'."
)
# raise error when y is not a pandas Series object
if not isinstance(y, pd.core.series.Series):
raise TypeError(
"Input y should be of type \
'pandas.core.series.Series'."
)
# raise error when model is not fitted yet
check_is_fitted(model)
# obtain coefficients and intercept
est = np.append(model.intercept_, model.coef_)
# obtain feature names
fea = np.append(np.array(["intercept"]), X.columns.values)
# obtain p-values
exog = sm.add_constant(X)
mod = sm.OLS(y, exog)
results = mod.fit()
p_val = np.round(results.pvalues.reset_index(drop=True), 4)
# assemble output dataframe
df = pd.DataFrame(zip(fea, est, p_val))
df.columns = ["feature", "coefficient", "p-value"]
return df
def tidy_kmeans(model, X):
"""
Return a tidy df of cluster information for a kmeans clustering algorithm
This function delivers diagnostic information about each cluster defined \
by an instance of scikit learn's implementation of kmeans clustering \
including total intertia in each cluster, cluster center, and \
total number of points associated with each cluster.
Parameters
----------
model : sklearn.cluster.KMeans
The model to extract the cluster specific information from.
X : pandas dataframe
The data to which the Kmeans object has been fitted
Returns
-------
df : pandas dataframe
A dataframe with k rows, where k is the number of clusters and 3 \
columns,describing respectively the center of the cluster, the sum of \
inertia of the cluster, and the number of associated data points in a \
cluster.
Examples
--------
>>> # Importing packages
>>> from sklearn.cluster import DBSCAN, KMeans
>>> from sklearn import datasets
>>> import pandas as pd
>>> import sktidy
>>> # Extracting data and training the clustering algorithm
>>> df = datasets.load_iris(return_X_y = True, as_frame = True)[0]
>>> kmeans_clusterer = KMeans()
>>> kmeans_clusterer.fit(df)
>>> # Getting the tidy df of cluster information
>>> tidy_kmeans(model = kmeans_clusterer, X = df)
"""
# raise error when model is not a sklearn LinearRegression object
if not isinstance(model, KMeans):
raise TypeError(
"Input model should be of type \
'sklearn.cluster.KMeans'"
)
# raise error when X is not a pandas dataframe object
if not isinstance(X, pd.core.frame.DataFrame):
raise TypeError(
"Input DataFrame should be of type 'pandas.core.frame.DataFrame'."
)
# raise error when model is not fitted yet
check_is_fitted(model)
cluster_labels, cluster_counts = np.unique(model.labels_,
return_counts=True)
# Creating a list that we'll fill with dfs corresponding to the kmeans \
# centroids with column labels
centers_list = []
for cluster in cluster_labels:
# Getting the cluster center for the given each cluster, reshaping it \
# so pandas behaves itself later
cluster_center = model.cluster_centers_[cluster].reshape(
1, cluster_labels.shape[0]
)
# Creating a df, adding labels from origional dataframe
cluster_center_df = pd.DataFrame(cluster_center, columns=X.columns)
centers_list.append(cluster_center_df)
df = pd.DataFrame(
{
"cluster_number": cluster_labels,
# "cluster_inertia" : cluster_labels,
"center_values": centers_list,
"n_points": cluster_counts,
}
)
return df
def augment_lr(model, X, y):
"""
Adds two columns to the original data of the scikit learn's linear \
regression model. This includes predictions and residuals.
Parameters
----------
model : sklearn.linear_model.LinearRegression object
The fitted sklearn LinearRegression model
X : pandas.core.frame.DataFrame
A dataframe of explanatory variables to predict on. Shaped n \
observations by m features.
y : pandas.core.series.Series
A pandas series of response variables to predict on. Shaped n \
observations by 1.
Returns
-------
df : pandas.core.frame.DataFrame
A dataframe with the original data plus two additional columns for \
predictions and residuals. Shaped n observations by m features + 2.
Examples
--------
>>> # Importing packages
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn import datasets
>>> import pandas as pd
>>> import sktidy
>>> # Extracting data and traning the linear regression model
>>> X = datasets.load_iris(return_X_y = True, as_frame = True)[0]
>>> y = datasets.load_iris(return_X_y = True, as_frame = True)[1]
>>> lr_model = LinearRegression()
>>> lr_model.fit(X,y)
>>> # Getting the tidy df of linear regression model output
>>> augment_lr(model = lr_model,X = X,y = y)
"""
# raise error when model is not a sklearn LinearRegression object
if not isinstance(model, LinearRegression):
raise TypeError(
"Input model should be of type \
'sklearn.linear_model.LinearRegression'."
)
# raise error when X is not a pandas dataframe object
if not isinstance(X, pd.core.frame.DataFrame):
raise TypeError(
"Input X should be of type \
'pandas.core.frame.DataFrame'."
)
# raise error when y is not a pandas Series object
if not isinstance(y, pd.core.series.Series):
raise TypeError(
"Input y should be of type \
'pandas.core.series.Series'."
)
# raise error when X is empty
if len(X) == 0:
raise ValueError("Input X should not be empty")
# raise error when Y is empty
if len(y) == 0:
raise ValueError("Input Y should not be empty")
# raise error when model is not fitted yet
check_is_fitted(model)
# calculate predictions and residuals
pred = model.predict(X)
res = y - pred
# create dataframe to return
df = X.join(y)
df["predictions"] = pred
df["residuals"] = res
return df
def augment_kmeans(model, X):
"""
This function returns a dataframe of the original samples with their \
assigned clusters based on predictions make by an instance of scikit \
learn's implementation of KMeans clustering.
Parameters
----------
model : sklearn.cluster.KMeans
The model to extract the cluster specific information from
X : pandas dataframe
The data to which the Kmeans object has been fitted
Returns
-------
df : pandas dataframe
A dataframe with k rows, where k is the number of examples in X and \
2 columns of the data points in X and their corresponding predicted \
label
Examples
--------
>>> # Importing packages
>>> from sklearn.cluster import KMeans
>>> from sklearn import datasets
>>> import pandas as pd
>>> import sktidy
>>> # Extracting data and traning the clustering algorithm
>>> df = datasets.load_iris(return_X_y = True, as_frame = True)[0]
>>> kmeans_clusterer = KMeans()
>>> kmeans_clusterer.fit(df)
>>> # Getting cluster assignment for each data point
>>> augment_kmeans(model = kmeans_clusterer, X = df)
"""
# raise error when model is not a sklearn KMeans object
if not isinstance(model, KMeans):
raise TypeError(
"Input model should be of type 'sklearn.cluster._kmeans.KMeans'."
)
# raise error when X is not a pandas dataframe object
if not isinstance(X, pd.core.frame.DataFrame):
raise TypeError(
"Input X should be of type \
'pandas.core.frame.DataFrame'."
)
# raise error when X is empty
if len(X) == 0:
raise ValueError("Input X should not be empty")
# raise error when model is not fitted yet
check_is_fitted(model)
# create dataframe to return
df = X.copy()
df["cluster"] = model.predict(X)
return df