import torch from torch import nn import torch.nn.functional as F from torchvision.transforms import ToTensor # Define model class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(1, 32, kernel_size=5) self.conv2 = nn.Conv2d(32, 32, kernel_size=5) self.conv3 = nn.Conv2d(32,64, kernel_size=5) self.fc1 = nn.Linear(3*3*64, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): x = F.relu(self.conv1(x)) #x = F.dropout(x, p=0.5, training=self.training) x = F.relu(F.max_pool2d(self.conv2(x), 2)) x = F.dropout(x, p=0.5, training=self.training) x = F.relu(F.max_pool2d(self.conv3(x),2)) x = F.dropout(x, p=0.5, training=self.training) x = x.view(-1,3*3*64 ) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) logits = self.fc2(x) return logits model = ConvNet() model.load_state_dict( torch.load("weights/mnist_convnet_model.pth", map_location=torch.device('cpu')) ) model.eval() import gradio as gr from torchvision import transforms def predict(image): tsr_image = transforms.ToTensor()(image) with torch.no_grad(): pred = model(tsr_image) prob = torch.nn.functional.softmax(pred[0], dim=0) confidences = {i: float(prob[i]) for i in range(10)} return confidences with gr.Blocks(css=".gradio-container {background:honeydew;}", title="MNIST 分類器" ) as demo: gr.HTML("""