yexuefeng commited on
Commit ·
b3db6b5
1
Parent(s): 1896dd6
add some debug information
Browse files
app.py
CHANGED
|
@@ -3,35 +3,6 @@ import gradio as gr
|
|
| 3 |
import torch
|
| 4 |
import torch.nn.functional as F
|
| 5 |
|
| 6 |
-
# path = untar_data(URLs.MNIST)
|
| 7 |
-
# def conv(ni, nf, ks=3, act=True):
|
| 8 |
-
# layers = [nn.Conv2d(ni, nf, stride=2, kernel_size=ks, padding=ks//2)]
|
| 9 |
-
# if act: layers.append(nn.ReLU())
|
| 10 |
-
# layers.append(nn.BatchNorm2d(nf))
|
| 11 |
-
# return nn.Sequential(*layers)
|
| 12 |
-
|
| 13 |
-
# def simple_cnn():
|
| 14 |
-
# return sequential(
|
| 15 |
-
# conv(1 ,8, ks=5), #14x14
|
| 16 |
-
# conv(8 ,16), #7x7
|
| 17 |
-
# conv(16,32), #4x4
|
| 18 |
-
# conv(32,64), #2x2
|
| 19 |
-
# conv(64,10, act=False), #1x1
|
| 20 |
-
# Flatten(),
|
| 21 |
-
# )
|
| 22 |
-
# def get_dls(bs=64):
|
| 23 |
-
# return DataBlock(
|
| 24 |
-
# blocks=(ImageBlock(cls=PILImageBW), CategoryBlock),
|
| 25 |
-
# get_items=get_image_files,
|
| 26 |
-
# splitter=GrandparentSplitter('training','testing'),
|
| 27 |
-
# get_y=parent_label,
|
| 28 |
-
# batch_tfms=Normalize()
|
| 29 |
-
# ).dataloaders(path, bs=bs)
|
| 30 |
-
|
| 31 |
-
# dls = get_dls()
|
| 32 |
-
# learn = Learner(dls, simple_cnn(), loss_func=F.cross_entropy,
|
| 33 |
-
# metrics=accuracy, cbs=ActivationStats(with_hist=True))
|
| 34 |
-
|
| 35 |
|
| 36 |
learn = load_learner("export_new.pkl")
|
| 37 |
# 用模型的 vocab 生成中文标签
|
|
@@ -44,8 +15,14 @@ def classify_image(img):
|
|
| 44 |
img = img.convert('L') # 转换为灰度图
|
| 45 |
img = img.resize((28, 28))
|
| 46 |
img = PILImage.create(img)
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
# 手动归一化
|
| 50 |
if not torch.is_tensor(probs):
|
| 51 |
probs = torch.tensor(probs)
|
|
|
|
| 3 |
import torch
|
| 4 |
import torch.nn.functional as F
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
learn = load_learner("export_new.pkl")
|
| 8 |
# 用模型的 vocab 生成中文标签
|
|
|
|
| 15 |
img = img.convert('L') # 转换为灰度图
|
| 16 |
img = img.resize((28, 28))
|
| 17 |
img = PILImage.create(img)
|
| 18 |
+
try:
|
| 19 |
+
pred, idx, probs = learn.predict(img)
|
| 20 |
+
print(f"预测类别: {pred}")
|
| 21 |
+
print(f"类别索引: {idx}")
|
| 22 |
+
print(f"概率分布: {probs}")
|
| 23 |
+
except IndexError as e:
|
| 24 |
+
print(f"错误: {e}")
|
| 25 |
+
print("检查模型的 vocab 是否匹配:", learn.dls.vocab)
|
| 26 |
# 手动归一化
|
| 27 |
if not torch.is_tensor(probs):
|
| 28 |
probs = torch.tensor(probs)
|