File size: 5,859 Bytes
d78c654
 
 
aa38e7b
d78c654
 
aa38e7b
 
 
 
d78c654
aa38e7b
d805a43
9e31797
2150cff
cab28de
 
aa38e7b
 
 
 
 
 
9e31797
aa38e7b
 
 
 
 
 
 
cab28de
aa38e7b
d805a43
d6e633e
aa38e7b
9e31797
aa38e7b
 
 
0f252cc
2bfd5ec
aa38e7b
d805a43
d78c654
 
aa38e7b
 
 
 
 
 
 
 
d78c654
 
 
aa38e7b
 
 
 
 
d78c654
aa38e7b
d78c654
aa38e7b
23b76e8
aa38e7b
 
 
 
23b76e8
aa38e7b
 
 
 
23b76e8
d78c654
 
 
 
 
 
 
 
 
 
 
 
aa38e7b
d78c654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3527aa
 
 
 
 
 
 
 
d78c654
 
2150cff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d78c654
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
---
license: mit
---

# Conditional Diffusion Model for Medical Image Generation

This repository contains a conditional diffusion model trained to generate **3D medical CT scan images** based on segmentation masks.  
The model uses a **U-Net architecture with score-based diffusion** for high-quality medical image synthesis.

---

## Real or Fake Image?

<p>
  <img src="assets/real_fake.png" alt="Sample real vs fake medical CT" width="600"/>
</p>

---

## Training Dataset

The model was trained on **3,346 CT scan examples** with corresponding segmentation masks (80/20 train–validation split).  

<p>
  <img src="assets/dataset.png" alt="Sample dataset" width="600"/>
</p>

**Sources:**
1. [Kaggle Pancreas CT](https://www.kaggle.com/datasets/salihayesilyurt/pancreas-ct)  
2. [Cancer Imaging Archive Pancreatic CT](https://nbia.cancerimagingarchive.net/nbia-search/)  
3. [Annotated Medical Image Dataset for Segmentation Algorithms](https://drive.google.com/drive/folders/1HqEgzS8BV2c7xYNrZdEAnrHk7osJJ--2)

---

## <a href="https://archietan.com/synthetic-ct-demo" style="color:blue; text-decoration:underline;">Live Interactive Demo</a>

<p>
  <a href="https://archietan.com/synthetic-ct-demo">
    <img src="assets/livedemo.png" alt="Sample input and output" width="600"/>
  </a>
</p>

---

## Model Architecture

- **Base Model**: U-Net with 5-level encoder–decoder  
- **Input**: 4-channel 256×256 CT scan images  
- **Conditioning**: Segmentation masks (4-channel 256×256)  
- **Output**: 4-channel 256×256 generated images  
- **Sampling**: Euler–Maruyama sampler (250 steps)  
- **Training**: Score matching loss with conditional generation  

---

## Model Details

- **Training Data**: 3,346 CT scan examples  
- **Lambda Parameter**: 25.0 (diffusion coefficient)  
- **Embedding Dimension**: 256  
- **Channels**: [32, 64, 128, 256, 512]  
- **Activation**: SiLU (Swish)  

---

## Usage

This model can be used to **add more diversity to your CT-scan dataset**, especially when:
- You have a **limited dataset size** (e.g., only a few hundred scans).  
- You want to **balance underrepresented anatomical variations** or rare conditions.  
- You need **synthetic augmentation** for training deep learning models in segmentation, detection, or classification.  

**Example Applications**
- Generate training samples from segmentation masks to **reduce overfitting**.  
- Create synthetic CT images with controlled variations to **test robustness**.  
- Improve representation of minority cases to **reduce bias in medical AI**.  

### Using the Hugging Face API

```python
from transformers import AutoModelForImageGeneration
import torch

# Load the model
model = AutoModelForImageGeneration.from_pretrained("your-username/your-model-name")

# Generate images
conditioning_mask = torch.randn(1, 4, 256, 256)  # Your segmentation mask
generated_image = model.generate(conditioning_mask)


### Local Usage

```python
import torch
from model import UNet, marginal_prob_std, diffusion_coeff, Euler_Maruyama_sampler

# Load model
Lambda = 25.0
marginal_prob_std_fn = lambda t: marginal_prob_std(t, Lambda=Lambda, device='cuda')
score_model = UNet(marginal_prob_std=marginal_prob_std_fn)
score_model.load_state_dict(torch.load("ckpt_3D_v2.pth"))
score_model.eval()

# Generate sample
conditioning_mask = torch.randn(1, 4, 256, 256)
samples = Euler_Maruyama_sampler(
    score_model,
    marginal_prob_std_fn,
    lambda t: diffusion_coeff(t, Lambda=Lambda, device='cuda'),
    batch_size=1,
    x_shape=(4, 256, 256),
    num_steps=250,
    device='cuda',
    y=conditioning_mask
)
```

## Training

The model was trained for 5000 epochs with:
- Learning rate: 2e-4 (with decay)
- Batch size: 1
- Optimizer: Adam
- Loss: Score matching loss

## Citation

If you use this model in your research, please cite:

```bibtex
@misc{conditional_diffusion_medical,
  title={Conditional Diffusion Model for Medical Image Generation},
  author={Archie Tan, Scott, Spurlock},
  year={2025},
  url={https://huggingface.co/tan200224}
}
```

## Publications

- **Archie Tan, Scott Spurlock.**  
  *Learning to generate realistic medical images to improve pancreatic cancer segmentation.*  
  Accepted for presentation at the [39th Annual Consortium for Computing Sciences in Colleges: Southeastern Conference (CCSC-SE 2025)](http://ccscse.org/), Mercer University, Macon, GA, November 7–8, 2025.  
  Published in the *Journal of the Consortium for Computing Sciences in Colleges* (to appear).  
  [Conference Site](https://www.conftool.org/ccsc-se/) | [Formatting Guidelines](https://lubaochuan.github.io/ccsc-editor/authors.html)

## License

This project is open-source under the MIT License.  

Copyright (c) 2025 Archie Tan, Scott Spurlock  

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.


## Contact

For questions or issues, please open an issue on this repository.