mochuan zhan commited on
Commit
78245fb
·
1 Parent(s): a121f59

Initial commit from desktop

Browse files
Files changed (3) hide show
  1. app.py +122 -0
  2. requirements.txt +4 -0
  3. vit_model.pth +3 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ from PIL import Image
5
+ import torch.nn as nn
6
+
7
+ # 如果你的模型结构与标准的torchvision模型不同,请确保在此处定义或导入你的模型结构
8
+ # 例如,如果你有一个model.py文件:
9
+ # from model import ViTModel
10
+
11
+ # 示例:定义一个简单的ViT模型结构(请根据你的实际模型调整)
12
+ class ViT(nn.Module):
13
+ def __init__(self, image_size=28, patch_size=7, num_classes=10, dim=128, depth=6, heads=8, mlp_dim=256, dropout=0.1):
14
+ super(ViT, self).__init__()
15
+
16
+ assert image_size % patch_size == 0, 'image dimensions must be divisible by the patch size'
17
+ num_patches = (image_size // patch_size) ** 2
18
+ patch_dim = 1 * patch_size ** 2
19
+
20
+ # 定义线性层将图像分块并映射到嵌入空间
21
+ self.patch_embedding = nn.Linear(patch_dim, dim)
22
+
23
+ # 位置编码
24
+ # nn.Parameter是Pytorch中的一个类,用于将一个张量注册为模型的参数
25
+ self.pos_embedding = nn.Parameter(torch.randn(1, num_patches, dim))
26
+
27
+ # Dropout层
28
+ self.dropout = nn.Dropout(dropout)
29
+
30
+ # Transformer编码器
31
+ # 当 batch_first=True 时,输入和输出张量的形状为 (batch_size, seq_length, feature_dim)。当 batch_first=False 时,输入和输出张量的形状为 (seq_length, batch_size, feature_dim)。
32
+ self.transformer = nn.TransformerEncoder(
33
+ nn.TransformerEncoderLayer(
34
+ d_model=dim,
35
+ nhead=heads,
36
+ dim_feedforward=mlp_dim
37
+ # batch_first=True
38
+ ),
39
+ num_layers=depth
40
+ )
41
+
42
+ # 分类头
43
+ # nn.Identity()是一个空的层,它不执行任何操作,只是返回输入
44
+ # self.to_cls_token = nn.Identity()
45
+ # self.mlp_head = nn.Linear(dim, num_classes)
46
+ self.mlp_head = nn.Sequential(
47
+ nn.LayerNorm(dim),
48
+ nn.Linear(dim, num_classes)
49
+ )
50
+
51
+ def forward(self, x):
52
+ # x shape: [batch_size, 1, 28, 28]
53
+ batch_size = x.size(0)
54
+ x = x.view(batch_size, -1, 7*7) # 将图像划分为7x7的Patch
55
+ x = self.patch_embedding(x) # [batch_size, num_patches, dim]
56
+ x += self.pos_embedding # 添加位置编码
57
+ x = self.dropout(x) # 应用Dropout
58
+
59
+ x = x.permute(1, 0, 2) # Transformer期望的输入形状:[seq_len, batch_size, embedding_dim]
60
+ x = self.transformer(x) # [序列长度, batch_size, dim]
61
+ x = x.permute(1, 0, 2) # 转回原来的形状:[batch_size, seq_len, dim]
62
+
63
+ x = x.mean(dim=1) # 对所有Patch取平均,x.mean(dim=1) 这一步是对所有 Patch 的特征向量取平均值,从而得到一个代表整个图像的全局特征向量。
64
+ x = self.mlp_head(x) # [batch_size, num_classes]
65
+ return x
66
+
67
+ # 加载模型
68
+ model = ViT(num_classes=10) # 确保num_classes与你的MNIST任务一致
69
+ model_path = "vit_mnist.pth" # 模型权重文件名
70
+ model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
71
+ model.eval()
72
+
73
+ # 定义图像预处理
74
+ transform = transforms.Compose([
75
+ transforms.Resize((224, 224)), # 适应ViT的输入大小
76
+ transforms.ToTensor(),
77
+ transforms.Normalize((0.5,), (0.5,)) # 根据训练时的归一化参数调整
78
+ ])
79
+
80
+ # 定义预测函数
81
+ def classify_image(image):
82
+ # 如果输入是灰度图,将其转换为RGB
83
+ if image.mode != "RGB":
84
+ image = image.convert("RGB")
85
+
86
+ # 预处理图像
87
+ img = transform(image).unsqueeze(0) # 添加批次维度
88
+
89
+ # 模型预测
90
+ with torch.no_grad():
91
+ outputs = model(img)
92
+
93
+ # 获取预测结果
94
+ _, predicted = torch.max(outputs, 1)
95
+ return str(predicted.item())
96
+
97
+ # # 创建Gradio界面
98
+ # iface = gr.Interface(
99
+ # fn=classify_image,
100
+ # inputs=gr.Image(shape=(28, 28), image_mode='L', source="upload", tool="editor"),
101
+ # outputs=gr.Label(num_top_classes=1),
102
+ # title="MNIST Classification with ViT",
103
+ # description="上传一张28x28的灰度图像,模型将预测其所属的数字类别。"
104
+ # )
105
+
106
+ iface = gr.Interface(
107
+ fn=classify_image,
108
+ inputs=gr.Image(
109
+ source="canvas",
110
+ tool="editor",
111
+ type="pil",
112
+ invert_colors=True,
113
+ shape=(224, 224),
114
+ image_mode="L",
115
+ label="Draw a digit"
116
+ ),
117
+ outputs=gr.Label(num_top_classes=1),
118
+ title="MNIST Digit Classification with ViT",
119
+ description="使用鼠标手绘一个数字,模型将预测其所属的类别。"
120
+ )
121
+
122
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ gradio
4
+ Pillow
vit_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:223c6c32c2a9d4c274b09c35ef089b358ee7cf1729b9d939fca898db5765dcdb
3
+ size 3248655