Upload 11 files
Browse files- .gitattributes +1 -0
- Tumor.py +97 -0
- brain_tumor_resnet18.pth +3 -0
- img.png +3 -0
- img_1.png +0 -0
- img_2.png +0 -0
- img_3.png +0 -0
- img_4.png +0 -0
- img_5.png +0 -0
- img_6.png +0 -0
- img_7.png +0 -0
- tumor_test.py +44 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
img.png filter=lfs diff=lfs merge=lfs -text
|
Tumor.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
import torchvision.models as models
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
|
| 9 |
+
# Device setup
|
| 10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
|
| 12 |
+
# Load dataset
|
| 13 |
+
ds = load_dataset("sartajbhuvaji/Brain-Tumor-Classification")
|
| 14 |
+
train_ds = ds["Training"]
|
| 15 |
+
test_ds = ds["Testing"]
|
| 16 |
+
|
| 17 |
+
# Data augmentation for training
|
| 18 |
+
train_transform = transforms.Compose([
|
| 19 |
+
transforms.Resize((224, 224)),
|
| 20 |
+
transforms.RandomHorizontalFlip(),
|
| 21 |
+
transforms.RandomRotation(15),
|
| 22 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2),
|
| 23 |
+
transforms.ToTensor(),
|
| 24 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 25 |
+
])
|
| 26 |
+
# Simpler transform for testing
|
| 27 |
+
test_transform = transforms.Compose([
|
| 28 |
+
transforms.Resize((224, 224)),
|
| 29 |
+
transforms.ToTensor(),
|
| 30 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 31 |
+
])
|
| 32 |
+
|
| 33 |
+
# Custom Dataset to wrap Hugging Face dataset for PyTorch usage
|
| 34 |
+
class HFToTorchDataset(Dataset):
|
| 35 |
+
def __init__(self, hf_ds, transform=None):
|
| 36 |
+
self.hf_ds = hf_ds
|
| 37 |
+
self.transform = transform
|
| 38 |
+
def __len__(self):
|
| 39 |
+
return len(self.hf_ds)
|
| 40 |
+
def __getitem__(self, idx):
|
| 41 |
+
image = self.hf_ds[idx]["image"].convert("RGB")
|
| 42 |
+
label = self.hf_ds[idx]["label"]
|
| 43 |
+
if self.transform:
|
| 44 |
+
image = self.transform(image)
|
| 45 |
+
return image, label
|
| 46 |
+
|
| 47 |
+
torch_train = HFToTorchDataset(train_ds, train_transform)
|
| 48 |
+
torch_test = HFToTorchDataset(test_ds, test_transform)
|
| 49 |
+
|
| 50 |
+
train_loader = DataLoader(torch_train, batch_size=32, shuffle=True)
|
| 51 |
+
test_loader = DataLoader(torch_test, batch_size=32, shuffle=False)
|
| 52 |
+
|
| 53 |
+
# Load pretrained ResNet18 and adjust for 4 classes
|
| 54 |
+
model = models.resnet18(weights="IMAGENET1K_V1")
|
| 55 |
+
num_ftrs = model.fc.in_features
|
| 56 |
+
model.fc = nn.Linear(num_ftrs, 4)
|
| 57 |
+
model = model.to(device)
|
| 58 |
+
|
| 59 |
+
# Loss and optimizer
|
| 60 |
+
criterion = nn.CrossEntropyLoss()
|
| 61 |
+
optimizer = optim.Adam(model.parameters(), lr=0.0005)
|
| 62 |
+
|
| 63 |
+
# Train!
|
| 64 |
+
num_epochs = 10 # Increase for even better results
|
| 65 |
+
for epoch in range(num_epochs):
|
| 66 |
+
model.train()
|
| 67 |
+
running_loss = 0.0
|
| 68 |
+
correct = total = 0
|
| 69 |
+
for images, labels in train_loader:
|
| 70 |
+
images, labels = images.to(device), labels.to(device)
|
| 71 |
+
optimizer.zero_grad()
|
| 72 |
+
outputs = model(images)
|
| 73 |
+
loss = criterion(outputs, labels)
|
| 74 |
+
loss.backward()
|
| 75 |
+
optimizer.step()
|
| 76 |
+
running_loss += loss.item() * images.size(0)
|
| 77 |
+
_, preds = torch.max(outputs, 1)
|
| 78 |
+
correct += (preds == labels).sum().item()
|
| 79 |
+
total += labels.size(0)
|
| 80 |
+
epoch_loss = running_loss / total
|
| 81 |
+
accuracy = correct / total
|
| 82 |
+
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}, Accuracy: {accuracy:.4f}")
|
| 83 |
+
|
| 84 |
+
# Test accuracy
|
| 85 |
+
model.eval()
|
| 86 |
+
correct = total = 0
|
| 87 |
+
with torch.no_grad():
|
| 88 |
+
for images, labels in test_loader:
|
| 89 |
+
images, labels = images.to(device), labels.to(device)
|
| 90 |
+
outputs = model(images)
|
| 91 |
+
_, preds = torch.max(outputs, 1)
|
| 92 |
+
correct += (preds == labels).sum().item()
|
| 93 |
+
total += labels.size(0)
|
| 94 |
+
print(f"Test Accuracy: {correct / total:.4f} ({correct}/{total})")
|
| 95 |
+
|
| 96 |
+
torch.save(model.state_dict(), "brain_tumor_resnet18.pth")
|
| 97 |
+
print("Model weights saved to brain_tumor_resnet18.pth")
|
brain_tumor_resnet18.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebd3aabb2861ddee9dd99f3e1adec967876137c41b8c529b57ce14c252ab64cf
|
| 3 |
+
size 44793419
|
img.png
ADDED
|
Git LFS Details
|
img_1.png
ADDED
|
img_2.png
ADDED
|
img_3.png
ADDED
|
img_4.png
ADDED
|
img_5.png
ADDED
|
img_6.png
ADDED
|
img_7.png
ADDED
|
tumor_test.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torchvision import transforms, models
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
# Device setup
|
| 7 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 8 |
+
|
| 9 |
+
# Transform (must match training on ResNet18/224 RGB)
|
| 10 |
+
transform = transforms.Compose([
|
| 11 |
+
transforms.Resize((224, 224)),
|
| 12 |
+
transforms.ToTensor(),
|
| 13 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 14 |
+
[0.229, 0.224, 0.225])
|
| 15 |
+
])
|
| 16 |
+
|
| 17 |
+
# Label map (matches Hugging Face dataset)
|
| 18 |
+
label_map = {
|
| 19 |
+
0: "glioma",
|
| 20 |
+
1: "meningioma",
|
| 21 |
+
2: "no_tumor",
|
| 22 |
+
3: "pituitary"
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
# ResNet18 model (final layer for 4 classes)
|
| 26 |
+
model = models.resnet18(weights=None)
|
| 27 |
+
num_ftrs = model.fc.in_features
|
| 28 |
+
model.fc = nn.Linear(num_ftrs, 4)
|
| 29 |
+
model = model.to(device)
|
| 30 |
+
model.load_state_dict(torch.load("brain_tumor_resnet18.pth", map_location=device))
|
| 31 |
+
model.eval()
|
| 32 |
+
|
| 33 |
+
# Predict function
|
| 34 |
+
def predict_image(image_path):
|
| 35 |
+
img = Image.open(image_path).convert('RGB')
|
| 36 |
+
img = transform(img).unsqueeze(0).to(device) # batch size 1
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
outputs = model(img)
|
| 39 |
+
_, pred_idx = torch.max(outputs, 1)
|
| 40 |
+
pred_label = label_map[pred_idx.item()]
|
| 41 |
+
print(f"Prediction: {pred_label}")
|
| 42 |
+
|
| 43 |
+
# Example usage:
|
| 44 |
+
predict_image("D:\\python\\Advanced_tumor\\img_3.png") # Replace with your image
|