Book a free call

How to Detect Breast Cancer with TensorFlow and CNNs

TensorFlow and convolutional neural networks can flag suspicious regions in mammograms before a radiologist reviews them. Here is how the model is built and checked.

Hertiv engineering teamReviewed by a senior engineer
7 min read
How to Detect Breast Cancer with TensorFlow and CNNs
On this page

Short answer

TensorFlow breast cancer detection uses a convolutional neural network trained on labelled mammograms to flag regions that may show cancer. The model learns patterns such as masses, calcifications and tissue distortion from thousands of examples, then scores new scans so a radiologist can review the most suspicious ones first. It is a screening aid, not a diagnosis, and a clinician always makes the final call.

What is TensorFlow breast cancer detection with CNNs?

TensorFlow breast cancer detection with CNNs is a machine learning method that trains a convolutional neural network on labelled mammograms to spot signs of cancer. A convolutional neural network, or CNN, is a model built to read images: it learns visual patterns layer by layer, from simple edges to shapes that look like masses or clusters of calcifications.

TensorFlow is the open-source library used to build and train the model, usually through its Keras interface. The model takes a mammogram image as input and returns a score for each region, or for the whole image, showing how closely it resembles the cancer cases in the training data.

The goal is triage, not replacement. A trained radiologist still reads every scan and makes the diagnosis. The model helps by sorting the worklist so suspicious cases reach a human sooner, and by giving a second look at regions that are easy to miss. That distinction matters for safety, for regulation and for how the team measures success.

How does a CNN read a mammogram?

A CNN reads a mammogram by passing the image through a series of learned filters that pick out visual features at increasing levels of detail. Early layers respond to edges and contrast changes, middle layers respond to textures and shapes, and later layers combine those signals into a judgement about the whole image.

Two operations do most of the work. Convolution slides small filters across the image to build feature maps, which show where each pattern appears. Pooling then shrinks those maps, keeping the strongest signals and making the model less sensitive to small shifts in position. A dense layer at the end turns the final feature map into a score.

What the network learns depends entirely on the training data. If the examples include masses, calcifications, architectural distortion and normal tissue, the model can learn the difference. If a pattern never appears in training, the model cannot be expected to find it. That is why data quality, not model size, usually decides how well the system works.

What data does the model need?

The model needs mammograms labelled by experts, with each image marked as showing cancer, showing a benign finding, or showing normal tissue. Labels must come from confirmed outcomes such as biopsy results or follow-up imaging, not from a single reader's first impression, because weak labels teach the model the wrong lesson.

Volume matters, but variety matters more. The data should cover different patient ages, breast densities, imaging machines and clinics, because a model trained on one site often performs worse on scans from another. Public research datasets such as CBIS-DDSM exist for experimentation, but a production model needs data that matches the population it will serve.

Three data practices are non-negotiable. First, split the data by patient, not by image, so the same person never appears in both training and test sets. Second, keep a held-out test set that nobody touches until the final evaluation. Third, handle class imbalance, since cancer cases are a small share of screening scans, with techniques such as sampling, class weights or augmentation rather than by ignoring the problem.

How do you build the model in TensorFlow?

You build the model in TensorFlow by setting up a data pipeline, choosing an architecture, and training with a loss function that matches the task. Most teams start with transfer learning: they take a network pre-trained on general images and retrain its later layers on mammograms, which works far better than training from scratch on a small medical dataset.

ApproachWhen to use itWhat it needs
Train from scratchLarge labelled dataset availableThousands of confirmed cases, long training time
Transfer learningSmall or medium datasetPre-trained network, fine-tuning of later layers
Pre-trained featuresVery small datasetFrozen network as a feature extractor, simple classifier

The data pipeline uses tf.data to load, resize and normalise images, and to apply augmentation such as small rotations, flips and contrast changes. Augmentation matters because it teaches the model that a mass is still a mass when the image is flipped or slightly rotated.

For a binary task, cancer or not, the usual setup is a sigmoid output with binary cross-entropy loss and an Adam optimiser. Input size is a trade-off: full-resolution mammograms carry fine detail but need more memory, so teams often train on cropped regions or downscaled images and test both. How the model is evaluated is covered in AI medical imaging intelligence.

How do you train and measure the model?

You train and measure the model by tracking metrics that match the clinical job, not just overall accuracy. In screening, missing a cancer is far worse than flagging a healthy scan, so sensitivity matters most, while specificity keeps the false-alarm rate low enough for radiologists to trust the tool.

MetricWhat it measuresWhy it matters
Sensitivity (recall)Share of cancers the model flagsMissed cancers are the main risk
SpecificityShare of healthy scans clearedToo many flags waste clinician time
PrecisionShare of flags that are real cancersShows how useful each alert is
AUCRanking quality across thresholdsCompares models without fixing a threshold

Training uses a validation set to pick the best checkpoint and to stop early when the model stops improving. The decision threshold is a clinical choice: a lower threshold catches more cancers but flags more healthy scans, while a higher threshold does the reverse. The team should set it with radiologists, not by default.

Finally, test on data the model has never seen, ideally from a different clinic or machine. A model that scores well on its own test set but fails elsewhere has learned the quirks of one site, not the signs of cancer. Comparing frameworks before you commit is easier with TensorFlow vs PyTorch vs OpenCV.

How do you build it in six steps?

You build a TensorFlow breast cancer detection model in six steps, moving from data to a tested model that a clinical team can review.

  1. Collect and label the data. Gather mammograms with confirmed outcomes, de-identified and consented, covering the ages, densities and machines the model will face.
  2. Split by patient. Divide the data into training, validation and test sets with no patient in more than one set, and lock the test set away.
  3. Build the data pipeline. Use tf.data to resize, normalise and augment images, and to feed balanced batches during training.
  4. Choose the architecture. Start with transfer learning from a proven network, add a classification head, and keep the design simple enough to explain.
  5. Train with validation. Track sensitivity, specificity and AUC on the validation set, stop early when it stops improving, and tune the decision threshold with clinicians.
  6. Evaluate and explain. Test on held-out data, check where the model fails, and use a method such as Grad-CAM to show which image regions drove each decision.

Each step produces something a reviewer can check: a data sheet, a split log, a training record and an evaluation report. If any step cannot be shown, the model is not ready for clinical use.

Example (hypothetical): a clinic pilots a screening aid

Example (hypothetical): a screening clinic reads 2,000 mammograms a month and wants a TensorFlow CNN to sort the worklist. The team trains the model on 8,000 labelled scans from its own archive, split by patient, and holds out 1,000 scans for testing.

In the pilot month, the model flags 240 of the 2,000 new scans for priority review, which is 12 in every 100. Radiologists confirm that 18 of those 240 need follow-up, while the other 222 turn out to be clear after review. The remaining 1,760 scans go through the normal queue, and the team checks a sample of them to make sure nothing was missed.

The pilot saves time because the 18 cases needing follow-up reach a specialist days sooner than they would have in the normal queue. It also shows the trade-off clearly: for every case that needed follow-up, about 12 flagged scans were clear. The clinic keeps the threshold where it is, since missing a cancer costs far more than reviewing extra scans.

What are the common mistakes?

The most common mistakes in TensorFlow breast cancer detection are data leakage, chasing one metric, and treating the model as a diagnosis instead of a screening aid.

  • Leaking patients across splits. If the same patient appears in training and test sets, the scores look far better than the model really is.
  • Ignoring class imbalance. A model that always says "healthy" can look accurate on screening data while catching nothing.
  • Optimising accuracy alone. Accuracy hides the difference between a missed cancer and a false alarm, which have very different costs.
  • No external validation. A model tested only on its own clinic's scans may fail on another machine or population.
  • No explainability. If radiologists cannot see why the model flagged a region, they will not trust it, and neither should the team.
  • Skipping clinical review. A model without a clinician in the loop is a research demo, not a medical tool, and it needs proper approval before use.

Agent-based imaging workflows add another layer on top of the model, which is why teams often read about AI agents in medical image analysis before designing the full system.

Key takeaways

  • TensorFlow CNNs flag suspicious regions in mammograms so radiologists can review them first
  • Data quality decides performance: confirmed labels, patient-level splits and varied sources
  • Transfer learning beats training from scratch on the small datasets most clinics have
  • Sensitivity and specificity matter more than accuracy for a screening tool
  • A clinician always makes the final call; the model is a triage aid, not a diagnosis

Frequently asked questions

Is TensorFlow free to use for medical imaging?

Yes. TensorFlow is open source and free to download and use. Costs come from data collection, labelling, compute time and clinical validation, not from the library itself, so budget for those parts instead.

Can a CNN replace a radiologist?

No. A CNN can sort and flag scans, but diagnosis, patient communication and treatment decisions stay with clinicians. Regulators treat these tools as aids that support a human reader, not as replacements for one.

How much data does a breast cancer CNN need?

It depends on the approach. Transfer learning can start with a few thousand labelled scans, while training from scratch needs far more. Variety across machines, densities and clinics matters as much as volume.

What is Grad-CAM?

Grad-CAM is a method that highlights the image regions that most influenced a CNN decision. It helps radiologists check whether the model looked at a real finding or at an artefact.

TensorFlow or PyTorch for this task?

Both work well. TensorFlow has strong deployment tooling, while PyTorch is popular in research. Choose the one your team already knows, since data and evaluation matter more than the framework.

Does the model work on all breast densities?

Dense tissue makes mammograms harder to read for humans and models alike. A model trained mostly on low-density scans may perform worse on dense tissue, so test results by density group before use.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: AI and agent systems in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Building a medical imaging model? Talk to Hertiv.

A senior engineer replies within one business day. Or see our Machine Learning Development service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to contact@hertiv.com.

Prefer email? Write to contact@hertiv.com
Estimate costBook a call