/ Модель

Характеристики

Лицензия
Apache 2.0
Базовая модель
nsfw-image-detection-384
Библиотека
onnx
Опубликована
2 июн 2026

nsfw-image-detection-384-onnx

Классификация изображенийИзображение → label3 профессии
213скачиваний за 30 дней0лайковвеса обновлены6 сен 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

ONNX-классификатор изображений на ViT Tiny выявляет потенциально откровенный контент, относя изображения к классам NSFW или SFW.

Это формат ONNX модели KanariKanaru/nsfw-image-detection-384-onnx — двухклассового классификатора изображений на архитектуре ViT Tiny с входом 384 × 384 пикселя. Репозиторий содержит экспорт модели Marqo/nsfw-image-detection-384; для запуска используется ONNX Runtime без PyTorch и timm. Модель принимает изображение и относит его к одному из двух классов: NSFW или SFW.

Модель подходит для предварительной фильтрации изображений и выявления потенциально откровенного контента. Исходная модель была дообучена на 200 000 изображений и показала точность 98,56% на тестовом наборе авторов из 20 000 изображений; эти результаты относятся к исходной модели и не являются независимой оценкой ONNX-экспорта. Веса ONNX имеют формат float32 и не квантизированы. Для неквадратных изображений способ изменения размера может повлиять на предсказание, а выбор порога вероятности меняет соотношение ложных срабатываний и пропусков. Классификация NSFW зависит от контекста, и модель может ошибаться. Лицензия — Apache-2.0.

Сценарии применения

  • фильтрация потенциально откровенных изображений в пользовательских загрузках
  • автоматическая модерация изображений на сайтах и в приложениях
  • предварительная сортировка изображений по признаку NSFW/SFW

Ограничения

Модель может ошибаться, поскольку оценка NSFW зависит от контекста; порог вероятности следует подбирать для конкретного применения. Изменение размера неквадратных изображений может влиять на предсказания, а приведённые показатели точности относятся к исходной модели и тестовому набору её авторов.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

NSFW Image Detection 384 — ONNX

ONNX export of Marqo/nsfw-image-detection-384, a two-class image classifier based on vit_tiny_patch16_384. Run inference with ONNX Runtime without installing PyTorch or timm.

The weights were converted from KanariKanaru/nsfw-image-detection-384 at revision dcbee2f0570c16c3212bc6b81bb8911194b9fa62. This repository provides a format conversion, not a newly trained model.

NSFW content is subjective and contextual, and the model can make mistakes. Evaluate it on your own images and choose a threshold appropriate for your application.

Model interface

PropertyValue
Model filemodel.onnx
FormatONNX, opset 17, float32 (not quantized)
Inputinput, float32, shape [1, 3, 384, 384] (NCHW)
ColorRGB
NormalizationScale pixels to [0, 1], then (x - 0.5) / 0.5 for each channel
Outputlogits, float32, shape [1, 2]
Class orderIndex 0: nsfw (NSFW); index 1: safe (SFW)
PostprocessingSoftmax over the class dimension
Batch sizeFixed at 1

Preprocessing and softmax run outside the ONNX graph. The packaged manifest specifies resizing directly to 384 × 384 with a Catmull–Rom filter. The example below uses Pillow's bicubic resampling, whose results can differ from another library's implementation. Direct resizing can change the aspect ratio; the original timm configuration instead specifies a center crop with crop_pct=1.0. These preprocessing paths may give different predictions on non-square images.

Python inference with ONNX Runtime

pip install onnxruntime numpy pillow huggingface_hub

Save an image as image.jpg, then run:

import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from PIL import Image, ImageOps

model_path = hf_hub_download(
    repo_id="KanariKanaru/nsfw-image-detection-384-onnx",
    filename="model.onnx",
)
# If you already downloaded the model, use model_path = "model.onnx".
session = ort.InferenceSession(
    model_path,
    providers=["CPUExecutionProvider"],
)

with Image.open("image.jpg") as source:
    image = ImageOps.exif_transpose(source).convert("RGB")
    image = image.resize((384, 384), resample=Image.Resampling.BICUBIC)
    pixels = np.asarray(image, dtype=np.float32) / np.float32(255.0)

pixels = (pixels - np.float32(0.5)) / np.float32(0.5)
inputs = np.ascontiguousarray(pixels.transpose(2, 0, 1)[None, ...])
logits = session.run(["logits"], {"input": inputs})[0]

# Numerically stable softmax: the model returns logits, not probabilities.
exp_logits = np.exp(logits - logits.max(axis=-1, keepdims=True))
probabilities = exp_logits / exp_logits.sum(axis=-1, keepdims=True)
labels = ["nsfw", "safe"]
scores = dict(zip(labels, probabilities[0].tolist()))
print("Probabilities:", scores)
print("Class:", labels[int(probabilities[0].argmax())])

threshold = 0.5  # Example only; tune on representative data.
print("NSFW:", scores["nsfw"] >= threshold)

Repository files

  • model.onnx: model used by the inference example.
  • manifest.json: input preprocessing, output labels, and artifact metadata.
  • conversion_report.json: source revision, exporter versions, and numerical validation results.
  • SHA256SUMS: checksums for the ONNX model and accompanying package metadata.
  • config.json and model.safetensors: source timm configuration and weights; not required for ONNX Runtime inference.
  • MODEL_NOTICES.md and LICENSE-APACHE-2.0.txt: attribution and license information.

To clone with the model weights, install Git LFS first:

git lfs install
git clone https://huggingface.co/KanariKanaru/nsfw-image-detection-384-onnx
cd nsfw-image-detection-384-onnx
shasum -a 256 -c SHA256SUMS

Conversion validation

The conversion report records the following comparison between the source model and ONNX Runtime:

MetricRecorded result
Maximum absolute logit difference7.152557373046875e-07
Maximum absolute softmax score difference5.960464477539063e-08
Top-label match1

The exporter used one synthetic random input for this check. These results check numerical agreement for that input; they do not constitute an evaluation of classification accuracy on real images.

Original model evaluation

The original model card reports 98.56% accuracy on the authors' proprietary test set of 20,000 images (10,000 NSFW and 10,000 SFW). The model was trained on 200,000 images, evenly split between the two classes, and fine-tuned from timm/vit_tiny_patch16_384.augreg_in21k_ft_in1k.

The following figures are reproduced from the original model card. They describe the source model's evaluation, not a separate benchmark of this ONNX export.

Original model comparison

Thresholds and precision vs. recall

Adjusting the NSFW probability threshold trades off precision and recall. The best threshold depends on your images and how you weigh false positives and false negatives.

Original model threshold evaluation Original model precision and recall curves

License and attribution

Apache-2.0. See LICENSE-APACHE-2.0.txt and MODEL_NOTICES.md. The original model was published by Marqo; this repository distributes its ONNX conversion and accompanying files.

Citation

@article{dosovitskiy2020vit,
  title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale},
  author={Dosovitskiy, Alexey and Beyer, Lucas and Kolesnikov, Alexander and Weissenborn, Dirk and Zhai, Xiaohua and Unterthiner, Thomas and  Dehghani, Mostafa and Minderer, Matthias and Heigold, Georg and Gelly, Sylvain and Uszkoreit, Jakob and Houlsby, Neil},
  journal={ICLR},
  year={2021}
}
@misc{rw2019timm,
  author = {Ross Wightman},
  title = {PyTorch Image Models},
  year = {2019},
  publisher = {GitHub},
  journal = {GitHub repository},
  doi = {10.5281/zenodo.4414861},
  howpublished = {\url{https://github.com/huggingface/pytorch-image-models}}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · onnx · image-classification

Можно запустить

Подбираем GPU…

Ревизия весов
8edc47e

0 моделей