Logo
Section 1 / 3

图像分类

学习如何使用 Hugging Face 推理 API 进行图像分类。

导入

图像分类

学习如何使用 Hugging Face 推理 API 进行图像分类。

图像分类模型

模型描述
google/vit-base-patch16-224一种类似BERT的图像处理模型。最初在包含约1400万张图像和21,843个类别的ImageNet-21k数据集上进行训练,随后在包含约一百万张图像和1,000个类别的ImageNet 2012数据集上微调。
microsoft/beit-base-patch16-224-pt22k-ft22k与google/vit基于相同理念,但在初始训练阶段旨在从被遮蔽区域中提取视觉标记。
microsoft/resnet-50基于卷积神经网络,使模型能够更深入地学习特征。在ImageNet-1k数据集上训练,图像尺寸为224x224。
facebook/convnext-tiny-224结合了卷积神经网络与Transformer思想的模型。在ImageNet-1k数据集上训练,图像尺寸为224x224。

1https://api-inference.huggingface.co/models/{model}
1// 接口地址 2const endpointUrl = "https://api-inference.huggingface.co/models/google/vit-base-patch16-224"; 3 4const headerParameters = { 5 "Authorization": "Bearer {{ACCESS_TOKEN}}" 6}; 7 8async function classifyImage(imgUrl) { 9 try { 10 // 从URL读取图像 11 const imgResponse = await fetch(imgUrl); 12 const buffer = await imgResponse.buffer(); 13 14 const options = { 15 method: "POST", 16 headers: headerParameters, 17 body: buffer 18 }; 19 20 // 调用接口地址对图像进行分类 21 const response = await fetch(endpointUrl, options); 22 printResponse(response); 23 } catch (error) { 24 printError(error); 25 } 26} 27 28// 待分类图像的URL 29let imgUrl = "https://images.unsplash.com/photo-1604675223954-b1aabd668078"; 30 31classifyImage(imgUrl);

参数类型描述
score浮点数表示标签的置信度得分
label字符串表示图像的预测标签

1// 示例1 2let imgUrl = "https://images.unsplash.com/photo-1599889959407-598566c6e1f1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=40" 3 4// 示例2 5let imgUrl = "https://images.unsplash.com/photo-1643251935745-4209d215f221?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1200&q=40"
1// 接口地址 2const endpointUrl = "https://api-inference.huggingface.co/models/google/vit-base-patch16-224"; 3 4const headerParameters = { 5 "Authorization": "Bearer {{ACCESS_TOKEN}}" 6}; 7 8async function classifyImage(imgUrl) { 9 try { 10 // 从URL读取图像 11 const imgResponse = await fetch(imgUrl); 12 const buffer = await imgResponse.buffer(); 13 14 const options = { 15 method: "POST", 16 headers: headerParameters, 17 body: buffer 18 }; 19 20 // 调用接口地址对图像进行分类 21 const response = await fetch(endpointUrl, options); 22 printResponse(response); 23 } catch (error) { 24 printError(error); 25 } 26} 27 28// 待分类图像的URL 29let imgUrl = "https://images.unsplash.com/photo-1599889959407-598566c6e1f1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=40"; 30 31// 在HTML中渲染图像以显示 32console.log(`<img src=${imgUrl} width="400px" height="500px">`); 33classifyImage(imgUrl);

自然语言处理

目标检测