Brain Tumor MRI Classification with Deep Learning: Training and Web Deployment Practice
This article presents an end-to-end engineering practice for four-class brain tumor MRI classification. It covers data governance, transfer learning training, evaluation and rejection calibration, Web backend deployment, recognition-history management, and a statistics dashboard. The system is positioned as a teaching and research reference rather than a diagnostic tool. The article provides reusable pseudocode and engineering notes for reproducibility, evaluation, deployment, and traceability.
Brain tumors are common tumors of the nervous system, and MRI is one of the primary imaging modalities for brain examination. Image interpretation relies on physicians reading images one by one, and differences in workload and experience objectively exist, so auxiliary interpretation tools have practical demand. In recent years, convolutional neural networks have become increasingly mature for medical image classification, and public brain tumor MRI datasets have lowered the experimental barrier; a consumer-grade GPU is sufficient for transfer learning training. For undergraduate computer science students, this topic covers data processing, model training, and website deployment. It combines algorithmic and engineering content, and its difficulty and scope make it suitable for a final-year or capstone project. The background is realistic, and literature and data resources are sufficient, so the project can be advanced according to a plan. This article takes four-class brain tumor MRI classification as the main line and explains the complete engineering chain from data governance, transfer learning training, evaluation, and rejection calibration to Web backend deployment, recognition-history management, and a statistics dashboard. It also provides reusable pseudocode and engineering notes.
1. Task Definition and System Boundaries
The task objective is to classify brain MRI images into four categories: glioma, meningioma, no tumor, and pituitary tumor. The system is positioned as a teaching and research auxiliary reference. Its output cannot replace a physician’s diagnosis and still has a gap from real clinical application. This limitation should be stated truthfully in documentation, page prompts, and project presentations, maintaining objective wording without exaggeration. Once the system boundary is clear, the engineering objectives are also clear: first, train a reproducible and evaluable classification model; second, package the model as a demonstrable Web service; third, provide account login and three recognition entrances: image recognition, video recognition, and real-time camera recognition; fourth, support paginated recognition-history queries, detail viewing, and soft deletion; fifth, provide a statistics dashboard that aggregates recognition counts and category distribution.
From the perspective of a capstone project, the value of this topic is reflected at three levels. At the learning level, completing the engineering chain of transfer learning, training tuning, model export, and Web deployment turns scattered knowledge points into an overall workflow understanding of deep learning projects. At the outcome level, the project produces a runnable website and a set of figures suitable for a paper, and the project presentation is intuitive. At the topic-selection level, the background is realistic, the workload is controllable, and the topic is suitable for an undergraduate capstone project. To avoid the common problem of “only getting training to run without completing the engineering loop,” it is advisable to determine data splits, metric logging, model export, and interface contracts early in the project so that the training side and the deployment side can proceed in parallel.
2. Data Governance: Splitting, Profiling, and Mislabel Scanning
The data uses a public deduplicated brain tumor MRI dataset, with about 6,500 images covering four categories. The first step in data governance is to physically split the data into training, validation, and test sets rather than randomly splitting only in memory. Physical splitting facilitates experimental reproducibility, avoids data leakage between different rounds, and allows the deployment side to fix the test set for regression verification. The class proportions should be kept as consistent as possible during splitting, and stratified sampling can be used. If class imbalance is obvious, class weights or resampling strategies should be used on the training side, and accuracy, precision, recall, F1 score, and the confusion matrix should be reported together on the evaluation side.
Data profiling should include at least: sample counts per category, image size distribution, channel count distribution, brightness and contrast statistics, duplicate sample checks, corrupted file checks, label distribution, and comparison of distributions before and after splitting. Mislabel scanning can use a “model-assisted + manual review” approach: first use a baseline model to make cross-validation predictions on the training set, filter samples with high confidence but inconsistent labels, and then manually spot-check them. For medical imaging data, a mislabel is not necessarily a true mislabel; it may also be a borderline case or ambiguity in the label system. Therefore, the scanning record should retain the original image ID, predicted category, confidence, review conclusion, and handling action, forming a traceable data-governance log.
Data augmentation should preserve the reasonableness of medical images. Mild rotation, translation, scaling, and contrast perturbation are generally usable; excessive flipping and strong color perturbation may change anatomical semantics and should be used cautiously. Preprocessing parameters for the training, validation, and test sets must be consistent. Normalization parameters such as mean and variance can only be calculated from the training set to avoid information leakage from the validation and test sets. For the video recognition and real-time camera recognition entrances, frame sampling strategy, blurred-frame filtering, and consecutive-frame deduplication should also be considered to avoid repeated counting of the same scene.
3. Model Training: Transfer Learning, Short Sweep, and Early Stopping
On the model side, a pretrained residual convolutional network is used for transfer learning. The reason for choosing a residual structure is that it has good feature extraction capability for medium-scale medical image classification tasks, and pretrained weights can alleviate the problem of limited data. Before training, a short learning-rate sweep should be performed: try several learning-rate ranges within a small number of epochs, observe changes in training loss and validation metrics, determine a relatively stable parameter range, and then enter full training. The purpose of the short sweep is not to pursue a single optimal run, but to avoid divergence caused by too large a learning rate and slow convergence caused by too small a learning rate.
During training, early stopping and mixed precision are recommended. Early stopping uses the primary validation-set metric as the criterion; if it does not improve for several consecutive epochs, training stops and rolls back to the best weights. Mixed precision can reduce memory usage and improve throughput on supported hardware, but numerical stability should be considered, and loss scaling and gradient clipping should be configured when necessary. Per-epoch metrics should be written to a CSV file or database table, recording at least training loss, validation loss, validation accuracy, validation F1 score, learning rate, elapsed time, and best-model marker. After training, export weights in two formats: framework-native weights for continued training and deployment loading, and a generic exchange format for cross-environment inference and model archiving. After export, a consistency check must be performed to ensure that the output difference for the same batch of test samples under the two formats is within an acceptable range.
Pseudocode is shown below:
Initialize data loaders: training set, validation set, test setLoad a pretrained residual convolutional network and replace the classification head with four-class outputShort-sweep the learning-rate range and record loss and validation metricsfor epoch in max_epochs:Switch model to training modefor image_batch, label_batch in training_set:Forward pass to compute outputCompute classification lossBackpropagate and update parametersSwitch model to evaluation modeCompute loss and primary metrics on the validation setWrite per-epoch metrics to the metrics tableIf validation metrics improve, save the best weightsIf there is no improvement for several consecutive epochs, stop earlyExport native weights and generic exchange formatRun final evaluation on the test set and generate figures
Training tuning should follow the order of “stabilize first, then improve”: first fix the augmentation strategy and input size, and determine the learning rate and batch size; then adjust class weights, loss function, and early-stopping patience; finally try more complex augmentation or deeper structures. Change only a small number of variables each time, and write each experimental configuration into a configuration file or experiment log to avoid irreproducibility caused by “tuning by feel.”
4. Evaluation, Interpretability, and Out-of-Distribution Rejection
Evaluation cannot rely only on overall accuracy. The confusion matrix can reveal confusion relationships between categories; for example, some tumor categories are easily misclassified as each other on low-contrast images. Calibration curves can show whether model confidence is consistent with actual correctness; if the model is clearly overconfident, probability display should be handled cautiously on the deployment side. Gradient-based class activation heatmaps can help observe the regions the model focuses on and can be used for project presentations and error analysis, but they cannot serve as a clinical basis. Test-set evaluation should fix the random seed and preprocessing pipeline, and reported metrics should include sample size and category distribution.
Out-of-distribution rejection is an important part of an auxiliary system. Real inputs may include non-brain MRI images, images with severe artifacts, or images unrelated to the four categories. Two types of rejection thresholds, energy score and nearest-neighbor distance, can be calibrated on the validation set: the energy score measures the model’s overall confidence in the input, and the nearest-neighbor distance measures the deviation of input features from the training distribution. Threshold selection should balance the rejection rate and false-rejection rate; normal samples must not be rejected in large numbers merely to reduce misclassification. During deployment, quality checking can be performed first, then classification, and finally a prompt of “unable to judge reliably” can be returned according to the thresholds. Rejection results should also be written into recognition history for later statistics and review.
5. Web Deployment: Entrances, History, and Dashboard
On the deployment side, a Web backend framework is used to build the service, and a relational database stores accounts, recognition records, model versions, and operation logs. The website provides account login and three recognition entrances: image recognition, video recognition, and real-time camera recognition. Image recognition receives a single image, completes preprocessing, inference, threshold judgment, and result persistence. Video recognition samples frames or extracts keyframes, aggregates multi-frame results, and avoids category jumps caused by single-frame noise. Real-time camera recognition should limit request frequency, use queues or asynchronous tasks to smooth traffic peaks, and display recent results and confidence prompts on the frontend.
Recognition history supports paginated queries, detail viewing, and soft deletion. Paginated queries should be sorted by time in descending order and provide filters such as category, time range, and rejection status. The detail page displays the original image thumbnail, predicted category, confidence, threshold judgment, model version, and creation time. Soft deletion only updates the status field without physically deleting data, which helps keep statistical definitions stable and allows recovery from accidental deletion. The statistics dashboard summarizes recognition counts and category distribution, can aggregate by day, week, or month, and displays total recognition volume, category proportions, rejection count, average confidence, and recent trends. Dashboard data should be generated through aggregate queries or scheduled summary tables to avoid scanning all detail records on every refresh.
Deployment pseudocode is shown below:
Route /login: authenticate account and establish sessionRoute /predict/image: receive image, quality check, preprocess, model inference, threshold judgment, write to historyRoute /predict/video: receive video, extract frames, batch inference, aggregate results, write to historyRoute /predict/camera: receive real-time frame, rate limit, inference, return recent resultRoute /history: paginated query with filters for category, time, and rejection statusRoute /history/detail: view record detailsRoute /history/delete: soft-delete recordRoute /dashboard: aggregate recognition counts and category distribution
From an engineering perspective, model loading should be decoupled from request handling: load and cache the model when the service starts, and let inference interfaces perform only preprocessing and inference. Validate input size, file type, and file size; return unified error codes for abnormal requests; and log and monitor inference latency, rejection rate, and category distribution. If cloud expansion is needed, a generic object storage service can be used to save original images and exported models, a container platform can host the service, and logging and monitoring services can observe interface health. These capabilities should be selected by generic category and should not depend on vendor-specific custom interfaces.
6. Project Wrap-Up and Conclusion
In the project wrap-up phase, the core code documentation, directory structure, environment dependencies, data-splitting scripts, training configuration, model export verification, interface documentation, and demo scripts should be completed. Paper figures should include at least a data distribution chart, training curves, a confusion matrix, a calibration curve, heatmap examples, and a screenshot of the statistics dashboard. All metrics should specify the test-set definition and model version to avoid treating validation-set results as final performance. The final system should clearly state its boundary as a “teaching and research auxiliary reference,” provide non-diagnostic prompts on pages, and truthfully explain the gap from real clinical application in the documentation.
Overall, this approach uses four-class brain tumor MRI classification as an entry point and connects data governance, transfer learning training, evaluation calibration, rejection thresholds, Web deployment, and statistical display into a complete engineering chain. For readers, the key takeaway is not a single-point metric of a particular model, but an understanding of how to make training results reproducible, evaluable, deployable, and traceable, while maintaining objective and standardized wording in real demonstration scenarios.
