f
gcw_pCMO8DfP/fairface_age_image_detection
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

FairFace Age 人脸年龄识别 — 昇腾 NPU 版 (ViTForImageClassification)

dima806/fairface_age_image_detection 是基于 google/vit-base-patch16-224-in21k 骨干网, 在 FairFace 数据集上微调的人脸年龄区间分类模型, 输出 9 个年龄区间: 0-2, 3-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, more than 70。

本仓库为 昇腾 Ascend NPU (torch_npu) 适配版, 全流程无 CUDA, 使用 transformers 内置 ViTForImageClassification + AutoImageProcessor 标准加载, 推理结果以 JSON 序列化输出。

环境要求

  • Python 3.10+
  • 昇腾 NPU (Ascend910) + torch_npu 2.9 + CANN
  • 依赖: torch torch_npu transformers fastapi uvicorn python-multipart safetensors pillow numpy

快速开始

# 命令行单图年龄识别
python3 inference.py --img sample_input.png

# 启动 FastAPI 服务 (根路径为上传表单, POST /predict 返回识别 JSON, 默认端口 8112)
python3 inference.py --server --port 8112

命令行参数

参数说明
--img输入图片路径 (必需)
--server启动 FastAPI Web 服务
--port服务端口 (默认 8112)

HTTP API

  • GET / —— HTML 上传表单
  • GET /health —— 健康检查
  • POST /predict —— multipart/form-data 上传字段 file, 返回识别 JSON

输出格式

{
  "model": "dima806/fairface_age_image_detection",
  "device": "npu:0",
  "image": "sample_input.png",
  "image_size": [224, 224],
  "top_class": "20-29",
  "top_class_id": 3,
  "top_score": 0.9875,
  "num_classes": 9,
  "probs": [
    {"label": "0-2", "score": 0.0},
    {"label": "3-9", "score": 0.0},
    {"label": "10-19", "score": 0.0012},
    {"label": "20-29", "score": 0.9875},
    {"label": "30-39", "score": 0.0113},
    {"label": "40-49", "score": 0.0},
    {"label": "50-59", "score": 0.0},
    {"label": "60-69", "score": 0.0},
    {"label": "more than 70", "score": 0.0}
  ],
  "inference_time_s": 0.032
}
  • top_class / top_class_id —— 预测年龄区间及其类别编号
  • probs —— 全部 9 个年龄区间的 softmax 概率
  • inference_time_s —— 单图 NPU 推理耗时 (秒)

模型权重

权重文件 (config.json + preprocessor_config.json + model.safetensors, 约 343MB fp32) 自动从 ai.gitcode.com/hf_mirrors 或 hf-mirror.com 镜像下载, 缓存到 ./model_weights/dima806/fairface_age_image_detection/, 优先复用本地缓存。

项目结构

fairface_age_image_detection/
├── inference.py        # 主推理脚本 (CLI + FastAPI 双模式)
├── sample_input.png    # 示例输入图像 (合成人脸画像)
├── README.md
├── .gitignore
├── model_weights/      # 权重缓存 (symlink 到共享缓存)
└── assets/             # 截图
    ├── agent_workflow.png
    ├── npu_device_call.png
    └── model_result.png

截图

NPU 环境部署与任务启动

agent_workflow

CLI 推理 (device=npu:0)

npu_device_call

FastAPI 返回识别 JSON

model_result