模型概述
模型特點
模型能力
使用案例
🚀 基於EVA的快速NSFW圖像分類器
本模型是一個基於EVA架構的視覺變換器,經過微調用於NSFW內容分類。它使用100,000張合成標註圖像進行訓練,可檢測視覺內容的四個類別(中性、低、中、高)。該模型既可以用作二元(是/否)分類器,也可以獲取完整的輸出概率。
🚀 快速開始
你可以通過以下幾種方式快速使用本模型:
📦 安裝指南
通過pip快速開始
pip install nsfw-image-detector
使用pipeline快速開始
from transformers import pipeline
from PIL import Image
# 創建分類器pipeline
classifier = pipeline(
"image-classification",
model="Freepik/nsfw_image_detector",
device=0 # 使用GPU (0) 或CPU (-1)
)
# 加載並分類圖像
image = Image.open("path/to/your/image.jpg")
predictions = classifier(image)
print(predictions)
避免安裝pip依賴
from transformers import AutoModelForImageClassification
import torch
from PIL import Image
from typing import List, Dict
import torch.nn.functional as F
from timm.data.transforms_factory import create_transform
from torchvision.transforms import Compose
from timm.data import resolve_data_config
from timm.models import get_pretrained_cfg
device = "cuda" if torch.cuda.is_available() else "cpu"
# 加載模型和處理器
model = AutoModelForImageClassification.from_pretrained("Freepik/nsfw_image_detector", torch_dtype = torch.bfloat16).to(device)
# 加載原始處理器(對張量更快)
cfg = get_pretrained_cfg("eva02_base_patch14_448.mim_in22k_ft_in22k_in1k")
processor: Compose = create_transform(**resolve_data_config(cfg.__dict__))
def predict_batch_values(model, processor: Compose, img_batch: List[Image.Image] | torch.Tensor) -> List[Dict[str, float]]:
"""
處理一批圖像並返回每個NSFW類別的預測分數
"""
idx_to_label = {0: 'neutral', 1: 'low', 2: 'medium', 3: 'high'}
# 準備批次
inputs = torch.stack([processor(img) for img in img_batch])
output = []
with torch.inference_mode():
logits = model(inputs).logits
batch_probs = F.log_softmax(logits, dim=-1)
batch_probs = torch.exp(batch_probs).cpu()
for i in range(len(batch_probs)):
element_probs = batch_probs[i]
output_img = {}
danger_cum_sum = 0
for j in range(len(element_probs) - 1, -1, -1):
danger_cum_sum += element_probs[j]
if j == 0:
danger_cum_sum = element_probs[j]
output_img[idx_to_label[j]] = danger_cum_sum.item()
output.append(output_img)
return output
def prediction(model, processor, img_batch: List[Image.Image], class_to_predict: str, threshold: float=0.5) -> List[bool]:
"""
預測圖像是否達到或超過特定的NSFW閾值
"""
if class_to_predict not in ["low", "medium", "high"]:
raise ValueError("class_to_predict必須是以下之一: low, medium, high")
if not 0 <= threshold <= 1:
raise ValueError("threshold必須在0和1之間")
output = predict_batch_values(model, processor, img_batch)
return [output[i][class_to_predict] >= threshold for i in range(len(output))]
# 示例用法
image = Image.open("path/to/your/image.jpg")
print(predict_batch_values(model, processor, [image]))
print(prediction(model, processor, [image], "medium")) # 選項: low, medium, high
💻 使用示例
基礎用法
from PIL import Image
from nsfw_image_detector import NSFWDetector
import torch
# 初始化檢測器
detector = NSFWDetector(dtype=torch.bfloat16, device="cuda")
# 加載並分類圖像
image = Image.open("your_image")
# 檢查圖像是否包含中等或更高敏感度的NSFW內容
is_nsfw = detector.is_nsfw(image, "medium")
# 獲取所有類別的概率分數
probabilities = detector.predict_proba(image)
print(f"是否為NSFW: {is_nsfw}")
print(f"概率: {probabilities}")
示例輸出:
是否為NSFW: False
概率:
[
{<NSFWLevel.HIGH: 'high'>: 0.00372314453125,
<NSFWLevel.MEDIUM: 'medium'>: 0.1884765625,
<NSFWLevel.LOW: 'low'>: 0.234375,
<NSFWLevel.NEUTRAL: 'neutral'>: 0.765625}
]
高級用法
# 模型支持對多個圖像進行高效批量處理
images = [Image.open(path) for path in ["image1.jpg", "image2.jpg", "image3.jpg"]]
predictions = classifier(images)
⚠️ 重要提示
如果打算在生產環境中使用該模型,請在使用此方法之前查看速度和內存指標部分。
💡 使用建議
- 模型以bf16進行訓練,建議以bf16使用。
- 使用torch張量時,速度提升並非通過pipeline實現,避免在生產環境中使用pipeline。
- 測量在NVIDIA RTX 3090上進行,在更強大的服務器上可能會有更好的指標。
- 吞吐量會隨著批量大小的增加而提高,選擇批量大小時請考慮使用場景。
- 列出的優化建議可進一步提高性能。
- 在將模型用於文本到圖像模型或類似場景時,特別建議使用torch張量,因為輸出已經是張量格式。
✨ 主要特性
- 高精度:在內部基準測試中,該模型在準確性方面優於其他優秀的公開可用模型,如Falconsai/nsfw_image_detection和AdamCodd/vit-base-nsfw-detector。
- 細粒度分類:不僅適用於檢測“高”和“中性”內容,在識別“低”和“中”級別的NSFW內容方面也表現出色。
- 在線試用:可以通過Hugging Face Space直接在瀏覽器中試用該模型,無需安裝。
- 批量處理:支持對多個圖像進行高效批量處理。
📚 詳細文檔
模型描述
本模型是基於EVA架構的視覺變換器,經過微調用於NSFW內容分類。它使用100,000張合成標註圖像進行訓練,可檢測視覺內容的四個類別(中性、低、中、高)。
該模型既可以用作二元(是/否)分類器,也可以獲取完整的輸出概率。在內部基準測試中,它優於其他優秀的公開可用模型,如Falconsai/nsfw_image_detection或AdamCodd/vit-base-nsfw-detector,並且能夠選擇適合您用例的NSFW級別。
在線試用!🌐
您可以通過我們的Hugging Face Space直接在瀏覽器中試用該模型。上傳任何圖像,即可立即獲得NSFW分類結果,無需任何安裝。
模型性能比較
全局性能
類別 | Freepik | Falconsai | Adamcodd |
---|---|---|---|
高 | 99.54% | 97.92% | 98.62% |
中 | 97.02% | 78.54% | 91.65% |
低 | 98.31% | 31.25% | 89.66% |
中性 | 99.87% | 99.27% | 98.37% |
以下是結果的獲取方式:
- 對於Falconsai和AdamCodd模型:
- 如果圖像標記為“低”、“中”或“高”,且模型返回true,則預測被認為是正確的。
- 如果標記為“中性”,則正確輸出應為false。
- 對於Freepik模型:
- 如果圖像標記為“低”、“中”或“高”,則模型應至少返回“低”。
- 如果標記為“中性”,則正確輸出應為“中性”。
結論:
- 我們的模型在準確性方面優於AdamCodd和Falconsai。在“高”和“中性”標籤上進行比較是完全公平的。
- 我們的模型提供了更高的粒度。它不僅適用於檢測“高”和“中性”內容,在識別“低”和“中”級別的NSFW內容方面也表現出色。
- Falconsai可能會將一些“中”和“低”級別的圖像分類為非NSFW,但將其他圖像標記為安全工作(SFW),這可能會導致意外結果。
- AdamCodd將“低”和“中”類別都分類為NSFW,這可能根據您的用例並不理想。此外,有10%的“低”和“中”級別的圖像被認為是SFW。
按AI內容劃分的準確率
我們創建了一個手動標註的數據集,並特別注意避免偏差(性別、種族等)。雖然樣本量相對較小,但它為不同場景下的模型性能提供了有意義的見解,這在訓練過程中對於避免偏差非常有用。
以下表格顯示了不同NSFW類別和內容類型的檢測準確率百分比:
AI生成內容
類別 | Freepik模型 | Falconsai模型 | Adamcodd模型 |
---|---|---|---|
高 | 100.00% | 84.00% | 92.00% |
中 | 96.15% | 69.23% | 96.00% |
低 | 100.00% | 35.71% | 92.86% |
中性 | 100.00% | 100.00% | 66.67% |
結論:
- 避免在AI生成內容中使用Falconsai,以防止預測錯誤。
- 我們的模型是檢測AI生成內容中NSFW內容的最佳選擇。
訓練
- 訓練數據:使用了100,000張圖像進行訓練。
- 訓練設備:在3塊NVIDIA GeForce RTX 3090上訓練了3個epoch。
- 數據集劃分:使用訓練集和驗證集進行訓練。
- 去重處理:為避免訓練集和驗證集之間的重複和偏差,使用“openai/clip-vit-base-patch32”模型去除餘弦相似度高於0.92的圖像。
- 自定義損失:創建了一個自定義損失,以最小化低於真實類別的預測。例如,標記為“高”的圖像被預測為“中性”的情況非常罕見(僅佔0.46%)。
速度和內存指標
批量大小 | 每批平均時間 (ms) | VRAM (MB) | 優化方式 |
---|---|---|---|
1 | 28 | 540 | 使用PIL圖像的BF16 |
4 | 110 | 640 | 使用PIL圖像的BF16 |
16 | 412 | 1144 | 使用PIL圖像的BF16 |
1 | 10 | 540 | 使用torch張量的BF16 |
4 | 33 | 640 | 使用torch張量的BF16 |
16 | 102 | 1144 | 使用torch張量的BF16 |
🔧 技術細節
模型基於EVA架構,使用了特定的訓練數據和優化策略,以實現高效準確的NSFW圖像分類。在訓練過程中,採用了自定義損失函數,避免了數據集中的重複和偏差,提高了模型的泛化能力。同時,通過對不同批量大小和數據格式(PIL圖像和torch張量)的測試,提供了詳細的速度和內存指標,為用戶在不同場景下的使用提供了參考。
📄 許可證
本項目採用MIT許可證 - 版權所有2025 Freepik Company S.L.
引用
如果您在研究或項目中使用此模型,請按以下方式引用:
@software{freepik2025nsfw,
title={EVA-based Fast NSFW Image Classifier},
author={Freepik Company S.L.},
year={2025},
publisher={Hugging Face},
url = {https://huggingface.co/Freepik/nsfw_image_detector},
organization = {Freepik Company S.L.}
}
致謝
本模型基於EVA架構(timm/eva02_base_patch14_448.mim_in22k_ft_in22k_in1k),相關論文如下:
EVA-02: A Visual Representation for Neon Genesis - https://arxiv.org/abs/2303.11331
@article{EVA02,
title={EVA-02: A Visual Representation for Neon Genesis},
author={Fang, Yuxin and Sun, Quan and Wang, Xinggang and Huang, Tiejun and Wang, Xinlong and Cao, Yue},
journal={arXiv preprint arXiv:2303.11331},
year={2023}
}









