那个痣危险吗?使用 WebGPU 和 EfficientNetV2 构建实时皮肤病变分类器 🚀

发布: (2026年1月28日 GMT+8 09:00)
6 分钟阅读
原文: Dev.to

I’m happy to translate the article for you, but I’ll need the text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source line and all formatting exactly as you requested.

介绍

Healthcare is moving to the edge. Imagine being able to screen a suspicious skin lesion directly in your browser with the privacy of local execution and the speed of a native app. Thanks to the WebGPU API and TensorFlow.js, we can now run heavy‑duty computer vision models like EfficientNetV2 with unprecedented performance.

In this tutorial we’ll dive deep into building a high‑performance Edge AI application for skin lesion classification. We will leverage WebGPU for hardware‑accelerated inference, ensuring that sensitive health data never leaves the user’s device. If you’ve been looking to master computer vision in the browser or want to see how the next generation of web graphics APIs can be used for deep learning, you’re in the right place! 💻🥑

数据流图

graph TD
    A[User Camera Stream] --> B[React Canvas Wrapper]
    B --> C{WebGPU Supported?}
    C -- Yes --> D[TF.js WebGPU Backend]
    C -- No --> E[TF.js WebGL/CPU Fallback]
    D --> F[EfficientNetV2 Inference]
    F --> G[Probability Distribution]
    G --> H[Medical Priority Assessment]
    H --> I[UI Alert/Recommendation]

先决条件

  • 前端结构使用 React 18+。
  • 使用带有 WebGPU 扩展的 TensorFlow.js(@tensorflow/tfjs)。
  • 已微调的 EfficientNetV2 模型(已转换为 model.json 格式)。
  • 支持 WebGPU 的浏览器(Chrome 113+ 或 Edge)。

WebGPU 初始化

WebGPU 是 WebGL 的继任者,提供更低的开销和更好的 GPU 计算能力访问。在 TensorFlow.js 中,初始化它相当简单,但需要进行异步检查。

import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-backend-webgpu';

async function initializeAI() {
  try {
    // Attempt to set the backend to WebGPU
    await tf.setBackend('webgpu');
    await tf.ready();
    console.log("🚀 Running on WebGPU: The future is here!");
  } catch (e) {
    console.warn("WebGPU not available, falling back to WebGL.");
    await tf.setBackend('webgl');
  }
}

模型加载

EfficientNetV2 非常适合此任务,因为它在提供最先进的准确性的同时,比其前代模型显著更快、更小。我们将加载一个在 ISIC(International Skin Imaging Collaboration)数据集上微调的模型。

const MODEL_URL = '/models/efficientnet_v2_skin/model.json';

const useSkinClassifier = () => {
  const [model, setModel] = React.useState(null);

  React.useEffect(() => {
    const loadModel = async () => {
      const loadedModel = await tf.loadGraphModel(MODEL_URL);
      // Warm up the model to avoid first‑inference lag
      const dummyInput = tf.zeros([1, 224, 224, 3]);
      loadedModel.predict(dummyInput);
      setModel(loadedModel);
    };
    loadModel();
  }, []);

  return model;
};

预测逻辑

核心逻辑包括捕获视频帧,将其调整为 224×224(EfficientNetV2 所需的输入尺寸),并对像素值进行归一化。

const predict = async (videoElement, model) => {
  if (!model || !videoElement) return;

  const result = tf.tidy(() => {
    // 1. Convert video frame to tensor
    const img = tf.browser.fromPixels(videoElement);

    // 2. Preprocess: Resize and Normalize to [-1, 1] or [0, 1]
    const resized = tf.image.resizeBilinear(img, [224, 224]);
    const offset = tf.scalar(127.5);
    const normalized = resized.sub(offset).div(offset).expandDims(0);

    // 3. Inference
    return model.predict(normalized);
  });

  const probabilities = await result.data();
  const topResult = getTopClass(probabilities);

  // Clean up tensors
  tf.dispose(result);

  return topResult;
};

生产考虑因素

构建原型很容易;构建生产级医学筛查工具却很困难。您需要处理:

  • 光照变化
  • 运动模糊
  • 分布外(OOD)数据(例如,用户将摄像头对准狗而不是皮肤病变)

专业提示: 在生产环境中,使用模型量化来减小捆绑包大小,并使用 Web Workers 让 UI 线程保持流畅。

如果您在寻找用于高风险环境部署 AI 的高级架构模式,请查看 WellAlly 博客的技术深度解析。他们提供了针对企业级 React 应用优化 TensorFlow 模型以及处理实时视觉流水线复杂状态的资源。

类映射与优先级评估

我们的系统不仅仅给出标签;它在评估“医疗优先级”。我们将诸如 Melanoma(黑色素瘤)映射为高优先级,将 Nevus(痣)映射为低优先级。

const CLASSES = {
  0: { name: 'Actinic keratoses', priority: 'Medium' },
  1: { name: 'Basal cell carcinoma', priority: 'High' },
  2: { name: 'Benign keratosis', priority: 'Low' },
  3: { name: 'Dermatofibroma', priority: 'Low' },
  4: { name: 'Melanoma', priority: 'Urgent' },
  5: { name: 'Melanocytic nevi', priority: 'Low' },
  6: { name: 'Vascular lesions', priority: 'Medium' }
};

const getTopClass = (probs) => {
  const maxIdx = probs.indexOf(Math.max(...probs));
  return {
    ...CLASSES[maxIdx],
    confidence: probs[maxIdx]
  };
};

结论

我们已经成功构建了一个本地化、硬件加速的皮肤病变分类器。通过使用 EfficientNetV2 和 WebGPU,我们实现了接近原生的性能,用户无需下载“App”。

注意: 基于 AI 的筛查工具旨在辅助,而不是取代专业的医学诊断。务必在 UI 中加入免责声明!🩺

接下来怎么办?

  • 尝试实现量化(Int8 或 Float16),看看它对 WebGPU 性能的影响。
  • 查看 WellAlly 的高级指南,获取有关扩展此类应用的更多见解。

你已经尝试过 WebGPU 吗?在下方留言告诉我们你的想法!👇

Back to Blog

相关文章

阅读更多 »