Views
No views yet
1from model import predict_age_gender
2
3result = predict_age_gender("your_image.jpg")
4print(f"Age: {result['age']}, Gender: {result['gender']}")LABEL_0/LABEL_1)1from model import predict_age_gender
2
3result = predict_age_gender("image.jpg")
4print(f"Age: {result['age']}, Gender: {result['gender']}")
5print(f"Confidence: {result['gender_confidence']:.1%}")1from model import simple_predict
2
3print(simple_predict("image.jpg"))
4# Output: "25 years, Female (87.3% confidence)"pipeline() approach returns LABEL_0/LABEL_1 and should not be used.1from model import predict_age_gender
2
3# Predict from file
4result = predict_age_gender("your_image.jpg")
5print(f"Age: {result['age']} years")
6print(f"Gender: {result['gender']}")
7print(f"Confidence: {result['gender_confidence']:.1%}")
8
9# Predict from URL
10result = predict_age_gender("https://example.com/face_image.jpg")
11print(f"Prediction: {result['age']} years, {result['gender']}")
12
13# Works with PIL Image too
14from PIL import Image
15img = Image.open("image.jpg")
16result = predict_age_gender(img)
17print(f"Result: {result['age']} years, {result['gender']}")1from model import predict_age_gender, simple_predict
2
3# Method 1: Detailed result
4result = predict_age_gender("your_image.jpg")
5print(f"Age: {result['age']}, Gender: {result['gender']}")
6print(f"Confidence: {result['confidence']:.1%}")
7
8# Method 2: Simple string output
9prediction = simple_predict("your_image.jpg")
10print(prediction) # "25 years, Female (87% confidence)"1# Install requirements
2!pip install transformers torch pillow
3
4from model import predict_age_gender
5import matplotlib.pyplot as plt
6from PIL import Image
7
8# Upload image in Colab
9from google.colab import files
10uploaded = files.upload()
11filename = list(uploaded.keys())[0]
12
13# Predict
14result = predict_age_gender(filename)
15
16# Display
17img = Image.open(filename)
18plt.figure(figsize=(8, 6))
19plt.imshow(img)
20plt.title(f"Prediction: {result['age']} years, {result['gender']} ({result['gender_confidence']:.1%})")
21plt.axis('off')
22plt.show()
23
24print(f"Age: {result['age']} years")
25print(f"Gender: {result['gender']}")
26print(f"Confidence: {result['gender_confidence']:.1%}")1from model import predict_age_gender
2
3# Process multiple images
4images = ["image1.jpg", "image2.jpg", "image3.jpg"]
5results = []
6
7for image in images:
8 result = predict_age_gender(image)
9 results.append({
10 'image': image,
11 'age': result['age'],
12 'gender': result['gender'],
13 'confidence': result['gender_confidence']
14 })
15
16for result in results:
17 print(f"{result['image']}: {result['age']} years, {result['gender']} ({result['confidence']:.1%})")1import cv2
2from model import predict_age_gender
3from PIL import Image
4
5cap = cv2.VideoCapture(0)
6
7while True:
8 ret, frame = cap.read()
9 if ret:
10 # Convert frame to PIL Image
11 rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
12 pil_image = Image.fromarray(rgb_frame)
13
14 # Predict
15 result = predict_age_gender(pil_image)
16
17 # Display prediction
18 text = f"Age: {result['age']}, Gender: {result['gender']}"
19 cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
20 cv2.imshow('Age-Gender Detection', frame)
21
22 if cv2.waitKey(1) & 0xFF == ord('q'):
23 break
24
25cap.release()
26cv2.destroyAllWindows()1from model import predict_age_gender
2
3# Direct URL prediction
4image_url = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300"
5result = predict_age_gender(image_url)
6
7print(f"Age: {result['age']} years")
8print(f"Gender: {result['gender']}")
9print(f"Confidence: {result['gender_confidence']:.1%}")1{
2 "age": 25,
3 "gender": "Female",
4 "gender_confidence": 0.873,
5 "gender_probability_male": 0.127,
6 "gender_probability_female": 0.873,
7 "label": "25 years, Female",
8 "score": 0.873
9}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 |
1# Minimal installation
2pip install transformers torch pillow
3
4# Full installation with optional dependencies
5pip install transformers torch torchvision pillow opencv-python matplotlib
6
7# For development
8pip install transformers torch pillow pytest black flake81from model import predict_age_gender
2
3def moderate_content(image_path):
4 result = predict_age_gender(image_path)
5 age = result['age']
6
7 if age < 18:
8 return f"Minor detected ({age} years) - content flagged for review"
9 return f"Adult content approved: {age} years, {result['gender']}"
10
11status = moderate_content("user_upload.jpg")
12print(status)1from model import predict_age_gender
2from glob import glob
3
4def analyze_audience(image_folder):
5 demographics = {"male": 0, "female": 0, "total_age": 0, "count": 0}
6
7 for image_path in glob(f"{image_folder}/*.jpg"):
8 result = predict_age_gender(image_path)
9 demographics[result['gender'].lower()] += 1
10 demographics['total_age'] += result['age']
11 demographics['count'] += 1
12
13 demographics['avg_age'] = demographics['total_age'] / demographics['count']
14 demographics['male_percent'] = demographics['male'] / demographics['count'] * 100
15 demographics['female_percent'] = demographics['female'] / demographics['count'] * 100
16
17 return demographics
18
19stats = analyze_audience("customer_photos/")
20print(f"Average age: {stats['avg_age']:.1f}")
21print(f"Gender split: {stats['male_percent']:.1f}% Male, {stats['female_percent']:.1f}% Female")1from model import predict_age_gender
2
3def verify_age(image_path, min_age=18):
4 result = predict_age_gender(image_path)
5 age = result['age']
6 confidence = result['gender_confidence']
7
8 if confidence < 0.7: # Low confidence
9 return "Please provide a clearer image"
10
11 if age >= min_age:
12 return f"Verified: {age} years old (meets {min_age}+ requirement)"
13 else:
14 return f"Age verification failed: {age} years old"
15
16verification = verify_age("id_photo.jpg", min_age=21)
17print(verification)1from model import predict_age_gender
2result = predict_age_gender("image.jpg")
3print(f"Age: {result['age']}, Gender: {result['gender']}")1from model import simple_predict
2print(simple_predict("image.jpg")) # "25 years, Female (87% confidence)"1from model import predict_age_gender
2
3def safe_predict(image_path):
4 try:
5 result = predict_age_gender(image_path)
6 return f"Age: {result['age']}, Gender: {result['gender']}"
7 except Exception as e:
8 return f"Prediction failed: {e}"
9
10prediction = safe_predict("any_image.jpg")
11print(prediction)LABEL_0/LABEL_1 instead of age/gender1# ✅ CORRECT METHOD - Use helper function
2from model import predict_age_gender
3
4result = predict_age_gender("image.jpg")
5print(f"Age: {result['age']}, Gender: {result['gender']}")
6# Output: Age: 25, Gender: Female1# ❌ WRONG METHOD - Don't use standard pipeline
2from transformers import pipeline
3classifier = pipeline("image-classification", ...) # Returns LABEL_0/LABEL_1pipeline() approach doesn't work properly with custom models. Always use the predict_age_gender() helper function.Some weights of ViTForImageClassification were not initialized...1@misc{age-gender-prediction-2025,
2 title={Age-Gender-Prediction: Vision Transformer for Facial Analysis},
3 author={Abhilash Sahoo},
4 year={2025},
5 publisher={Hugging Face},
6 url={https://huggingface.co/abhilash88/age-gender-prediction},
7 note={One-liner pipeline with 94.3\% gender accuracy}
8}1from model import predict_age_gender
2
3result = predict_age_gender("your_image.jpg")
4print(f"Age: {result['age']}, Gender: {result['gender']}")
5print(f"Confidence: {result['gender_confidence']:.1%}")1from model import simple_predict
2print(simple_predict("your_image.jpg"))
3# Output: "25 years, Female (87.3% confidence)"