Spaces:
Sleeping
Sleeping
Upload 23 files
Browse filesFiles changed (6)
123456789101112---title: IntelligentHandwrittenCGSemoji: 👀colorFrom: purplecolorTo: indigosdk: gradiosdk_version: 6.13.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104---title: MNIST Handwriting Recognize & Generatesdk: gradioapp_file: app.pypython_version: "3.11"pinned: false---# 智能手写体分析与生成系统(MNIST)本项目实现:- CNN 手写数字识别(MNIST)- 基于遗传算法(GA)的“标签 → 图像”生成(生成结果需被分类器高置信度识别)- 交互式界面:手写输入实时识别 + 选择目标数字一键生成## 1. 环境与安装Python 建议 3.10+。```bashpip install -r requirements.txt```如 `torch/torchvision` 在你的平台上安装失败,请按 PyTorch 官网提示安装与显卡/CPU 适配的版本,然后再执行:```bashpip install -r requirements.txt --no-deps```## 2. 训练分类器(CNN)训练完成后会在 `artifacts/` 下保存:模型权重、训练曲线图、指标 JSON。```bashpython train_classifier.py --epochs 8 --batch-size 128 --lr 0.001```## 3. 遗传算法生成(标签 → 图像)生成结果会在 `artifacts/generated/` 下保存 PNG,并输出目标类别置信度。```bashpython ga_generate.py --target 3 --generations 250 --pop-size 220 --seed 7```## 4. 交互界面(Gradio)```bashpython app.py```启动后打开终端输出的本地地址即可:- 左侧手写输入:实时识别与置信度- 右侧选择目标数字:点击“生成”得到一张对应数字图像,并显示分类器置信度## 4.1 部署(推荐 Docker)注意:在线部署需要确保存在 `artifacts/cnn_mnist.pt`(训练得到的权重)。如果远端环境没有该文件,请先在本地运行训练,再把 `artifacts/cnn_mnist.pt` 一并带上部署。你也可以通过环境变量指定权重位置:`WEIGHTS_PATH=/path/to/cnn_mnist.pt`。### Docker 本地运行```bashdocker build -t mnist-handwriting .docker run --rm -p 7860:7860 mnist-handwriting```浏览器打开:`http://127.0.0.1:7860/`### Windows 没装 Docker 的情况如果终端提示“无法将 docker 识别为命令”,说明你尚未安装/启用 Docker。你有两条路:1) 安装 Docker Desktop(Windows)后再按上面的 Docker 步骤运行。2) 不使用 Docker,直接部署到支持 Gradio 的托管平台(推荐 Hugging Face Spaces):#### 部署到 Hugging Face Spaces(无需 Docker)- 新建 Space,SDK 选择 Gradio- 上传本项目代码(至少包含 `app.py`、`src/`、`requirements.txt`)- 额外上传你的权重文件,并在 Space 的环境变量里设置:`WEIGHTS_PATH=cnn_mnist.pt`- 启动后即可在线访问更详细的 Spaces 部署步骤见:`README_SPACES.md`## 5. 代码结构- `src/handwriting/model.py`:CNN 模型- `src/handwriting/data.py`:MNIST 数据与划分- `src/handwriting/train.py`:训练/评估/曲线保存- `src/handwriting/ga.py`:遗传算法生成- `train_classifier.py`:训练入口- `ga_generate.py`:生成入口- `app.py`:GUI## 6. 报告材料建议(你可以直接引用本仓库输出)- 方法描述:CNN 结构与训练细节;GA 的编码方式、选择/交叉/变异设计与适应度函数- 实验结果:`artifacts/curves.png`,测试集准确率(`artifacts/metrics.json`)- 生成示例:`artifacts/generated/` 下的 PNG- 困难与解决:如 GA 收敛速度、生成图像噪声、分类器校准等
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Hugging Face Spaces 一键部署说明(Gradio)
本项目可直接部署到 Hugging Face Spaces(无需 Docker)。
## 1) 准备权重文件
你需要先在本地训练一次分类器,生成权重文件:
```bashpython train_classifier.py --epochs 8 --batch-size 128```
训练完成后会得到:`artifacts/cnn_mnist.pt`
把它复制/重命名为仓库根目录下的 `cnn_mnist.pt`(推荐这样做,便于 Spaces 直接引用):
```bashcopy artifacts\cnn_mnist.pt cnn_mnist.pt```
## 2) 创建 Space
- New Space- SDK 选择:Gradio- 可见性:按需选择 Public/Private
## 3) 上传文件(最小集合)
至少上传以下内容:
- `app.py`- `requirements.txt`- `src/`(整个目录)- `cnn_mnist.pt`(你本地训练得到的权重)
不要上传:`data/`、`artifacts/`(太大且 Spaces 不需要训练数据)。
## 4) 设置环境变量(可选)
程序会按顺序自动查找权重:`WEIGHTS_PATH` → `cnn_mnist.pt` → `artifacts/cnn_mnist.pt`。
如果你把权重文件放在根目录并命名为 `cnn_mnist.pt`,通常不需要额外设置。
也可以在 Space 的 Variables 里显式设置:
- `WEIGHTS_PATH=cnn_mnist.pt`
如果你把权重放在其他路径,就用 `WEIGHTS_PATH` 指向它。
## 5) 启动验证
Space 构建完成后,直接打开页面即可。
- 左侧:手写输入实时识别(数字+置信度)- 右侧:选择目标数字点击“生成”,得到 GA 生成图与目标置信度27 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646 unmodified lines7172737475767778798081828384858687888990919226 unmodified lines1191201211221231247 unmodified lines13213313413513613713827 unmodified linesclass AppState:def __init__(self) -> None:self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self.weights_path = Path(os.getenv("WEIGHTS_PATH", str(Path("artifacts") / "cnn_mnist.pt")))self.model = Nonedef ensure_model(self):if self.model is not None:returnif not self.weights_path.exists():raise FileNotFoundError(f"未找到模型权重:{self.weights_path}。请先运行:python train_classifier.py")self.model = load_model(weights_path=self.weights_path, device=self.device)STATE = AppState()def classify_drawn(img) -> tuple[str, float]:STATE.ensure_model()if img is None:return "", 0.0if isinstance(img, dict) and "composite" in img:img = img["composite"]if isinstance(img, np.ndarray):pil = Image.fromarray(img)else:pil = imgx = normalize_mnist(to_mnist_tensor(pil).to(STATE.device))label, conf = predict_single(STATE.model, x)return str(label), float(conf)def generate_digit(6 unmodified linescrossover_rate: float,smoothness: float,seed: int,):STATE.ensure_model()result = evolve_digit(model=STATE.model,device=STATE.device,target=int(target),generations=int(generations),pop_size=int(pop_size),elite=int(elite),mutation_rate=float(mutation_rate),mutation_sigma=float(mutation_sigma),crossover_rate=float(crossover_rate),smoothness=float(smoothness),seed=int(seed),)return result.to_pil(), float(result.target_confidence)with gr.Blocks(title="手写数字识别与生成") as demo:26 unmodified linesbtn = gr.Button("生成")gen_img = gr.Image(label="生成结果", height=280, width=280)gen_conf = gr.Number(label="生成图像的目标置信度", precision=4)btn.click(fn=generate_digit,inputs=[7 unmodified linessmoothness,seed,],outputs=[gen_img, gen_conf],)27 unmodified lines2829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495966 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812926 unmodified lines1561571581591601611627 unmodified lines17017117217317417517627 unmodified linesclass AppState:def __init__(self) -> None:self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self.weights_path = self._resolve_weights_path()self.model = Noneself.last_error = ""def _resolve_weights_path(self) -> Path:env = os.getenv("WEIGHTS_PATH")if env:return Path(env)candidates = [Path("cnn_mnist.pt"),Path("artifacts") / "cnn_mnist.pt",]for p in candidates:if p.exists():return preturn candidates[0]def ensure_model(self) -> tuple[bool, str]:if self.model is not None:return True, ""self.weights_path = self._resolve_weights_path()if not self.weights_path.exists():self.last_error = ("未找到模型权重文件。请先本地训练生成 `artifacts/cnn_mnist.pt`,""然后将其放到项目根目录并命名为 `cnn_mnist.pt`,或设置环境变量 WEIGHTS_PATH 指向它。")return False, self.last_errortry:self.model = load_model(weights_path=self.weights_path, device=self.device)self.last_error = ""return True, ""except Exception as e:self.last_error = f"模型加载失败:{type(e).__name__}: {e}"return False, self.last_errorSTATE = AppState()def classify_drawn(img) -> tuple[str, float]:ok, msg = STATE.ensure_model()if not ok:return msg, 0.0if img is None:return "", 0.0try:if isinstance(img, dict):if "composite" in img and img["composite"] is not None:img = img["composite"]elif "layers" in img and img["layers"]:img = img["layers"][-1]elif "image" in img and img["image"] is not None:img = img["image"]if isinstance(img, np.ndarray):pil = Image.fromarray(img)else:pil = imgx = normalize_mnist(to_mnist_tensor(pil).to(STATE.device))label, conf = predict_single(STATE.model, x)return str(label), float(conf)except Exception as e:return f"识别失败:{type(e).__name__}: {e}", 0.0def generate_digit(6 unmodified linescrossover_rate: float,smoothness: float,seed: int,) -> tuple[Image.Image | None, float, str]:ok, msg = STATE.ensure_model()if not ok:return None, 0.0, msgtry:result = evolve_digit(model=STATE.model,device=STATE.device,target=int(target),generations=int(generations),pop_size=int(pop_size),elite=int(elite),mutation_rate=float(mutation_rate),mutation_sigma=float(mutation_sigma),crossover_rate=float(crossover_rate),smoothness=float(smoothness),seed=int(seed),)return result.to_pil(), float(result.target_confidence), ""except Exception as e:return None, 0.0, f"生成失败:{type(e).__name__}: {e}"with gr.Blocks(title="手写数字识别与生成") as demo:26 unmodified linesbtn = gr.Button("生成")gen_img = gr.Image(label="生成结果", height=280, width=280)gen_conf = gr.Number(label="生成图像的目标置信度", precision=4)gen_status = gr.Textbox(label="生成状态")btn.click(fn=generate_digit,inputs=[7 unmodified linessmoothness,seed,],outputs=[gen_img, gen_conf, gen_status],)
README.md+98-6
README_SPACES.mdAdded+55
app.py+74-36
src/__pycache__/__init__.cpython-313.pyc
src/handwriting/__pycache__/__init__.cpython-313.pyc
src/handwriting/__pycache__/runtime.cpython-313.pyc