Summary
- Goal: predict whether a patient has chronic kidney disease (CKD) from routine clinical measurements.
- Compared five classifiers: Random Forest, Logistic Regression, K-Nearest Neighbours, Support Vector Machine and Naive Bayes.
- SVM performed best, with 96.3% accuracy and F1-score.
- The biggest lessons were about data: missing values, scaling, and choosing the right metric for medical screening.
This was a university machine-learning project (CSE427, BRAC University). The model is not validated for clinical use and must not be used for diagnosis.
Chronic kidney disease often progresses silently: many patients have few symptoms until kidney function is seriously reduced. Early screening with routine blood and urine tests can make a large difference, which makes CKD a natural test case for machine learning on tabular clinical data. In this project my team trained and compared five classic classifiers. The full code is on GitHub, and there is a presentation video. Here I explain the reasoning behind each step — the part code alone doesn't show — using a cleaned-up version of the pipeline that you can reuse on your own tabular data.
The data
We used a publicly available CKD dataset of patient records (dataset link) with a mix of numeric and categorical clinical attributes, and a label indicating CKD or not. Typical features in this kind of dataset include:
- Numeric: age, blood pressure, blood glucose, blood urea, serum creatinine, sodium, potassium, haemoglobin, packed cell volume, white and red blood cell counts.
- Categorical: presence of hypertension, diabetes, anaemia, pedal oedema, appetite, and urine test results such as albumin and sugar levels.
Like most real clinical data, it was messy: many records had missing values, some numeric columns were stored as text, and a few categorical values had inconsistent spellings and stray whitespace.
Step 1: Cleaning
Before any modelling, fix data types and spellings. A small amount of careful cleaning is worth more than any hyperparameter tuning.
import pandas as pd
import numpy as np
df = pd.read_csv("kidney_disease.csv")
# strip whitespace / tabs from text columns and unify spellings
for col in df.select_dtypes(include="object"):
df[col] = df[col].astype(str).str.strip().replace({"nan": np.nan, "?": np.nan})
# columns that should be numeric but were read as text
for col in ["pcv", "wc", "rc"]:
df[col] = pd.to_numeric(df[col], errors="coerce")
df["classification"] = df["classification"].map({"ckd": 1, "notckd": 0})
df = df.dropna(subset=["classification"])
print(df.isna().mean().sort_values(ascending=False).head(10))
Printing the share of missing values per column is the first thing I do with any dataset. Here several lab measurements were missing for a significant fraction of patients — dropping those rows would have thrown away a large part of a small dataset.
Step 2: Handling missing values without leaking information
The pipeline below imputes missing values: the median for numeric columns (robust to extreme lab values) and the most frequent value for categorical ones. The crucial detail is where imputation happens. If you compute medians on the whole dataset before splitting, information from the test set leaks into training and your accuracy looks better than it really is. Putting imputation inside a scikit-learn Pipeline guarantees it's learned from the training folds only.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = df.drop(columns=["id", "classification"], errors="ignore")
y = df["classification"].astype(int)
numeric = X.select_dtypes(include="number").columns
categorical = X.select_dtypes(exclude="number").columns
preprocess = ColumnTransformer([
("num", Pipeline([("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())]), numeric),
("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore"))]), categorical),
])
Step 3: Five models, one fair comparison
Each model gets the same preprocessing and is evaluated with stratified cross-validation, which keeps the ratio of CKD to non-CKD patients the same in every fold. With a small dataset, a single train/test split can be lucky or unlucky; averaging over folds gives a more trustworthy number.
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.preprocessing import FunctionTransformer
to_dense = FunctionTransformer(lambda m: m.toarray() if hasattr(m, "toarray") else m)
models = {
"Random Forest": RandomForestClassifier(n_estimators=300, random_state=42),
"Logistic Regression": LogisticRegression(max_iter=2000),
"KNN": KNeighborsClassifier(n_neighbors=5),
"SVM": SVC(kernel="rbf", C=1.0, gamma="scale"),
"Naive Bayes": Pipeline([("dense", to_dense), ("nb", GaussianNB())]),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for name, model in models.items():
pipe = Pipeline([("prep", preprocess), ("model", model)])
scores = cross_validate(pipe, X, y, cv=cv, scoring=["accuracy", "f1", "recall"])
print(f"{name:20} acc={scores['test_accuracy'].mean():.3f} "
f"f1={scores['test_f1'].mean():.3f} recall={scores['test_recall'].mean():.3f}")
(Naive Bayes in scikit-learn needs a dense matrix, hence the small conversion step.)
Results and why SVM won
In our experiments the Support Vector Machine reached 96.3% accuracy and a matching F1-score, the best of the five models. Several factors favour SVMs on this kind of problem:
- Small, clean feature space. With a few hundred patients and a couple of dozen features, SVMs find a robust boundary without needing huge amounts of data.
- Scaling helps SVM a lot. Lab values live on very different scales (creatinine vs. blood glucose). Because every model received standardised features, SVM's distance-based margin worked as intended.
- Strong individual signals. Markers such as serum creatinine, haemoglobin and packed cell volume separate CKD and non-CKD patients well, and the RBF kernel captures the non-linear combinations.
The other models also performed well — CKD screening data is fairly separable — which is a reminder that on simple tabular problems, careful preprocessing often matters more than the choice of algorithm.
Accuracy isn't enough: think about errors
In medical screening, the two kinds of mistakes are not equal:
- A false negative (telling a CKD patient they're fine) can delay treatment.
- A false positive (flagging a healthy person) usually means an extra confirmatory test.
So alongside accuracy you should look at recall (sensitivity) for the CKD class and at the confusion matrix. If recall is too low, you can lower the decision threshold, which trades some false positives for fewer missed patients. That's a clinical decision as much as a technical one, and it should be made together with domain experts.
What I would do differently today
- Use a separate hold-out test set, untouched until the very end, in addition to cross-validation, and tune hyperparameters with nested cross-validation.
- Report confidence intervals. On a few hundred records, the difference between 95% and 96% may not be meaningful.
- Explain predictions. Tools like SHAP or permutation importance would show which features drive each prediction — essential for any medical audience.
- Check calibration. A model that outputs reliable probabilities ("70% risk") is more useful to clinicians than a yes/no label.
- Validate externally. A model trained on one hospital's patients can fail on another's. Real-world use would require testing on data from Nepali hospitals and labs.
Key lessons for your own ML projects
- Look at missing values and data types before anything else.
- Put all preprocessing inside a pipeline to avoid leakage.
- Compare several simple models with cross-validation before reaching for deep learning.
- Choose metrics that reflect the real cost of each kind of error.
If you're learning machine learning, a project like this — small, messy, meaningful data — teaches more than a perfectly clean tutorial dataset. For the data-cleaning side in more depth, see my pandas data-cleaning guide.
Spotted an error or have a question about this article? Send me a message — corrections are applied and noted with an updated date. See the editorial policy.