โ† Back to list

๐Ÿง  Building an AI-Powered Disease Classifier: A Machine Learning Journey

๐Ÿฉบ Introduction

Hafsa Zia ยท 2025-04-14 19:38 ยท 0 claps ยท 2.1 min read
#machine-learning #knn #data-reduction #classification #tf-idf
Open on Medium โ†—
Wiki topics: ML ยท Machine Learning AI ยท AI ยท General EDU ยท Education & Learning

๐Ÿง  Building an AI-Powered Disease Classifier: A Machine Learning Journey

๐Ÿฉบ Introduction

In todayโ€™s healthcare world, early and accurate diagnosis can be life-saving. But symptoms often overlap โ€” fever could signal the flu, COVID-19, or pneumonia. Even seasoned clinicians can struggle to differentiate them.

So I asked: Can machine learning help?

To find out, I built an end-to-end AI system that predicts diseases based on symptoms and risk factors. Along the way, I compared K-Nearest Neighbors (KNN) and Logistic Regression.

In this blog, youโ€™ll discover:

โœ… Data preprocessing & feature engineering โœ… Model training & evaluation โœ… Key insights & deployment โœ… Real-world applications

Letโ€™s dive in! ๐Ÿ‘‡

1๏ธโƒฃ The Problem & Approach

๐ŸŽฏ Objective

Build a machine learning model that:

  • Accepts symptoms (e.g., fever, cough) and risk factors (e.g., diabetes, smoking)
  • Predicts the most likely disease
  • Compares the performance of KNN vs. Logistic Regression

๐Ÿ“Š Dataset

The dataset included:

  • Symptoms: Text-based (e.g., โ€œnausea, dizzinessโ€)
  • Risk Factors: Categorical (e.g., hypertension: yes/no)
  • Diseases: Labeled outcomes (e.g., COPD, Diabetes)

2๏ธโƒฃ Data Preprocessing & Feature Engineering

๐Ÿงพ Text Features: Symptoms

Symptoms were vectorized using TF-IDF (Term Frequency-Inverse Document Frequency), which:

  • Converts raw text into numerical format
  • Gives higher weight to rare (but significant) terms like โ€œhemoptysisโ€
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(token_pattern=r'\b\w+\b', stop_words='english')
symptoms_tfidf = tfidf.fit_transform(df['Symptoms'].apply(' '.join))

๐Ÿงฌ Categorical Features: Risk Factors

Risk factors were encoded using One-Hot Encoding:

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
risk_factors_encoded = encoder.fit_transform(df[['Hypertension', 'Diabetes']])

๐Ÿงฉ Final Feature Set

We combined text and categorical features using hstack:

from scipy.sparse import hstack
X = hstack([symptoms_tfidf, risk_factors_encoded])
y = df['Disease']

3๏ธโƒฃ Model Training & Evaluation

๐Ÿงช Algorithms Tested

Model Hyperparameters Tested KNN k = 3, 5, 7; Metrics = Euclidean, Manhattan, Cosine Logistic Regression Penalty = L1/L2, class_weight balancing

โš™๏ธ Training Process

  • 5-fold cross-validation for robustness
  • Stratified sampling to address class imbalance
  • Metrics: Accuracy, Precision, Recall, F1-score
from sklearn.model_selection import cross_validate
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3, metric='cosine')
cv_scores = cross_validate(knn, X, y, cv=5, scoring=['accuracy', 'f1_weighted'])

๐Ÿ“ˆ Results

Model Accuracy F1-Score Best Configuration KNN 87% 0.85 k=3, Cosine similarity Logistic Regression 83% 0.81 L2 penalty, class_weight='balanced'

๐Ÿ’ก Why KNN won: Cosine similarity handled symptom vectors well, while Logistic Regression struggled with rare diseases.

4๏ธโƒฃ Deployment & Real-World Use Cases

๐Ÿ’พ Saving the Model

Used joblib to serialize the trained model:

import joblib
joblib.dump(knn, 'disease_predictor.pkl')

๐Ÿ” Prediction Example

from predictor import DiseasePredictor
model = DiseasePredictor.load('disease_predictor.pkl')
model.predict([["fever", "cough", "fatigue"]])  # โžœ ['Influenza']

๐ŸŒ Real-World Applications

  1. Telemedicine Platforms: Pre-consultation triage
  2. Hospital Support Tools: Assist doctors with differential diagnosis
  3. Public Health Systems: Track symptom clusters and disease spread

5๏ธโƒฃ Challenges & Lessons Learned

โœ”๏ธ Class Imbalance: Handled using stratified cross-validation โœ”๏ธ Text Representation: TF-IDF outperformed Bag-of-Words โœ”๏ธ Interpretability vs. Accuracy: Logistic Regression was easier to explain, but KNN performed better

๐Ÿงช Whatโ€™s Next?

  • Experiment with BERT embeddings for smarter text understanding
  • Integrate lab test results and vitals for improved accuracy

โœ… Conclusion

This project showed that machine learning can assist clinicians by suggesting potential diagnoses. While not a replacement for doctors, it can support faster, smarter decisions.

๐Ÿ› ๏ธ Final Result:

  • Best model: KNN (Cosine Similarity + TF-IDF)
  • Use cases: Telehealth, diagnostics, public health monitoring

๐Ÿ‘‰ Try it yourself: GitHub Repo


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
f9c61e2300a8
slug
building-an-ai-powered-disease-classifier-a-machine-learning-journey-f9c61e2300a8
url
https://medium.com/@hafsaz2533/building-an-ai-powered-disease-classifier-a-machine-learning-journey-f9c61e2300a8
canonical_url
https://medium.com/@hafsaz2533/building-an-ai-powered-disease-classifier-a-machine-learning-journey-f9c61e2300a8
author_url
https://medium.com/@hafsaz2533
status
ok
fetched_at
2026-07-21 20:37:53