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ns
|
8 |
+
from matplotlib.colors import ListedColormap
|
9 |
+
from sklearn.model_selection import train_test_split
|
10 |
+
from scipy.stats import boxcox
|
11 |
+
from sklearn.pipeline import Pipeline
|
12 |
+
from sklearn.preprocessing import StandardScaler
|
13 |
+
from sklearn.neighbors import KNeighborsClassifier
|
14 |
+
from sklearn.svm import SVC
|
15 |
+
from sklearn.model_selection import GridSearchCV, StratifiedKFold
|
16 |
+
from sklearn.metrics import classification_report, accuracy_score
|
17 |
+
from sklearn.tree import DecisionTreeClassifier
|
18 |
+
from sklearn.ensemble import RandomForestClassifier
|
19 |
+
|
20 |
+
%matplotlib inline
|
21 |
+
|
22 |
+
# Set the resolution of the plotted figures
|
23 |
+
plt.rcParams['figure.dpi'] = 200
|
24 |
+
|
25 |
+
# Configure Seaborn plot styles: Set background color and use dark grid
|
26 |
+
sns.set(rc={'axes.facecolor': '#faded9'}, style='darkgrid')
|
27 |
+
|
28 |
+
df = pd.read_csv("/content/heart.csv")
|
29 |
+
df
|
30 |
+
df.info()
|
31 |
+
|
32 |
+
# Define the continuous features
|
33 |
+
continuous_features = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
|
34 |
+
|
35 |
+
# Identify the features to be converted to object data type
|
36 |
+
features_to_convert = [feature for feature in df.columns if feature not in continuous_features]
|
37 |
+
|
38 |
+
# Convert the identified features to object data type
|
39 |
+
df[features_to_convert] = df[features_to_convert].astype('object')
|
40 |
+
|
41 |
+
df.dtypes
|
42 |
+
|
43 |
+
# Get the summary statistics for numerical variables
|
44 |
+
df.describe().T
|
45 |
+
|
46 |
+
# Get the summary statistics for categorical variables
|
47 |
+
df.describe(include='object')
|
48 |
+
|
49 |
+
# Filter out continuous features for the univariate analysis
|
50 |
+
df_continuous = df[continuous_features]
|
51 |
+
|
52 |
+
# Set up the subplot
|
53 |
+
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(15, 10))
|
54 |
+
|
55 |
+
# Loop to plot histograms for each continuous feature
|
56 |
+
for i, col in enumerate(df_continuous.columns):
|
57 |
+
x = i // 3
|
58 |
+
y = i % 3
|
59 |
+
values, bin_edges = np.histogram(df_continuous[col],
|
60 |
+
range=(np.floor(df_continuous[col].min()), np.ceil(df_continuous[col].max())))
|
61 |
+
|
62 |
+
graph = sns.histplot(data=df_continuous, x=col, bins=bin_edges, kde=True, ax=ax[x, y],
|
63 |
+
edgecolor='none', color='red', alpha=0.6, line_kws={'lw': 3})
|
64 |
+
ax[x, y].set_xlabel(col, fontsize=15)
|
65 |
+
ax[x, y].set_ylabel('Count', fontsize=12)
|
66 |
+
ax[x, y].set_xticks(np.round(bin_edges, 1))
|
67 |
+
ax[x, y].set_xticklabels(ax[x, y].get_xticks(), rotation=45)
|
68 |
+
ax[x, y].grid(color='lightgrey')
|
69 |
+
|
70 |
+
for j, p in enumerate(graph.patches):
|
71 |
+
ax[x, y].annotate('{}'.format(p.get_height()), (p.get_x() + p.get_width() / 2, p.get_height() + 1),
|
72 |
+
ha='center', fontsize=10, fontweight="bold")
|
73 |
+
|
74 |
+
textstr = '\n'.join((
|
75 |
+
r'$\mu=%.2f$' % df_continuous[col].mean(),
|
76 |
+
r'$\sigma=%.2f$' % df_continuous[col].std()
|
77 |
+
))
|
78 |
+
ax[x, y].text(0.75, 0.9, textstr, transform=ax[x, y].transAxes, fontsize=12, verticalalignment='top',
|
79 |
+
color='white', bbox=dict(boxstyle='round', facecolor='#ff826e', edgecolor='white', pad=0.5))
|
80 |
+
|
81 |
+
ax[1,2].axis('off')
|
82 |
+
plt.suptitle('Distribution of Continuous Variables', fontsize=20)
|
83 |
+
plt.tight_layout()
|
84 |
+
plt.subplots_adjust(top=0.92)
|
85 |
+
plt.show()
|
86 |
+
|
87 |
+
# Filter out categorical features for the univariate analysis
|
88 |
+
categorical_features = df.columns.difference(continuous_features)
|
89 |
+
df_categorical = df[categorical_features]
|
90 |
+
|
91 |
+
# Set up the subplot for a 4x2 layout
|
92 |
+
fig, ax = plt.subplots(nrows=5, ncols=2, figsize=(15, 18))
|
93 |
+
|
94 |
+
# Loop to plot bar charts for each categorical feature in the 4x2 layout
|
95 |
+
for i, col in enumerate(categorical_features):
|
96 |
+
row = i // 2
|
97 |
+
col_idx = i % 2
|
98 |
+
|
99 |
+
# Calculate frequency percentages
|
100 |
+
value_counts = df[col].value_counts(normalize=True).mul(100).sort_values()
|
101 |
+
|
102 |
+
# Plot bar chart
|
103 |
+
value_counts.plot(kind='barh', ax=ax[row, col_idx], width=0.8, color='red')
|
104 |
+
|
105 |
+
# Add frequency percentages to the bars
|
106 |
+
for index, value in enumerate(value_counts):
|
107 |
+
ax[row, col_idx].text(value, index, str(round(value, 1)) + '%', fontsize=15, weight='bold', va='center')
|
108 |
+
|
109 |
+
ax[row, col_idx].set_xlim([0, 95])
|
110 |
+
ax[row, col_idx].set_xlabel('Frequency Percentage', fontsize=12)
|
111 |
+
ax[row, col_idx].set_title(f'{col}', fontsize=20)
|
112 |
+
|
113 |
+
ax[4,1].axis('off')
|
114 |
+
plt.suptitle('Distribution of Categorical Variables', fontsize=22)
|
115 |
+
plt.tight_layout()
|
116 |
+
plt.subplots_adjust(top=0.95)
|
117 |
+
plt.show()
|
118 |
+
# Set color palette
|
119 |
+
sns.set_palette(['#ff826e', 'red'])
|
120 |
+
|
121 |
+
# Create the subplots
|
122 |
+
fig, ax = plt.subplots(len(continuous_features), 2, figsize=(15,15), gridspec_kw={'width_ratios': [1, 2]})
|
123 |
+
|
124 |
+
# Loop through each continuous feature to create barplots and kde plots
|
125 |
+
for i, col in enumerate(continuous_features):
|
126 |
+
# Barplot showing the mean value of the feature for each target category
|
127 |
+
graph = sns.barplot(data=df, x="target", y=col, ax=ax[i,0])
|
128 |
+
|
129 |
+
# KDE plot showing the distribution of the feature for each target category
|
130 |
+
sns.kdeplot(data=df[df["target"]==0], x=col, fill=True, linewidth=2, ax=ax[i,1], label='0')
|
131 |
+
sns.kdeplot(data=df[df["target"]==1], x=col, fill=True, linewidth=2, ax=ax[i,1], label='1')
|
132 |
+
ax[i,1].set_yticks([])
|
133 |
+
ax[i,1].legend(title='Heart Disease', loc='upper right')
|
134 |
+
|
135 |
+
# Add mean values to the barplot
|
136 |
+
for cont in graph.containers:
|
137 |
+
graph.bar_label(cont, fmt=' %.3g')
|
138 |
+
|
139 |
+
# Set the title for the entire figure
|
140 |
+
plt.suptitle('Continuous Features vs Target Distribution', fontsize=22)
|
141 |
+
plt.tight_layout()
|
142 |
+
plt.show()
|
143 |
+
|
144 |
+
# Set color palette
|
145 |
+
sns.set_palette(['#ff826e', 'red'])
|
146 |
+
|
147 |
+
# Create the subplots
|
148 |
+
fig, ax = plt.subplots(len(continuous_features), 2, figsize=(15,15), gridspec_kw={'width_ratios': [1, 2]})
|
149 |
+
|
150 |
+
# Loop through each continuous feature to create barplots and kde plots
|
151 |
+
for i, col in enumerate(continuous_features):
|
152 |
+
# Barplot showing the mean value of the feature for each target category
|
153 |
+
graph = sns.barplot(data=df, x="target", y=col, ax=ax[i,0])
|
154 |
+
|
155 |
+
# KDE plot showing the distribution of the feature for each target category
|
156 |
+
sns.kdeplot(data=df[df["target"]==0], x=col, fill=True, linewidth=2, ax=ax[i,1], label='0')
|
157 |
+
sns.kdeplot(data=df[df["target"]==1], x=col, fill=True, linewidth=2, ax=ax[i,1], label='1')
|
158 |
+
ax[i,1].set_yticks([])
|
159 |
+
ax[i,1].legend(title='Heart Disease', loc='upper right')
|
160 |
+
|
161 |
+
# Add mean values to the barplot
|
162 |
+
for cont in graph.containers:
|
163 |
+
graph.bar_label(cont, fmt=' %.3g')
|
164 |
+
|
165 |
+
# Set the title for the entire figure
|
166 |
+
plt.suptitle('Continuous Features vs Target Distribution', fontsize=22)
|
167 |
+
plt.tight_layout()
|
168 |
+
plt.show()
|
169 |
+
|
170 |
+
# Remove 'target' from the categorical_features
|
171 |
+
categorical_features = [feature for feature in categorical_features if feature != 'target']
|
172 |
+
fig, ax = plt.subplots(nrows=2, ncols=4, figsize=(15,10))
|
173 |
+
|
174 |
+
for i,col in enumerate(categorical_features):
|
175 |
+
|
176 |
+
# Create a cross tabulation showing the proportion of purchased and non-purchased loans for each category of the feature
|
177 |
+
cross_tab = pd.crosstab(index=df[col], columns=df['target'])
|
178 |
+
|
179 |
+
# Using the normalize=True argument gives us the index-wise proportion of the data
|
180 |
+
cross_tab_prop = pd.crosstab(index=df[col], columns=df['target'], normalize='index')
|
181 |
+
|
182 |
+
# Define colormap
|
183 |
+
cmp = ListedColormap(['#ff826e', 'red'])
|
184 |
+
|
185 |
+
# Plot stacked bar charts
|
186 |
+
x, y = i//4, i%4
|
187 |
+
cross_tab_prop.plot(kind='bar', ax=ax[x,y], stacked=True, width=0.8, colormap=cmp,
|
188 |
+
legend=False, ylabel='Proportion', sharey=True)
|
189 |
+
|
190 |
+
# Add the proportions and counts of the individual bars to our plot
|
191 |
+
for idx, val in enumerate([*cross_tab.index.values]):
|
192 |
+
for (proportion, count, y_location) in zip(cross_tab_prop.loc[val],cross_tab.loc[val],cross_tab_prop.loc[val].cumsum()):
|
193 |
+
ax[x,y].text(x=idx-0.3, y=(y_location-proportion)+(proportion/2)-0.03,
|
194 |
+
s = f' {count}\n({np.round(proportion * 100, 1)}%)',
|
195 |
+
color = "black", fontsize=9, fontweight="bold")
|
196 |
+
|
197 |
+
# Add legend
|
198 |
+
ax[x,y].legend(title='target', loc=(0.7,0.9), fontsize=8, ncol=2)
|
199 |
+
# Set y limit
|
200 |
+
ax[x,y].set_ylim([0,1.12])
|
201 |
+
# Rotate xticks
|
202 |
+
ax[x,y].set_xticklabels(ax[x,y].get_xticklabels(), rotation=0)
|
203 |
+
|
204 |
+
|
205 |
+
plt.suptitle('Categorical Features vs Target Stacked Barplots', fontsize=22)
|
206 |
+
plt.tight_layout()
|
207 |
+
plt.show()
|
208 |
+
|
209 |
+
# Check for missing values in the dataset
|
210 |
+
df.isnull().sum().sum()
|
211 |
+
continuous_features
|
212 |
+
|
213 |
+
Q1 = df[continuous_features].quantile(0.25)
|
214 |
+
Q3 = df[continuous_features].quantile(0.75)
|
215 |
+
IQR = Q3 - Q1
|
216 |
+
outliers_count_specified = ((df[continuous_features] < (Q1 - 1.5 * IQR)) | (df[continuous_features] > (Q3 + 1.5 * IQR))).sum()
|
217 |
+
|
218 |
+
outliers_count_specified
|
219 |
+
|
220 |
+
# Implementing one-hot encoding on the specified categorical features
|
221 |
+
df_encoded = pd.get_dummies(df, columns=['cp', 'restecg', 'thal'], drop_first=True)
|
222 |
+
|
223 |
+
# Convert the rest of the categorical variables that don't need one-hot encoding to integer data type
|
224 |
+
features_to_convert = ['sex', 'fbs', 'exang', 'slope', 'ca', 'target']
|
225 |
+
for feature in features_to_convert:
|
226 |
+
df_encoded[feature] = df_encoded[feature].astype(int)
|
227 |
+
|
228 |
+
df_encoded.dtypes
|
229 |
+
# Displaying the resulting DataFrame after one-hot encoding
|
230 |
+
df_encoded.head()
|
231 |
+
# Define the features (X) and the output labels (y)
|
232 |
+
X = df_encoded.drop('target', axis=1)
|
233 |
+
y = df_encoded['target']
|
234 |
+
# Splitting data into train and test sets
|
235 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
|
236 |
+
continuous_features
|
237 |
+
# Adding a small constant to 'oldpeak' to make all values positive
|
238 |
+
X_train['oldpeak'] = X_train['oldpeak'] + 0.001
|
239 |
+
X_test['oldpeak'] = X_test['oldpeak'] + 0.001
|
240 |
+
|
241 |
+
# Checking the distribution of the continuous features
|
242 |
+
fig, ax = plt.subplots(2, 5, figsize=(15,10))
|
243 |
+
|
244 |
+
# Original Distributions
|
245 |
+
for i, col in enumerate(continuous_features):
|
246 |
+
sns.histplot(X_train[col], kde=True, ax=ax[0,i], color='#ff826e').set_title(f'Original {col}')
|
247 |
+
|
248 |
+
|
249 |
+
# Applying Box-Cox Transformation
|
250 |
+
# Dictionary to store lambda values for each feature
|
251 |
+
lambdas = {}
|
252 |
+
|
253 |
+
for i, col in enumerate(continuous_features):
|
254 |
+
# Only apply box-cox for positive values
|
255 |
+
if X_train[col].min() > 0:
|
256 |
+
X_train[col], lambdas[col] = boxcox(X_train[col])
|
257 |
+
# Applying the same lambda to test data
|
258 |
+
X_test[col] = boxcox(X_test[col], lmbda=lambdas[col])
|
259 |
+
sns.histplot(X_train[col], kde=True, ax=ax[1,i], color='red').set_title(f'Transformed {col}')
|
260 |
+
else:
|
261 |
+
sns.histplot(X_train[col], kde=True, ax=ax[1,i], color='green').set_title(f'{col} (Not Transformed)')
|
262 |
+
|
263 |
+
fig.tight_layout()
|
264 |
+
plt.show()
|
265 |
+
|
266 |
+
X_train.head()
|
267 |
+
|
268 |
+
# Define the base DT model
|
269 |
+
dt_base = DecisionTreeClassifier(random_state=0)
|
270 |
+
|
271 |
+
def tune_clf_hyperparameters(clf, param_grid, X_train, y_train, scoring='recall', n_splits=3):
|
272 |
+
'''
|
273 |
+
This function optimizes the hyperparameters for a classifier by searching over a specified hyperparameter grid.
|
274 |
+
It uses GridSearchCV and cross-validation (StratifiedKFold) to evaluate different combinations of hyperparameters.
|
275 |
+
The combination with the highest recall for class 1 is selected as the default scoring metric.
|
276 |
+
The function returns the classifier with the optimal hyperparameters.
|
277 |
+
'''
|
278 |
+
|
279 |
+
# Create the cross-validation object using StratifiedKFold to ensure the class distribution is the same across all the folds
|
280 |
+
cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=0)
|
281 |
+
|
282 |
+
# Create the GridSearchCV object
|
283 |
+
clf_grid = GridSearchCV(clf, param_grid, cv=cv, scoring=scoring, n_jobs=-1)
|
284 |
+
|
285 |
+
# Fit the GridSearchCV object to the training data
|
286 |
+
clf_grid.fit(X_train, y_train)
|
287 |
+
|
288 |
+
# Get the best hyperparameters
|
289 |
+
best_hyperparameters = clf_grid.best_params_
|
290 |
+
|
291 |
+
# Return best_estimator_ attribute which gives us the best model that has been fitted to the training data
|
292 |
+
return clf_grid.best_estimator_, best_hyperparameters
|
293 |
+
|
294 |
+
# Hyperparameter grid for DT
|
295 |
+
param_grid_dt = {
|
296 |
+
'criterion': ['gini', 'entropy'],
|
297 |
+
'max_depth': [2,3],
|
298 |
+
'min_samples_split': [2, 3, 4],
|
299 |
+
'min_samples_leaf': [1, 2]
|
300 |
+
}
|
301 |
+
# Call the function for hyperparameter tuning
|
302 |
+
best_dt, best_dt_hyperparams = tune_clf_hyperparameters(dt_base, param_grid_dt, X_train, y_train)
|
303 |
+
|
304 |
+
print('DT Optimal Hyperparameters: \n', best_dt_hyperparams)
|
305 |
+
# Evaluate the optimized model on the train data
|
306 |
+
print(classification_report(y_train, best_dt.predict(X_train)))
|
307 |
+
# Evaluate the optimized model on the test data
|
308 |
+
print(classification_report(y_test, best_dt.predict(X_test)))
|
309 |
+
def evaluate_model(model, X_test, y_test, model_name):
|
310 |
+
"""
|
311 |
+
Evaluates the performance of a trained model on test data using various metrics.
|
312 |
+
"""
|
313 |
+
# Make predictions
|
314 |
+
y_pred = model.predict(X_test)
|
315 |
+
|
316 |
+
# Get classification report
|
317 |
+
report = classification_report(y_test, y_pred, output_dict=True)
|
318 |
+
|
319 |
+
# Extracting metrics
|
320 |
+
metrics = {
|
321 |
+
"precision_0": report["0"]["precision"],
|
322 |
+
"precision_1": report["1"]["precision"],
|
323 |
+
"recall_0": report["0"]["recall"],
|
324 |
+
"recall_1": report["1"]["recall"],
|
325 |
+
"f1_0": report["0"]["f1-score"],
|
326 |
+
"f1_1": report["1"]["f1-score"],
|
327 |
+
"macro_avg_precision": report["macro avg"]["precision"],
|
328 |
+
"macro_avg_recall": report["macro avg"]["recall"],
|
329 |
+
"macro_avg_f1": report["macro avg"]["f1-score"],
|
330 |
+
"accuracy": accuracy_score(y_test, y_pred)
|
331 |
+
}
|
332 |
+
|
333 |
+
# Convert dictionary to dataframe
|
334 |
+
df = pd.DataFrame(metrics, index=[model_name]).round(2)
|
335 |
+
|
336 |
+
return df
|
337 |
+
dt_evaluation = evaluate_model(best_dt, X_test, y_test, 'DT')
|
338 |
+
dt_evaluation
|
339 |
+
rf_base = RandomForestClassifier(random_state=0)
|
340 |
+
param_grid_rf = {
|
341 |
+
'n_estimators': [10, 30, 50, 70, 100],
|
342 |
+
'criterion': ['gini', 'entropy'],
|
343 |
+
'max_depth': [2, 3, 4],
|
344 |
+
'min_samples_split': [2, 3, 4, 5],
|
345 |
+
'min_samples_leaf': [1, 2, 3],
|
346 |
+
'bootstrap': [True, False]
|
347 |
+
}
|
348 |
+
# Using the tune_clf_hyperparameters function to get the best estimator
|
349 |
+
best_rf, best_rf_hyperparams = tune_clf_hyperparameters(rf_base, param_grid_rf, X_train, y_train)
|
350 |
+
print('RF Optimal Hyperparameters: \n', best_rf_hyperparams)
|
351 |
+
|
352 |
+
# Evaluate the optimized model on the train data
|
353 |
+
print(classification_report(y_train, best_rf.predict(X_train)))
|
354 |
+
|
355 |
+
# Evaluate the optimized model on the test data
|
356 |
+
print(classification_report(y_test, best_rf.predict(X_test)))
|
357 |
+
|
358 |
+
rf_evaluation = evaluate_model(best_rf, X_test, y_test, 'RF')
|
359 |
+
rf_evaluation
|
360 |
+
|
361 |
+
# Define the base KNN model and set up the pipeline with scaling
|
362 |
+
knn_pipeline = Pipeline([
|
363 |
+
('scaler', StandardScaler()),
|
364 |
+
('knn', KNeighborsClassifier())
|
365 |
+
])
|
366 |
+
# Hyperparameter grid for KNN
|
367 |
+
knn_param_grid = {
|
368 |
+
'knn__n_neighbors': list(range(1, 12)),
|
369 |
+
'knn__weights': ['uniform', 'distance'],
|
370 |
+
'knn__p': [1, 2] # 1: Manhattan distance, 2: Euclidean distance
|
371 |
+
}
|
372 |
+
# Hyperparameter tuning for KNN
|
373 |
+
best_knn, best_knn_hyperparams = tune_clf_hyperparameters(knn_pipeline, knn_param_grid, X_train, y_train)
|
374 |
+
print('KNN Optimal Hyperparameters: \n', best_knn_hyperparams)
|
375 |
+
# Evaluate the optimized model on the train data
|
376 |
+
print(classification_report(y_train, best_knn.predict(X_train)))
|
377 |
+
# Evaluate the optimized model on the test data
|
378 |
+
print(classification_report(y_test, best_knn.predict(X_test)))
|
379 |
+
knn_evaluation = evaluate_model(best_knn, X_test, y_test, 'KNN')
|
380 |
+
knn_evaluation
|
381 |
+
|
382 |
+
svm_pipeline = Pipeline([
|
383 |
+
('scaler', StandardScaler()),
|
384 |
+
('svm', SVC(probability=True))
|
385 |
+
])
|
386 |
+
|
387 |
+
param_grid_svm = {
|
388 |
+
'svm__C': [0.0011, 0.005, 0.01, 0.05, 0.1, 1, 10, 20],
|
389 |
+
'svm__kernel': ['linear', 'rbf', 'poly'],
|
390 |
+
'svm__gamma': ['scale', 'auto', 0.1, 0.5, 1, 5],
|
391 |
+
'svm__degree': [2, 3, 4]
|
392 |
+
}
|
393 |
+
# Call the function for hyperparameter tuning
|
394 |
+
best_svm, best_svm_hyperparams = tune_clf_hyperparameters(svm_pipeline, param_grid_svm, X_train, y_train)
|
395 |
+
print('SVM Optimal Hyperparameters: \n', best_svm_hyperparams)
|
396 |
+
# Evaluate the optimized model on the train data
|
397 |
+
print(classification_report(y_train, best_svm.predict(X_train)))
|
398 |
+
svm_evaluation = evaluate_model(best_svm, X_test, y_test, 'SVM')
|
399 |
+
svm_evaluation
|
400 |
+
# Concatenate the dataframes
|
401 |
+
all_evaluations = [dt_evaluation, rf_evaluation, knn_evaluation, svm_evaluation]
|
402 |
+
results = pd.concat(all_evaluations)
|
403 |
+
|
404 |
+
# Sort by 'recall_1'
|
405 |
+
results = results.sort_values(by='recall_1', ascending=False).round(2)
|
406 |
+
results
|
407 |
+
# Sort values based on 'recall_1'
|
408 |
+
results.sort_values(by='recall_1', ascending=True, inplace=True)
|
409 |
+
recall_1_scores = results['recall_1']
|
410 |
+
|
411 |
+
# Plot the horizontal bar chart
|
412 |
+
fig, ax = plt.subplots(figsize=(12, 7), dpi=70)
|
413 |
+
ax.barh(results.index, recall_1_scores, color='red')
|
414 |
+
|
415 |
+
# Annotate the values and indexes
|
416 |
+
for i, (value, name) in enumerate(zip(recall_1_scores, results.index)):
|
417 |
+
ax.text(value + 0.01, i, f"{value:.2f}", ha='left', va='center', fontweight='bold', color='red', fontsize=15)
|
418 |
+
ax.text(0.1, i, name, ha='left', va='center', fontweight='bold', color='white', fontsize=25)
|
419 |
+
|
420 |
+
# Remove yticks
|
421 |
+
ax.set_yticks([])
|
422 |
+
|
423 |
+
# Set x-axis limit
|
424 |
+
ax.set_xlim([0, 1.2])
|
425 |
+
|
426 |
+
# Add title and xlabel
|
427 |
+
plt.title("Recall for Positive Class across Models", fontweight='bold', fontsize=22)
|
428 |
+
plt.xlabel('Recall Value', fontsize=16)
|
429 |
+
plt.show()
|
430 |
+
|
431 |
+
!pip install gradio
|
432 |
+
import gradio as gr
|
433 |
+
import numpy as np
|
434 |
+
from sklearn.ensemble import RandomForestClassifier
|
435 |
+
|
436 |
+
# Example: Define and train a Random Forest model
|
437 |
+
model = RandomForestClassifier()
|
438 |
+
|
439 |
+
# Dummy training data (replace with your actual data)
|
440 |
+
X_train = np.random.rand(100, 13) # 100 samples, 12 features (one for each input)
|
441 |
+
y_train = np.random.randint(2, size=100) # Binary target
|
442 |
+
|
443 |
+
# Train the model
|
444 |
+
model.fit(X_train, y_train)
|
445 |
+
|
446 |
+
# Define the prediction function
|
447 |
+
def predict(*inputs):
|
448 |
+
try:
|
449 |
+
# Convert inputs to a numpy array and reshape it to match the model's expected input shape
|
450 |
+
input_array = np.array(inputs).reshape(1, -1)
|
451 |
+
prediction = model.predict(input_array) # Make a prediction
|
452 |
+
return str(prediction[0]) # Return the prediction (single value) as a string for display
|
453 |
+
except Exception as e:
|
454 |
+
return str(e) # Return any errors as a string (for debugging)
|
455 |
+
|
456 |
+
# Define the features (input fields) for Gradio
|
457 |
+
features = [
|
458 |
+
'age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach',
|
459 |
+
'exang', 'oldpeak', 'slope', 'ca','thal'
|
460 |
+
]
|
461 |
+
|
462 |
+
# Create Gradio input components (use gr.Number for numeric inputs)
|
463 |
+
inputs = [gr.Number(label=feature, value=0) for feature in features]
|
464 |
+
|
465 |
+
# Output component (show the prediction result)
|
466 |
+
outputs = gr.Textbox(label="Prediction Output")
|
467 |
+
|
468 |
+
# Create and launch the Gradio interface
|
469 |
+
gr.Interface(fn=predict, inputs=inputs, outputs=outputs).launch()
|