MIT Applied Data Science and AI · Capstone project

Teaching a neural network to spot malaria in a single blood cell

I built and compared five convolutional neural networks that classify microscope images of red blood cells as parasitized or uninfected. The goal was a model accurate enough to help, and careful enough to almost never miss an infection.

Test accuracy
98.5%
Infected cells missed
19 of 1,300
Cell images
27,557
Architectures compared
5

01 · The problem

Diagnosis still depends on a trained eye and a microscope

Malaria remains one of the world's most serious health challenges. The World Health Organization estimated 249 million cases and 608,000 deaths in 2022, most of them young children and pregnant women in sub-Saharan Africa.

The standard diagnosis is a technician examining a blood smear under a microscope. It works, but it is slow, depends on scarce expertise, and is prone to human error. Rapid diagnostic tests exist, but they can lack sensitivity and are not always available in remote areas.

An image classifier that reads the same blood cell images could make screening faster and more consistent, and ease the load on health workers where it matters most.

  • 1

    Classify accurately

    Build a CNN that separates parasitized from uninfected cell images.

  • 2

    Minimize missed infections

    Prioritize recall on the parasitized class over raw accuracy.

  • 3

    Generalize

    Use preprocessing and augmentation so the model holds up on unseen cells.

  • 4

    Validate honestly

    Judge every model with confusion matrices and held-out test images.

02 · The data

27,557 single-cell images, split almost perfectly in half

Each image is one red blood cell cropped from a stained blood smear. Parasitized cells contain the Plasmodium parasite; uninfected cells do not.

Class balance

A balanced dataset means accuracy is a fair headline metric, and neither class dominates training.

Preparation

  • Resize. Raw crops ranged from 40×46 to 385×394 pixels. Every image was resized to 128×128.
  • Normalize. Pixel values were scaled from 0–255 down to 0–1.
  • Encode. Labels were one-hot encoded: parasitized = 0, uninfected = 1.
  • Clean. Corrupt or unreadable files were removed before training.

What the cells look like

Uninfected cells tend to be rounder, but shape is not reliable. The real tell is the stain: parasitized cells carry one or more dark purple or pink spots.

Try it

Can you spot the parasite?

You are the model for a minute. Look at the cell and make the call. Then see how you compare to the network's 98.5%.

No answers yet.

A stained red blood cell to classify

 

Looking for signal before training

Three quick explorations tested whether simple image processing makes the difference between classes easier to see.

Average of all parasitized training images: a soft purple discParasitized
Average of all uninfected training images: a nearly identical discUninfected
Mean images. Averaging every image in each class gives two nearly identical discs. The parasites sit in different places in every cell, so they average away. A model has to find local features.
Mean parasitized image after HSV conversion, with a purple ringParasitized
Mean uninfected image after HSV conversion, mostly greenUninfected
HSV color space. Converting to hue, saturation and value pulls the classes apart: the parasitized mean shows a purple ring that the uninfected mean lacks.
A blurred parasitized cell with a clear purple spotParasitized
A blurred uninfected cell with no spotUninfected
Gaussian blur. Blurring removes fine noise while the purple spot survives, which hints that the signal is a larger structure and not pixel-level texture.

03 · The models

Five architectures, one change at a time

Each model builds on a lesson from the one before. All were trained with the Adam optimizer and categorical cross-entropy, for up to 30 epochs with early stopping, then scored on the same 2,600 held-out test images. Pick a model to see how it was built and how it did.

04 · Results

The model trained on augmented images missed the fewest infections

Out of 1,300 infected test cells and 1,300 healthy ones, here is how many each model got wrong. Shorter bars are better, and the top bar in each pair is the one that matters most.

Test-set performance of all five models
Model Accuracy Recall infected Precision infected Missed False alarms Test loss Parameters

Recall is the share of infected cells the model caught. Precision is the share of its "infected" calls that were right. Both are computed from each model's confusion matrix on the 2,600 test images. One caveat: the test images also served as the validation data that early stopping monitored, so these figures are likely slightly optimistic. A stricter rerun would hold out part of the training set for that job.

05 · The final model

A small CNN, trained on images that never look the same twice

Model 4 was the most accurate, had the fewest missed infections, and its errors were evenly balanced: 19 missed infections against 20 false alarms. What set it apart was less the network and more the training data.

Architecture

    4.3 million trainable parameters, nearly all of them in the first dense layer.

    Data augmentation

    Every training image was randomly transformed each time the model saw it, so it could not simply memorize cells. The test images were left untouched.

    • Rotationup to 20°
    • Horizontal shiftup to 20%
    • Vertical shiftup to 20%
    • Shear0.2
    • Zoomup to 20%
    • Horizontal fliprandom

    A batch of augmented training images. The streaks at the edges come from filling in pixels after a shift or rotation.

    Show the Keras code
    def cnn_model_4():
        model = Sequential([
            Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(128, 128, 3)),
            MaxPooling2D(2, 2),
    
            Conv2D(64, (3, 3), activation='relu', padding='same'),
            MaxPooling2D(2, 2),
    
            Conv2D(128, (3, 3), activation='relu', padding='same'),
            MaxPooling2D(2, 2),
    
            Flatten(),
            Dense(128, activation='relu'),
            Dropout(0.5),                    # regularization to prevent overfitting
            Dense(2, activation='softmax')
        ])
        return model
    
    datagen = ImageDataGenerator(
        rescale=1.0/255,         # normalize pixel values to [0, 1]
        rotation_range=20,       # rotate up to 20 degrees
        width_shift_range=0.2,   # shift horizontally up to 20%
        height_shift_range=0.2,  # shift vertically up to 20%
        shear_range=0.2,         # shearing transformations
        zoom_range=0.2,          # zoom in or out up to 20%
        horizontal_flip=True,    # random horizontal flips
        fill_mode='nearest'      # fill new pixels from their nearest neighbors
    )

    06 · Further experiments

    Three more ideas, tested against the winner

    Activation

    Swish instead of ReLU

    The same three-block network with Swish activations in the convolutional layers, trained without augmentation. Early stopping ended training at epoch 7.

    95.8% test accuracy

    No improvement. ReLU stayed.

    Color space

    Training on HSV images

    A quick trial of a small CNN on HSV-converted images, using an 80/20 split of the 2,600 test images (2,080 to train, 520 to validate) for 30 epochs.

    98.5% validation accuracy

    Promising for so little data, and the top candidate for follow-up work.

    Augmentation

    How much distortion helps?

    The final architecture retrained with different augmentation strengths and scored on the test images.

    • Original settings (20°, 20%)96.8%55 missed
    • Slightly stronger (25°, 25%)98.2%22 missed
    • 90° rotation, 0.5 shear97.9%17 missed

    Heavier rotation and shear caught the most infections, at the cost of more false alarms (38). The original settings scored lower on this rerun than in the first run, a reminder that a point or so of difference between top models is within run-to-run variation.

    07 · Takeaways

    What I learned, and what I would do next

    Findings

    • Small CNNs are enough. Four of the five models scored 97% or better on unseen cells.
    • Accuracy hides the important errors. Models 1 and 3 both reached 97% accuracy, yet missed roughly three to seven times more infections than they raised false alarms.
    • Augmentation was the biggest lever. Training on randomly transformed images gave the best accuracy and the fewest missed infections.
    • Bigger was not better. Transfer learning with VGG16, with 15 million parameters, finished last and missed 147 infected cells.
    • Extra machinery did not help. Batch normalization with LeakyReLU, and Swish activations, both failed to beat plain ReLU.

    Next steps

    • Re-evaluate with a separate validation split. Hold out part of the training set for early stopping, and score the test images only once at the end, so the headline accuracy is fully unbiased.
    • Repeat each run several times with different seeds and report the average, since a single run can swing by a point or more.
    • Penalize false negatives directly with class weighting, so a missed infection costs more than a false alarm during training.
    • Combine HSV with Model 4. The HSV trial performed well enough to deserve a full run on the training set.
    • Mix augmented and original images in the training set, and explore more augmentation combinations.
    • Try global average pooling in place of the flatten layer to cut parameters without losing accuracy.
    • Go deeper selectively, adding layers and varied activations to the Model 4 design.

    Want every cell of code?

    The complete Jupyter notebook is available, with all the code, training logs and plots. A few result cells that displayed the wrong model's output have been corrected and are clearly marked.

    Open the full notebook