Downloads · 30 days
223
10% of all-time downloads
onnx-community/age-gender-prediction-ONNX
age-gender-prediction-ONNX is a image classification model from onnx-community. Use it when you need a label for an image. It is set up for transformers.js. The card lists the license as apache-2.0.
This is an ONNX version of abhilash88/age-gender-prediction. It was automatically converted and uploaded using this Hugging Face Space.
Downloads · 30 days
223
10% of all-time downloads
All-time downloads
2.2K
Public
Repo size
1.2 GB
Likes
3
Public
Click a slice to open those files.
.onnx345 MB · 100%
From the Hugging Face model README
This is an ONNX version of abhilash88/age-gender-prediction. It was automatically converted and uploaded using this Hugging Face Space.
import { AutoModel, AutoProcessor, load_image } from "@huggingface/transformers";
// Load model and processor
const model_id = 'onnx-community/age-gender-prediction-ONNX';
const model = await AutoModel.from_pretrained(model_id);
const processor = await AutoProcessor.from_pretrained(model_id);
// Load and preprocess image
const image = await load_image('https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?w=720');
const inputs = await processor(image);
// Run model
const { logits } = await model(inputs);
// Extract age and gender
const [ageLogits, genderLogits] = logits.tolist()[0];
const age = Math.min(Math.max(Math.round(ageLogits), 0), 100);
const gender = genderLogits >= 0.5 ? 'Female' : 'Male';
const confidence = Math.max(genderLogits, 1 - genderLogits);
console.table({ age, gender, confidence });
// ┌────────────┬────────────────────┐
// │ (index) │ Values │
// ├────────────┼────────────────────┤
// │ age │ 26 │
// │ gender │ 'Male' │
// │ confidence │ 0.9973341226577759 │
// └────────────┴────────────────────┘
A state-of-the-art Vision Transformer model for simultaneous age estimation and gender classification, achieving 94.3% gender accuracy and 4.5 years age MAE on the UTKFace dataset.
from model import predict_age_gender
result = predict_age_gender("your_image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
That's it! One line to get age and gender predictions.
✅ Issue Resolved: Model now includes helper functions that return proper age and gender values (not LABEL_0/LABEL_1)
Recommended usage:
from model import predict_age_gender
result = predict_age_gender("image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
print(f"Confidence: {result['gender_confidence']:.1%}")
Simple one-liner version:
from model import simple_predict
print(simple_predict("image.jpg"))
# Output: "25 years, Female (87.3% confidence)"
Important: These helper functions work correctly. The standard pipeline() approach returns LABEL_0/LABEL_1 and should not be used.
from model import predict_age_gender
# Predict from file
result = predict_age_gender("your_image.jpg")
print(f"Age: {result['age']} years")
print(f"Gender: {result['gender']}")
print(f"Confidence: {result['gender_confidence']:.1%}")
# Predict from URL
result = predict_age_gender("https://example.com/face_image.jpg")
print(f"Prediction: {result['age']} years, {result['gender']}")
# Works with PIL Image too
from PIL import Image
img = Image.open("image.jpg")
result = predict_age_gender(img)
print(f"Result: {result['age']} years, {result['gender']}")
from model import predict_age_gender, simple_predict
# Method 1: Detailed result
result = predict_age_gender("your_image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
print(f"Confidence: {result['confidence']:.1%}")
# Method 2: Simple string output
prediction = simple_predict("your_image.jpg")
print(prediction) # "25 years, Female (87% confidence)"
# Install requirements
!pip install transformers torch pillow
from model import predict_age_gender
import matplotlib.pyplot as plt
from PIL import Image
# Upload image in Colab
from google.colab import files
uploaded = files.upload()
filename = list(uploaded.keys())[0]
# Predict
result = predict_age_gender(filename)
# Display
img = Image.open(filename)
plt.figure(figsize=(8, 6))
plt.imshow(img)
plt.title(f"Prediction: {result['age']} years, {result['gender']} ({result['gender_confidence']:.1%})")
plt.axis('off')
plt.show()
print(f"Age: {result['age']} years")
print(f"Gender: {result['gender']}")
print(f"Confidence: {result['gender_confidence']:.1%}")
from model import predict_age_gender
# Process multiple images
images = ["image1.jpg", "image2.jpg", "image3.jpg"]
results = []
for image in images:
result = predict_age_gender(image)
results.append({
'image': image,
'age': result['age'],
'gender': result['gender'],
'confidence': result['gender_confidence']
})
for result in results:
print(f"{result['image']}: {result['age']} years, {result['gender']} ({result['confidence']:.1%})")
import cv2
from model import predict_age_gender
from PIL import Image
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret:
# Convert frame to PIL Image
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(rgb_frame)
# Predict
result = predict_age_gender(pil_image)
# Display prediction
text = f"Age: {result['age']}, Gender: {result['gender']}"
cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('Age-Gender Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
from model import predict_age_gender
# Direct URL prediction
image_url = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300"
result = predict_age_gender(image_url)
print(f"Age: {result['age']} years")
print(f"Gender: {result['gender']}")
print(f"Confidence: {result['gender_confidence']:.1%}")
The helper function returns a dictionary with the prediction:
{
"age": 25,
"gender": "Female",
"gender_confidence": 0.873,
"gender_probability_male": 0.127,
"gender_probability_female": 0.873,
"label": "25 years, Female",
"score": 0.873
}
Access the values:
result['age'] - Predicted age (integer, 0-100)result['gender'] - Predicted gender ("Male" or "Female")result['gender_confidence'] - Confidence score (0-1)result['gender_probability_male'] - Male probability (0-1)result['gender_probability_female'] - Female probability (0-1)result['label'] - Formatted string summary| Metric | Performance | Dataset |
|---|---|---|
| Gender Accuracy | 94.3% | UTKFace |
| Age MAE | 4.5 years | UTKFace |
| Architecture | ViT-Base + Dual Head | 768→256→64→1 |
| Parameters | 86.8M | Optimized |
| Inference Speed | ~50ms/image | CPU |
# Minimal installation
pip install transformers torch pillow
# Full installation with optional dependencies
pip install transformers torch torchvision pillow opencv-python matplotlib
# For development
pip install transformers torch pillow pytest black flake8
from model import predict_age_gender
def moderate_content(image_path):
result = predict_age_gender(image_path)
age = result['age']
if age < 18:
return f"Minor detected ({age} years) - content flagged for review"
return f"Adult content approved: {age} years, {result['gender']}"
status = moderate_content("user_upload.jpg")
print(status)
from model import predict_age_gender
from glob import glob
def analyze_audience(image_folder):
demographics = {"male": 0, "female": 0, "total_age": 0, "count": 0}
for image_path in glob(f"{image_folder}/*.jpg"):
result = predict_age_gender(image_path)
demographics[result['gender'].lower()] += 1
demographics['total_age'] += result['age']
demographics['count'] += 1
demographics['avg_age'] = demographics['total_age'] / demographics['count']
demographics['male_percent'] = demographics['male'] / demographics['count'] * 100
demographics['female_percent'] = demographics['female'] / demographics['count'] * 100
return demographics
stats = analyze_audience("customer_photos/")
print(f"Average age: {stats['avg_age']:.1f}")
print(f"Gender split: {stats['male_percent']:.1f}% Male, {stats['female_percent']:.1f}% Female")
from model import predict_age_gender
def verify_age(image_path, min_age=18):
result = predict_age_gender(image_path)
age = result['age']
confidence = result['gender_confidence']
if confidence < 0.7: # Low confidence
return "Please provide a clearer image"
if age >= min_age:
return f"Verified: {age} years old (meets {min_age}+ requirement)"
else:
return f"Age verification failed: {age} years old"
verification = verify_age("id_photo.jpg", min_age=21)
print(verification)
from model import predict_age_gender
result = predict_age_gender("image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
from model import simple_predict
print(simple_predict("image.jpg")) # "25 years, Female (87% confidence)"
from model import predict_age_gender
def safe_predict(image_path):
try:
result = predict_age_gender(image_path)
return f"Age: {result['age']}, Gender: {result['gender']}"
except Exception as e:
return f"Prediction failed: {e}"
prediction = safe_predict("any_image.jpg")
print(prediction)
LABEL_0/LABEL_1 instead of age/genderSolution: Use the helper functions instead of pipeline:
# ✅ CORRECT METHOD - Use helper function
from model import predict_age_gender
result = predict_age_gender("image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
# Output: Age: 25, Gender: Female
# ❌ WRONG METHOD - Don't use standard pipeline
from transformers import pipeline
classifier = pipeline("image-classification", ...) # Returns LABEL_0/LABEL_1
The standard pipeline() approach doesn't work properly with custom models. Always use the predict_age_gender() helper function.
This warning is expected and safe to ignore:
Some weights of ViTForImageClassification were not initialized...
The model uses custom age and gender heads instead of standard classification, which causes this informational warning. The model works correctly.
For optimal results:
@misc{age-gender-prediction-2025,
title={Age-Gender-Prediction: Vision Transformer for Facial Analysis},
author={Abhilash Sahoo},
year={2025},
publisher={Hugging Face},
url={https://huggingface.co/abhilash88/age-gender-prediction},
note={One-liner pipeline with 94.3\% gender accuracy}
}
Licensed under Apache 2.0. Commercial use permitted with attribution.
🎉 Ready to use! Just one line of code to get accurate age and gender predictions from any facial image! 🚀
Try it now:
from model import predict_age_gender
result = predict_age_gender("your_image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
print(f"Confidence: {result['gender_confidence']:.1%}")
Simple one-liner:
from model import simple_predict
print(simple_predict("your_image.jpg"))
# Output: "25 years, Female (87.3% confidence)"