Views
No views yet
clip-face-attribute-classifier, a fine-tuned version of the openai/clip-vit-large-patch14 model. It has been adapted for multi-task classification of perceived age, gender, and race from facial images.MultiTaskClipVisionModel class, as it is not a standard AutoModel.1import torch
2from PIL import Image
3from transformers import CLIPImageProcessor, AutoModel
4import os
5import torch.nn as nn
6
7# --- 0. Define the Custom Model Class ---
8# You must define the model architecture to load the weights into it.
9class MultiTaskClipVisionModel(nn.Module):
10 def __init__(self, num_labels):
11 super(MultiTaskClipVisionModel, self).__init__()
12 # Load the vision part of a CLIP model
13 self.vision_model = AutoModel.from_pretrained("openai/clip-vit-large-patch14").vision_model
14
15 hidden_size = self.vision_model.config.hidden_size
16 self.age_head = nn.Linear(hidden_size, num_labels['age'])
17 self.gender_head = nn.Linear(hidden_size, num_labels['gender'])
18 self.race_head = nn.Linear(hidden_size, num_labels['race'])
19
20 def forward(self, pixel_values):
21 outputs = self.vision_model(pixel_values=pixel_values)
22 pooled_output = outputs.pooler_output
23 return {
24 'age': self.age_head(pooled_output),
25 'gender': self.gender_head(pooled_output),
26 'race': self.race_head(pooled_output),
27 }
28
29# --- 1. Configuration ---
30MODEL_PATH = "syntheticbot/clip-face-attribute-classifier"
31DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
32
33# --- 2. Define Label Mappings (must match training) ---
34age_labels = ['0-2', '10-19', '20-29', '3-9', '30-39', '40-49', '50-59', '60-69', 'more than 70']
35gender_labels = ['Female', 'Male']
36race_labels = ['Black', 'East Asian', 'Indian', 'Latino_Hispanic', 'Middle Eastern', 'Southeast Asian', 'White']
37
38# Use sorted lists to create a consistent mapping
39id_mappings = {
40 'age': {i: label for i, label in enumerate(sorted(age_labels))},
41 'gender': {i: label for i, label in enumerate(sorted(gender_labels))},
42 'race': {i: label for i, label in enumerate(sorted(race_labels))},
43}
44NUM_LABELS = { 'age': len(age_labels), 'gender': len(gender_labels), 'race': len(race_labels) }
45
46# --- 3. Load Model and Processor ---
47processor = CLIPImageProcessor.from_pretrained(MODEL_PATH)
48model = MultiTaskClipVisionModel(num_labels=NUM_LABELS)
49
50
51model.to(DEVICE)
52model.eval()
53
54# --- 4. Prediction Function ---
55def predict(image_path):
56 if not os.path.exists(image_path):
57 print(f"Error: Image not found at {image_path}")
58 return
59
60 image = Image.open(image_path).convert("RGB")
61 inputs = processor(images=image, return_tensors="pt").to(DEVICE)
62
63 with torch.no_grad():
64 logits = model(pixel_values=inputs['pixel_values'])
65
66 predictions = {}
67 for task in ['age', 'gender', 'race']:
68 pred_id = torch.argmax(logits[task], dim=-1).item()
69 pred_label = id_mappings[task][pred_id]
70 predictions[task] = pred_label
71
72 print(f"Predictions for {image_path}:")
73 for task, label in predictions.items():
74 print(f" - {task.capitalize()}: {label}")
75 return predictions
76
77# --- 5. Run Prediction ---
78
79predict('sample.jpg') # Replace with the path to your image precision recall f1-score support
Female 0.96 0.96 0.96 5162
Male 0.96 0.97 0.97 5792
accuracy 0.96 10954
macro avg 0.96 0.96 0.96 10954
weighted avg 0.96 0.96 0.96 10954 precision recall f1-score support
Black 0.90 0.89 0.89 1556
East Asian 0.74 0.78 0.76 1550
Indian 0.81 0.75 0.78 1516
Latino_Hispanic 0.58 0.62 0.60 1623
Middle Eastern 0.69 0.57 0.62 1209
Southeast Asian 0.66 0.65 0.65 1415
White 0.75 0.80 0.77 2085
accuracy 0.73 10954
macro avg 0.73 0.72 0.73 10954
weighted avg 0.73 0.73 0.73 10954 precision recall f1-score support
0-2 0.93 0.45 0.60 199
10-19 0.62 0.41 0.50 1181
20-29 0.64 0.76 0.70 3300
3-9 0.77 0.88 0.82 1356
30-39 0.49 0.50 0.49 2330
40-49 0.46 0.44 0.45 1353
50-59 0.47 0.40 0.43 796
60-69 0.45 0.32 0.38 321
more than 70 0.75 0.10 0.18 118
accuracy 0.59 10954
macro avg 0.62 0.47 0.51 10954
weighted avg 0.59 0.59 0.58 109541@inproceedings{radford2021learning,
2 title={Learning Transferable Visual Models From Natural Language Supervision},
3 author={Alec Radford and Jong Wook Kim and Chris Hallacy and Aditya Ramesh and Gabriel Goh and Sandhini Agarwal and Girish Sastry and Amanda Askell and Pamela Mishkin and Jack Clark and Gretchen Krueger and Ilya Sutskever},
4 booktitle={International Conference on Machine Learning},
5 year={2021}
6}1@inproceedings{karkkainenfairface,
2 title={FairFace: Face Attribute Dataset for Balanced Race, Gender, and Age},
3 author={Karkkainen, Kimmo and Joo, Jungseock},
4 booktitle={IEEE Winter Conference on Applications of Computer Vision (WACV)},
5 pages={1548--1558},
6 year={2021}
7}