The dataset viewer is not available because its heuristics could not detect any supported data files. You can try uploading some data files, or configuring the data files location manually.
- π Database Overview
- π¬ Tuberculosis Classes
- π Database Files
- π Usage
- π§ Model Architecture
- π Performance Characteristics
- π§ Technical Details
- π Use Cases
- π Global TB Context
- π Data Privacy & Ethics
- π οΈ Building the Database
- π Dataset Statistics
- π Citation
- π Contact & Support
- βοΈ License
- π About Gaston Software Solutions LLP
- π Related Databases
π« Tuberculosis Chest X-Ray RAG Database (Part 3)
A specialized Retrieval-Augmented Generation (RAG) database for tuberculosis detection from chest X-ray images, built using DenseNet-121 deep learning model and FAISS vector search.
Developed by: Gaston Software Solutions LLP
Location: Ntinda, Kampala, Uganda
Contact: info@gss-tec.com
Website: www.gss-tec.com
π Database Overview
Statistics
- Total Images: 4,200 chest X-ray images
- Embedding Dimension: 1,024 features per image
- Model: DenseNet-121 (pretrained on ImageNet)
- Vector Index: FAISS (GPU-accelerated)
- Dataset: Tuberculosis TB Chest X-Ray Dataset
Dataset Distribution
| Class | Images | Percentage | Description |
|---|---|---|---|
| Normal | 3,500 | 83.3% | Healthy chest X-rays |
| Tuberculosis | 700 | 16.7% | TB-positive chest X-rays |
| Total | 4,200 | 100% | TB screening dataset |
Class Imbalance Note
This dataset reflects real-world TB screening scenarios where:
- Normal cases are more common (83.3%)
- TB cases are less frequent (16.7%)
- Ratio approximates actual TB prevalence in screening programs
π¬ Tuberculosis Classes
1. Normal (3,500 images)
- Type: Healthy chest X-rays
- Characteristics:
- Clear lung fields
- Normal cardiac silhouette
- No infiltrates or consolidation
- No cavitation or nodules
- Purpose: Baseline for TB detection
- Clinical Use: Negative screening results
2. Tuberculosis (700 images)
- Type: TB-positive chest X-rays
- Characteristics:
- Pulmonary infiltrates
- Cavitary lesions
- Nodular opacities
- Upper lobe predominance
- Possible pleural effusion
- Severity: Active pulmonary tuberculosis
- Clinical Use: Positive screening requiring treatment
π Database Files
The RAG database consists of three essential files:
1. embeddings.npy (~16 MB)
- Format: NumPy array
- Shape: (4200, 1024)
- Content: DenseNet-121 feature vectors for all chest X-rays
- Purpose: Dense vector representations for similarity search
2. metadata.json (~1.1 MB)
- Format: JSON
- Content: Image metadata including:
image_path: Original file pathclass: TB classification (Normal or Tuberculosis)dataset: Source dataset name (tuberculosis)filename: Image filename
- Purpose: Linking search results back to original X-rays
3. faiss_index.bin (~16 MB)
- Format: FAISS binary index
- Type: IndexFlatIP (Inner Product)
- Content: Optimized vector search index
- Purpose: Fast similarity search across 4,200 chest X-rays
π Usage
Loading the Database
import numpy as np
import faiss
import json
from pathlib import Path
# Load embeddings
embeddings = np.load('embeddings.npy')
# Load metadata
with open('metadata.json', 'r') as f:
metadata = json.load(f)
# Load FAISS index
index = faiss.read_index('faiss_index.bin')
print(f"Loaded {index.ntotal} chest X-ray vectors")
# Check class distribution
tb_count = sum(1 for m in metadata if 'Tuberculosis' in m['class'])
normal_count = sum(1 for m in metadata if 'Normal' in m['class'])
print(f"TB cases: {tb_count}, Normal cases: {normal_count}")
Performing Similarity Search
from PIL import Image
import torchvision.transforms as transforms
import torchvision.models as models
import torch
# Load DenseNet-121 model
model = models.densenet121(weights=models.DenseNet121_Weights.IMAGENET1K_V1)
model.classifier = torch.nn.Identity()
model.eval()
# Image preprocessing
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
# Extract features from query chest X-ray
def extract_features(image_path):
img = Image.open(image_path).convert('RGB')
img_tensor = transform(img).unsqueeze(0)
with torch.no_grad():
features = model(img_tensor).numpy()
# Normalize
features = features / np.linalg.norm(features)
return features
# Search for similar chest X-rays
query_features = extract_features('patient_xray.jpg')
k = 10 # Number of similar X-rays to retrieve
distances, indices = index.search(query_features, k)
# Get results
print("Similar chest X-rays:")
for i, idx in enumerate(indices[0]):
result = metadata[idx]
diagnosis = result['class'].replace('tuberculosis_', '')
print(f"{i+1}. {diagnosis.upper()} - {result['filename']}")
print(f" Similarity: {distances[0][i]:.4f}")
TB-Specific Search
def search_tb_cases(query_features, k=5):
"""Search only among TB-positive cases"""
# Get indices of TB cases
tb_indices = [i for i, m in enumerate(metadata)
if 'Tuberculosis' in m['class']]
# Create TB-only index
tb_embeddings = embeddings[tb_indices]
tb_index = faiss.IndexFlatIP(1024)
faiss.normalize_L2(tb_embeddings)
tb_index.add(tb_embeddings)
# Search
distances, indices = tb_index.search(query_features, k)
# Map back to original indices
results = []
for idx in indices[0]:
original_idx = tb_indices[idx]
results.append(metadata[original_idx])
return results, distances[0]
# Find similar TB cases
tb_results, scores = search_tb_cases(query_features, k=5)
print("\nSimilar TB cases:")
for i, result in enumerate(tb_results):
print(f"{i+1}. {result['filename']} - Score: {scores[i]:.4f}")
Screening Support System
def tb_screening_support(query_features, threshold=0.75):
"""
Provide screening support by finding similar cases
Returns: (similar_cases, tb_probability_estimate)
"""
k = 20 # Check top 20 similar cases
distances, indices = index.search(query_features, k)
# Count TB cases in top results
tb_count = 0
similar_cases = []
for i, idx in enumerate(indices[0]):
if distances[0][i] >= threshold: # Only high similarity
result = metadata[idx]
similar_cases.append({
'filename': result['filename'],
'class': result['class'],
'similarity': float(distances[0][i])
})
if 'Tuberculosis' in result['class']:
tb_count += 1
# Estimate TB probability based on similar cases
tb_probability = tb_count / len(similar_cases) if similar_cases else 0
return similar_cases, tb_probability
# Use for screening
similar, tb_prob = tb_screening_support(query_features)
print(f"\nTB Probability Estimate: {tb_prob*100:.1f}%")
print(f"Based on {len(similar)} similar cases")
π§ Model Architecture
DenseNet-121
- Architecture: Dense Convolutional Network
- Layers: 121 layers with dense connections
- Feature Dimension: 1,024
- Pretrained: ImageNet-1K
- TB Detection Advantages:
- Excellent feature extraction for chest X-rays
- Captures subtle pulmonary patterns
- Proven performance on medical imaging
- Efficient for large-scale screening
π Performance Characteristics
Search Performance
- Index Type: Flat (exact search)
- Distance Metric: Inner Product (cosine similarity)
- Search Speed: <1ms per query (GPU)
- Accuracy: 100% (exact nearest neighbors)
Memory Requirements
- Total Size: ~33 MB (all three files)
- RAM for Loading: ~60 MB
- GPU Memory: ~500 MB (for model inference)
Dataset Characteristics
- Class Imbalance: 5:1 ratio (Normal:TB)
- Real-world Reflection: Mirrors actual screening scenarios
- Considerations:
- More normal cases for robust baseline
- Sufficient TB cases for pattern learning
- Balanced for screening applications
π§ Technical Details
Feature Extraction Pipeline
- Input: Chest X-ray images (grayscale or RGB)
- Preprocessing:
- Convert to RGB if grayscale
- Resize to 256Γ256
- Center crop to 224Γ224
- Normalize with ImageNet statistics
- Model: DenseNet-121 (without classification layer)
- Output: 1,024-dimensional feature vector
- Normalization: L2 normalization for cosine similarity
Vector Index
- Algorithm: FAISS IndexFlatIP
- Normalization: L2-normalized vectors
- Similarity: Cosine similarity via inner product
- GPU Support: Yes (for faster search)
π Use Cases
1. TB Screening Support
- Assist radiologists in TB detection
- Find similar historical TB cases
- Support differential diagnosis
- Reduce false negatives in screening
2. Quality Assurance
- Second opinion for TB diagnosis
- Peer review of screening results
- Training validation for radiologists
- Consistency checks across readers
3. Medical Education
- Teaching TB radiological patterns
- Case-based learning
- Demonstrate disease progression
- Train medical students and residents
4. Research Applications
- Study TB presentation patterns
- Analyze radiological features
- Build training datasets for AI
- Validate diagnostic algorithms
5. Public Health Programs
- Mass screening campaigns
- Contact tracing support
- Treatment monitoring
- Epidemiological studies
π Global TB Context
Tuberculosis Facts
- Global Burden: ~10 million new TB cases annually
- Mortality: One of top 10 causes of death worldwide
- Screening: Chest X-ray is primary screening tool
- Challenge: Requires expert radiologist interpretation
- Solution: AI-assisted screening can improve access
Screening Importance
- Early Detection: Critical for treatment success
- Contact Tracing: Identify exposed individuals
- Public Health: Control TB transmission
- Resource-Limited: AI support in areas with few radiologists
π Data Privacy & Ethics
Important Considerations
- Public Dataset: From publicly available Kaggle dataset
- De-identification: Ensure patient privacy in deployment
- Clinical Use: Screening support tool, not diagnostic device
- Validation: Always confirm with qualified radiologists
- Regulatory: Requires medical device approval for clinical use
- Bias: Be aware of dataset limitations
- False Negatives: Critical to minimize in TB screening
Clinical Deployment Guidelines
- Not a Replacement: Supplement, not replace, radiologist review
- Validation Required: Extensive clinical validation needed
- Regulatory Approval: Obtain necessary certifications
- Quality Control: Regular performance monitoring
- Training: Proper training for healthcare workers
- Documentation: Clear limitations and use cases
π οΈ Building the Database
The database was built using:
- Notebook:
Health_Imaging_RAG_Colab_Part3.ipynb - Platform: Google Colab with T4 GPU
- Processing Time: ~8-12 minutes
- Framework: PyTorch + FAISS
- Model: DenseNet-121 (torchvision)
Dataset Source
- Kaggle:
tawsifurrahman/tuberculosis-tb-chest-xray-dataset - Original Size: 4,200 chest X-rays
- Format: JPEG/PNG images
- Classes: 2 classes (Normal, Tuberculosis)
π Dataset Statistics
Image Distribution
Normal: ββββββββββββββββββββββββββββββββββββββββ 3,500 (83.3%)
Tuberculosis: ββββββββ 700 (16.7%)
Quality Metrics
- Imbalance Ratio: 5:1 (reflects real-world screening)
- Image Quality: Clinical-grade chest X-rays
- Coverage: Diverse TB presentations
- Reliability: Suitable for screening support systems
π Citation
If you use this database in your research, please cite:
@software{tuberculosis_rag_2026,
author = {{Gaston Software Solutions LLP}},
title = {Tuberculosis Chest X-Ray RAG Database},
year = {2026},
publisher = {GSS-LLP},
address = {Ntinda, Kampala, Uganda},
url = {https://www.gss-tec.com},
note = {TB screening support system using DenseNet-121 and FAISS}
}
Please also cite the original dataset:
@dataset{tuberculosis_xray,
author = {Tawsifur Rahman},
title = {Tuberculosis (TB) Chest X-ray Database},
year = {2020},
publisher = {Kaggle},
url = {https://www.kaggle.com/datasets/tawsifurrahman/tuberculosis-tb-chest-xray-dataset}
}
π Contact & Support
Gaston Software Solutions LLP
- Email: info@gss-tec.com
- Website: www.gss-tec.com
- Location: Ntinda, Kampala, Uganda
For technical support, questions, or collaboration opportunities, please contact us via email.
βοΈ License
MIT License
Copyright (c) 2026 Gaston Software Solutions LLP
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Intellectual Property Notice
This Tuberculosis Chest X-Ray RAG Database is provided by Gaston Software Solutions LLP (GSS-LLP) under the MIT License for open-source use.
While the software is open-source and freely available for use, modification, and distribution under the MIT License terms, the intellectual property rights, including the database architecture, processing pipeline, and implementation methodology, remain the property of Gaston Software Solutions LLP.
Key Points:
- β Free to use, modify, and distribute under MIT License
- β Open-source for research and commercial applications
- β No warranty or liability from GSS-LLP
- β οΈ Intellectual property and methodology rights retained by GSS-LLP
- β οΈ Original dataset subject to its respective license
- β οΈ Medical use requires appropriate validation and regulatory compliance
- β οΈ Not approved for clinical diagnosis without proper medical device certification
- β οΈ TB screening requires expert radiologist confirmation
Dataset License
The underlying tuberculosis chest X-ray dataset is sourced from Kaggle and is subject to its respective license. Users must comply with the original dataset license when using this RAG database. Please refer to:
- Tuberculosis TB Chest X-Ray Dataset: https://www.kaggle.com/datasets/tawsifurrahman/tuberculosis-tb-chest-xray-dataset
π About Gaston Software Solutions LLP
Gaston Software Solutions LLP (GSS-LLP) is a technology company based in Ntinda, Kampala, Uganda, specializing in AI/ML solutions, software development, and data science applications for healthcare and other industries.
Our Mission: Leveraging cutting-edge technology to solve real-world problems and improve lives through innovative software solutions.
Healthcare AI Services:
- TB Screening Support Systems
- Medical Image Analysis
- RAG Databases for Healthcare
- Clinical Decision Support Tools
- Public Health AI Solutions
Visit us at www.gss-tec.com or contact info@gss-tec.com for more information.
π Related Databases
This is Part 3 of the Health Imaging RAG Database series:
- Part 1: Pneumonia + Malaria (66,828 images)
- Part 2: Brain Tumor MRI (7,200 images)
- Part 3: Tuberculosis (4,200 images) β You are here
Combined Total: 78,228 medical images across multiple conditions
Last Updated: June 2026
Version: 1.0
Total Images: 4,200
Model: DenseNet-121
Developed by: Gaston Software Solutions LLP
License: MIT
- Downloads last month
- 28