/ Модель

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

Лицензия
MIT
Базовая модель
swiftformer_l1.dist_in1k
Библиотека
timm
Опубликована
15 мар 2026

image-safety-classifier-m

Классификация изображенийИзображение → label3 профессии

Компактная модель на базе SwiftFormer L1 классифицирует изображения как NSFW, NSFL или SFW для задач фильтрации и модерации контента.

179скачиваний за 30 дней1лайквеса обновлены17 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

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

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

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

OwenElliott/image-safety-classifier-m — компактная модель классификации изображений, разработанная Owen Elliott на базе SwiftFormer L1. Она относит изображение к одной из трёх категорий: NSFW — порнографический или откровенный контент, NSFL — сцены с кровью и жестокостью, SFW — остальной контент. Модель содержит 12,1 млн параметров и рассчитана на быстрое выполнение, в том числе на устройствах с ограниченными ресурсами. Доступны веса PyTorch и ONNX в форматах safetensors и ONNX.

Модель подходит для предварительной модерации изображений, фильтрации пользовательских загрузок и разметки контента по уровням безопасности. По заявлению автора, она обучена на частном наборе примерно из 320 тысяч веб-изображений, включавшем фотографии, рисунки, мемы, скриншоты и изображения, созданные ИИ. Лицензия — MIT.

Классы NSFL представлены в обучающих данных значительно слабее, чем NSFW и SFW, поэтому распознавание жестокого контента может быть менее надёжным. Предсказания могут ошибаться, а граница между откровенным и безопасным контентом зависит от контекста; результаты требуют осторожной интерпретации.

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

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

Ограничения

Класс NSFL слабо представлен в обучающем наборе, поэтому его распознавание может быть менее надёжным. Модель может ошибаться, а оценка откровенности зависит от контекста.

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

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

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

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

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

Открыть на Hugging Face

Image Safety Classifier

NOTE: Like all models, this one can make mistakes. NSFW content can be subjective and contextual, this model is intended to help identify this content, use at your own risk.

OwenElliott/image-safety-classifier-m is a lightweight image classification model designed to categorise images as either NSFW, NSFL, or SFW. NSFW images contain pornographic or highly suggestive content, NSFL images contain gore, and SFW images are everything else. The small size of this model and the SwiftFormer architecture make this model suitable for edge deployment or latency critical applications.

The model is trained on a proprietary dataset of ~320,000 images scraped from the web. These images include a diverse range of content including real photos, drawings, Rule 34, screenshots, AI generated images, memes, and more. The NSFW and SFW classes were checked with Marqo/nsfw-image-detection-384 and any images which were confidently predicted to be in the wrong class were manually reviewed.

Model Family

This model is part of a lineup of image safety classification models in 4 different sizes. All models are finetunes of SwiftFormer models.

Model NameParametersAccuracy
OwenElliott/image-safety-classifier-xs3.5M97.76%
OwenElliott/image-safety-classifier-s6.1M97.99%
OwenElliott/image-safety-classifier-m (this model)12.1M98.06%
OwenElliott/image-safety-classifier-l28.5M98.20%

Evaluation

This model outperforms existing NSFW detectors on our dataset, here we provide an evaluation against Marqo/nsfw-image-detection-384 and Falconsai/nsfw_image_detection.

Overall evaluation against other models on NSFW, NSFL and SFW

Per class evaluation against other models on NSFW, NSFL and SFW

*Note that Marqo/nsfw-image-detection-384 and Falconsai/nsfw_image_detection don't have an explicit NSFL class, for this evaluation the NSFW class from these model is treated as a correct classification for an NSFL image.

Model Usage

Image Classification with timm

pip install timm
from urllib.request import urlopen
from PIL import Image
import timm
import torch

img = Image.open(urlopen(
    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
))

model = timm.create_model("OwenElliott/image-safety-classifier-m", pretrained=True)
model = model.eval()

data_config = timm.data.resolve_model_data_config(model)
transforms = timm.data.create_transform(**data_config, is_training=False)

with torch.no_grad():
    output = model(transforms(img).unsqueeze(0)).softmax(dim=-1).cpu()

class_names = model.pretrained_cfg["label_names"]
print("Probabilities:", output[0])
print("Class:", class_names[output[0].argmax()])

ONNX Inference

ONNX models are available with preprocessing baked in — normalization and softmax are part of the graph, so you just need to resize your image and pass pixel values in 0-255 range. Both fp32 and fp16 variants are provided.

pip install onnxruntime pillow numpy
# For GPU: pip install onnxruntime-gpu
from urllib.request import urlopen
from PIL import Image
import numpy as np
import onnxruntime as ort

img = Image.open(urlopen(
    'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
))

# The model accepts 224x224 images
img = img.convert("RGB").resize((224, 224), Image.BILINEAR)

# Convert to [1, 3, 224, 224] float32 in 0-255
pixels = np.array(img, dtype=np.float32).transpose(2, 0, 1)[np.newaxis]

# Run inference (use fp16 variant for GPU acceleration)
# image colour channel normalisation is baked into the ONNX models
from huggingface_hub import hf_hub_download
model_path = hf_hub_download("OwenElliott/image-safety-classifier-m", "image-safety-classifier-m.onnx")
sess = ort.InferenceSession(model_path)
probs = sess.run(None, {{"image": pixels}})[0][0]

class_names = ["NSFL", "NSFW", "SFW"]
print("Probabilities:", dict(zip(class_names, probs)))
print("Class:", class_names[np.argmax(probs)])

Notes on the Dataset

The dataset is primarily NSFW and SFW examples, the NSFL class is very underrepresented, collecting NSFL data at scale has been challenging. This is something I would like to improve in a future version, for the moment this model significatly outperforms other models on NSFL classification however there is definitely room for improvement.

License

The fine-tuned weights and modifications in this repository are released under the MIT License.

This model is a fine-tuned version of timm/swiftformer_l1.dist_in1k, which is licensed under the Apache License 2.0 (see LICENSE-APACHE-SwiftFormer). The base weights were modified by fine-tuning on a separate image dataset for safety classification.

This model is provided "as is", without warranty of any kind. Users are responsible for evaluating its suitability and legal compliance for their use case and jurisdiction.

Citations

@InProceedings{Shaker_2023_ICCV,
    author    = {Shaker, Abdelrahman and Maaz, Muhammad and Rasheed, Hanoona and Khan, Salman and Yang, Ming-Hsuan and Khan, Fahad Shahbaz},
    title     = {SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications},
    booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV)},
    year      = {2023},
}
@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

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

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

Подбираем GPU…

Ревизия весов
23a4915

0 моделей