vit-age-classifier 是基于 Google ViT-Base-Patch16-224 的年龄分类模型,能够对输入的人脸图像进行年龄范围分类。模型将图像分类为 9 个年龄组:0-2、3-9、10-19、20-29、30-39、40-49、50-59、60-69、70+。
vit-age-classifier-ascend/
├── inference.py # 推理测试脚本
├── log.txt # 测试日志
├── README.md # 本文档
├── test_image.png # 测试图像
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果docker exec -it test-modelagent bashsource /usr/local/Ascend/ascend-toolkit/set_env.sh模型文件位于 /data/ysws/agentsp/5-16/vit-age-classifier/ 目录下:
pip install transformers torch_npu pillow numpy -i https://pypi.huaweicloud.com/repository/pypi/simple/Run the inference script for age classification:
cd /data/ysws/agentsp/5-16/vit-age-classifier-ascend/
python3 inference.py
python3 inference.py --mode inferenceRun the accuracy comparison test:
cd /data/ysws/agentsp/5-16/vit-age-classifier-ascend/
python3 inference.py --mode precision_test| 参数 | 说明 | 默认值 |
|---|---|---|
--mode | 测试模式: all, inference 或 precision_test | all |
| 指标 | 实测值 | 阈值 | 状态 |
|---|---|---|---|
| 最大相对误差 | 0.2793% | < 1.00% | PASS |
| CPU 推理时间 | 1.683s | - | - |
| NPU 推理时间 | 0.014s | - | - |
| 加速比 | 121.20x | > 1x | PASS |
输入: 224x224 RGB 人脸图像
输出:
| 年龄组 | ID |
|---|---|
| 0-2 | 0 |
| 3-9 | 1 |
| 10-19 | 2 |
| 20-29 | 3 |
| 30-39 | 4 |
| 40-49 | 5 |
| 50-59 | 6 |
| 60-69 | 7 |
| 70+ | 8 |
ViT Age Classifier NPU Test
Model: google/vit-base-patch16-224-in21k (age classification)
Output: /data/ysws/agentsp/5-16/vit-age-classifier-ascend
============================================================
Inference Test (NPU)
============================================================
Device: npu:0
Loading model and processor...
Model loaded successfully
Input shape: torch.Size([1, 3, 224, 224])
Inference time: 5.470s
Predicted class: 3 (20-29)
Logits shape: torch.Size([1, 9])
============================================================
Precision Test (CPU vs NPU)
============================================================
NPU Device: npu:0
Loading model...
Input shape: torch.Size([1, 3, 224, 224])
Running on CPU...
Running on NPU...
CPU inference time: 1.683s
NPU inference time: 0.014s
Speedup: 121.20x
Max absolute error: 3.722869e-03
Max relative error: 0.2793% (threshold: 1.0%)
Status: PASS
============================================================
Precision Test Result: PASS
============================================================
============================================================
Test Complete!
============================================================import torch
from PIL import Image
from transformers import ViTForImageClassification, AutoImageProcessor
MODEL_DIR = "/data/ysws/agentsp/5-16/vit-age-classifier"
processor = AutoImageProcessor.from_pretrained(MODEL_DIR)
model = ViTForImageClassification.from_pretrained(MODEL_DIR)
model = model.to("npu:0").eval()
image = Image.open("face.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt")
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class = logits.argmax(-1).item()
predicted_label = model.config.id2label[str(predicted_class)]
print(f"Predicted: {predicted_label}")import numpy as np
array = np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)
image = Image.fromarray(array)
inputs = processor(images=image, return_tensors="pt")| 组件 | 说明 |
|---|---|
| embeddings | 补丁嵌入 + CLS标记 |
| encoder | 12层Transformer编码器 |
| layernorm | 层归一化 |
| classifier | 线性分类头 (768 -> 9) |
从 config.json 提取的关键参数:
{
"hidden_size": 768,
"intermediate_size": 3072,
"num_attention_heads": 12,
"num_hidden_layers": 12,
"patch_size": 16,
"image_size": 224,
"num_channels": 3
}A: 检查 NPU 驱动是否正确安装。ViT 模型在 CPU 和 NPU 上的数值误差极小(< 0.3%),远低于 1% 阈值。
A: 首次推理会有编译开销。NPU 相比 CPU 有显著加速(121x),适合批量处理场景。
A: 支持 PIL、numpy array、torch tensor 等常见格式。输入图像会自动 resize 到 224x224 并 normalize。
A: 修改 inputs 格式即可:
images = [Image.open(f) for f in image_files]
inputs = processor(images=images, return_tensors="pt")本项目遵循 Apache-2.0 许可证