Spaces:
Runtime error
Runtime error
ditobprasetio commited on
Commit ·
fa2a7b2
1
Parent(s): 8ffceae
add application files
Browse filesFiles changed (2)
- app.pyAdded+75
- requirements.txtAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import torchimport torch.nn.functional as Fimport torchvision.transforms as transformsimport numpy as npimport gradio as grfrom torch import nnfrom gradio import componentsfrom PIL import Image
class BrainTumorClassifier(nn.Module): def __init__(self, num_classes): super(BrainTumorClassifier, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 20, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(20, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2, 2) ) self.classifier = nn.Sequential( nn.Linear(32 * 56 * 56, 128), # Adjust input size based on image size nn.ReLU(), nn.Linear(128, num_classes) )
def forward(self, x): x = self.features(x) x = x.view(-1, 32 * 56 * 56) x = self.classifier(x) return x def predict(image): image = Image.fromarray(np.uint8(image)).convert('RGB') ## give the weights trained model_path = 'cnn_tumorbrain_classifier_self.pth' model_load = BrainTumorClassifier(4) model_load.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
## put the model in evaluation mode model_load.eval()
transform_pipeline = transforms.Compose([ transforms.Resize((224,224)), transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)) ])
## transform the img like the training image input_img = transform_pipeline(image).unsqueeze(0) # input_img
## define the label by index class_to_label = {0: 'glioma', 1: 'meningioma', 2: 'notumor', 3: 'pituitary'}
## run the model with torch.no_grad(): output = model_load(input_img)
## convert to the softmax for getting percent each label probabilities = F.softmax(output, dim=1)
## get predicted label with highest value _, predicted_label = torch.max(probabilities,1) # confidence_percent = probabilities[0].tolist()[predicted_label.item()] conf, _ = torch.max(probabilities, 1)
result = "{}, with confidence level in {}%".format(class_to_label[predicted_label.item()], conf.item()*100) return result
iface = gr.Interface(fn=predict, inputs=gr.Image(), outputs="textbox")
iface.launch(share=True)123torchtorchvisionnumpyapp.pyAdded+75
requirements.txtAdded+3