-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_model.py
More file actions
119 lines (101 loc) · 3.85 KB
/
Copy pathdebug_model.py
File metadata and controls
119 lines (101 loc) · 3.85 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
import joblib
import pandas as pd
import numpy as np
try:
print("Loading artifacts...")
model = joblib.load("KNN_heart.pkl")
scaler = joblib.load("scaler.pkl")
expected_columns = joblib.load("columns.pkl")
print(f"Artifacts loaded. Expected columns ({len(expected_columns)}):")
print(expected_columns)
except Exception as e:
print(f"Error loading artifacts: {e}")
exit()
# Load heart.csv to compute original stats for pre-scaling
try:
df_raw = pd.read_csv("heart.csv")
pre_scale_cols = ['RestingBP', 'Cholesterol', 'MaxHR', 'Oldpeak']
pre_scale_stats = {}
for col in pre_scale_cols:
# Note: If notebook removed 0s or outliers, these stats might be slightly off
# but should be much better than raw values
pre_scale_stats[col] = {
'mean': df_raw[col].mean(),
'std': df_raw[col].std()
}
print("Computed pre-scaling stats from heart.csv")
except Exception as e:
print(f"Error loading heart.csv: {e}")
exit()
def predict_manually(data):
# 1. Prepare raw input (mocking the API logic)
raw_input = {
'Age': data['Age'],
'RestingBP': data['RestingBP'],
'Cholesterol': data['Cholesterol'],
'FastingBS': data['FastingBS'],
'MaxHR': data['MaxHR'],
'Oldpeak': data['Oldpeak'],
}
# 2. One-hot encoding logic
# Set base fields
# Note: dict keys must match the dummies used in training
processed_input = raw_input.copy()
# Sex
processed_input[f"Sex_{data['Sex']}"] = 1
# ChestPainType
processed_input[f"ChestPainType_{data['ChestPainType']}"] = 1
# RestingECG
processed_input[f"RestingECG_{data['RestingECG']}"] = 1
# ExerciseAngina
processed_input[f"ExerciseAngina_{data['ExerciseAngina']}"] = 1
# ST_Slope
processed_input[f"ST_Slope_{data['ST_Slope']}"] = 1
# Feature Engineering
processed_input['High_Cholesterol'] = 1 if data['Cholesterol'] > 240 else 0
# APPLY PRE-SCALING to specific columns
# RestingBP, Cholesterol, MaxHR, Oldpeak
for col in pre_scale_cols:
val = processed_input[col]
stat = pre_scale_stats[col]
processed_input[col] = (val - stat['mean']) / stat['std']
# 3. Create DataFrame and align
input_df = pd.DataFrame([processed_input])
final_df = pd.DataFrame(columns=expected_columns)
final_df.loc[0] = 0.0
for col in input_df.columns:
if col in final_df.columns:
final_df.at[0, col] = input_df.at[0, col]
# 4. Scale
print("\nFeature vector (first 5 and non-zero):")
row = final_df.iloc[0]
print(row[row != 0])
scaled_input = scaler.transform(final_df)
scaled_input = scaler.transform(final_df)
print("\nScaler Mean:", scaler.mean_)
print("Scaler Var:", scaler.var_)
print("Scaled input (first 5):", scaled_input[0][:5])
# 5. Predict
prediction = model.predict(scaled_input)[0]
probs = model.predict_proba(scaled_input)[0]
print(f"Prediction: {prediction} (Probabilities: {probs})")
try:
if hasattr(model, 'n_neighbors'):
print(f"Model K: {model.n_neighbors}")
except:
pass
return prediction
print("\n--- TEST CASE 1: Low Risk Profile (Young, Normal BP/Chol, No Angina) ---")
test_1 = {
'Age': 25, 'Sex': 'F', 'ChestPainType': 'ATA', 'RestingBP': 110,
'Cholesterol': 180, 'FastingBS': 0, 'RestingECG': 'Normal',
'MaxHR': 180, 'ExerciseAngina': 'N', 'Oldpeak': 0.0, 'ST_Slope': 'Up'
}
predict_manually(test_1)
print("\n--- TEST CASE 2: High Risk Profile (Older, High BP, Angina, Flat Slope) ---")
test_2 = {
'Age': 65, 'Sex': 'M', 'ChestPainType': 'ASY', 'RestingBP': 160,
'Cholesterol': 300, 'FastingBS': 1, 'RestingECG': 'ST',
'MaxHR': 110, 'ExerciseAngina': 'Y', 'Oldpeak': 2.5, 'ST_Slope': 'Flat'
}
predict_manually(test_2)