Tanusree88 commited on
Commit
7e5db72
·
verified ·
1 Parent(s): b856b08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -5
app.py CHANGED
@@ -1,11 +1,94 @@
1
- import zipfile
2
  import os
 
 
 
 
 
 
 
 
3
 
 
4
  def extract_zip(zip_file, extract_to):
5
  with zipfile.ZipFile(zip_file, 'r') as zip_ref:
6
  zip_ref.extractall(extract_to)
7
 
8
- # Example usage
9
- zip_file_path = 'https://huggingface.co/spaces/Tanusree88/ViT-MRI-FineTuning/resolve/main/MS.zip'
10
- extract_to = 'https://huggingface.co/spaces/Tanusree88/ViT-MRI-FineTuning/resolve/main/extracttedfiles'
11
- extract_zip(zip_file_path, extract_to)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import zipfile
3
+ import numpy as np
4
+ import torch
5
+ from transformers import ViTForImageClassification, AdamW
6
+ import nibabel as nib
7
+ from PIL import Image
8
+ from torch.utils.data import Dataset, DataLoader
9
+ import streamlit as st
10
 
11
+ # 1. Function to extract zip files
12
  def extract_zip(zip_file, extract_to):
13
  with zipfile.ZipFile(zip_file, 'r') as zip_ref:
14
  zip_ref.extractall(extract_to)
15
 
16
+ # 2. Preprocess images
17
+ def preprocess_image(image_path):
18
+ ext = os.path.splitext(image_path)[-1].lower()
19
+
20
+ if ext == '.nii' or ext == '.nii.gz':
21
+ nii_image = nib.load(image_path)
22
+ image_data = nii_image.get_fdata()
23
+ image_tensor = torch.tensor(image_data).float()
24
+ if len(image_tensor.shape) == 3:
25
+ image_tensor = image_tensor.unsqueeze(0)
26
+
27
+ elif ext in ['.jpg', '.jpeg']:
28
+ img = Image.open(image_path).convert('RGB').resize((224, 224))
29
+ img_np = np.array(img)
30
+ image_tensor = torch.tensor(img_np).permute(2, 0, 1).float()
31
+
32
+ else:
33
+ raise ValueError(f"Unsupported format: {ext}")
34
+
35
+ image_tensor /= 255.0 # Normalize to [0, 1]
36
+ return image_tensor
37
+
38
+ # 3. Label images
39
+ def prepare_dataset(extracted_folder):
40
+ image_paths = []
41
+ labels = []
42
+ for disease_folder in ['alzheimers', 'parkinsons', 'ms']:
43
+ folder_path = os.path.join(extracted_folder, disease_folder)
44
+ label = {'alzheimers': 0, 'parkinsons': 1, 'ms': 2}[disease_folder]
45
+ for img_file in os.listdir(folder_path):
46
+ if img_file.endswith(('.nii', '.jpg', '.jpeg')):
47
+ image_paths.append(os.path.join(folder_path, img_file))
48
+ labels.append(label)
49
+ return image_paths, labels
50
+
51
+ # 4. Custom Dataset
52
+ class CustomImageDataset(Dataset):
53
+ def __init__(self, image_paths, labels):
54
+ self.image_paths = image_paths
55
+ self.labels = labels
56
+
57
+ def __len__(self):
58
+ return len(self.image_paths)
59
+
60
+ def __getitem__(self, idx):
61
+ image = preprocess_image(self.image_paths[idx])
62
+ label = self.labels[idx]
63
+ return image, label
64
+
65
+ # 5. Training function
66
+ def fine_tune_model(train_loader):
67
+ model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224-in21k', num_labels=3)
68
+ model.train()
69
+ optimizer = AdamW(model.parameters(), lr=1e-4)
70
+ criterion = torch.nn.CrossEntropyLoss()
71
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
72
+ model.to(device)
73
+ for epoch in range(10):
74
+ running_loss = 0.0
75
+ for images, labels in train_loader:
76
+ images, labels = images.to(device), labels.to(device)
77
+ optimizer.zero_grad()
78
+ outputs = model(pixel_values=images).logits
79
+ loss = criterion(outputs, labels)
80
+ loss.backward()
81
+ optimizer.step()
82
+ running_loss += loss.item()
83
+ return running_loss / len(train_loader)
84
+
85
+ # Streamlit UI
86
+ st.title("Fine-tune ViT on MRI Scans")
87
+
88
+ if st.button("Start Training"):
89
+ extract_zip('your_zip_file.zip', 'extracted_folder/')
90
+ image_paths, labels = prepare_dataset('extracted_folder/')
91
+ dataset = CustomImageDataset(image_paths, labels)
92
+ train_loader = DataLoader(dataset, batch_size=32, shuffle=True)
93
+ final_loss = fine_tune_model(train_loader)
94
+ st.write(f"Training Complete with Final Loss: {final_loss}")