Spaces:
Runtime error
Runtime error
Download model.py from ramyamail2/DLA_project: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/ramyamail2/DLA_project/resolve/main/model.py
- Command line
-
hf download hf://spaces/ramyamail2/DLA_project/model.py
-
curl -L -o model.py https://huggingface.co/spaces/ramyamail2/DLA_project/resolve/main/model.py
16.6 kB
| """ | |
| Face Emotion Recognition - Deep Learning Model | |
| Dataset: FER-2013 (Facial Expression Recognition) | |
| Classes: Angry, Disgust, Fear, Happy, Neutral, Sad, Surprise | |
| """ | |
| import numpy as np | |
| import os | |
| import cv2 | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.preprocessing import LabelBinarizer | |
| from sklearn.metrics import classification_report, confusion_matrix | |
| import seaborn as sns | |
| import json | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONFIG | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| EMOTIONS = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise'] | |
| IMG_SIZE = 48 | |
| CHANNELS = 1 # grayscale | |
| NUM_CLASSES = 7 | |
| EPOCHS = 50 | |
| BATCH_SIZE = 64 | |
| LEARNING_RATE = 0.001 | |
| RANDOM_SEED = 42 | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| # 1. SYNTHETIC DATASET GENERATOR | |
| # (Simulates FER-2013 structure so the | |
| # project runs without downloading 35 MB) | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| class FERDatasetGenerator: | |
| """ | |
| Generates synthetic 48Γ48 grayscale face-like images for each emotion. | |
| In a real project replace this with: | |
| kaggle datasets download -d msambare/fer2013 | |
| """ | |
| EMOTION_PROFILES = { | |
| 'Angry': {'brightness': 0.4, 'contrast': 1.4, 'noise': 0.15, 'color': 80}, | |
| 'Disgust': {'brightness': 0.35,'contrast': 1.2, 'noise': 0.12, 'color': 60}, | |
| 'Fear': {'brightness': 0.3, 'contrast': 0.9, 'noise': 0.20, 'color': 100}, | |
| 'Happy': {'brightness': 0.7, 'contrast': 1.1, 'noise': 0.05, 'color': 200}, | |
| 'Neutral': {'brightness': 0.5, 'contrast': 1.0, 'noise': 0.08, 'color': 128}, | |
| 'Sad': {'brightness': 0.3, 'contrast': 0.8, 'noise': 0.10, 'color': 90}, | |
| 'Surprise': {'brightness': 0.65,'contrast': 1.3, 'noise': 0.18, 'color': 180}, | |
| } | |
| # Approximate FER-2013 class counts | |
| SAMPLES_PER_CLASS = { | |
| 'Angry': 3995, 'Disgust': 436, 'Fear': 4097, | |
| 'Happy': 7215, 'Neutral': 4965,'Sad': 4830, 'Surprise': 3171, | |
| } | |
| def __init__(self, samples_per_class=None, img_size=IMG_SIZE): | |
| self.img_size = img_size | |
| self.counts = samples_per_class or self.SAMPLES_PER_CLASS | |
| def _generate_face(self, emotion): | |
| """Create a plausible face-like grayscale image for a given emotion.""" | |
| p = self.EMOTION_PROFILES[emotion] | |
| img = np.zeros((self.img_size, self.img_size), dtype=np.float32) | |
| cx, cy = self.img_size // 2, self.img_size // 2 | |
| # Head oval | |
| for y in range(self.img_size): | |
| for x in range(self.img_size): | |
| dx = (x - cx) / (self.img_size * 0.4) | |
| dy = (y - cy) / (self.img_size * 0.48) | |
| if dx*dx + dy*dy <= 1.0: | |
| img[y, x] = p['color'] | |
| # Eyes | |
| eye_y = int(cy - self.img_size * 0.12) | |
| for ex in [int(cx - self.img_size * 0.18), int(cx + self.img_size * 0.18)]: | |
| cv2.ellipse(img, (ex, eye_y), | |
| (int(self.img_size*0.07), int(self.img_size*0.05)), | |
| 0, 0, 360, 30, -1) | |
| # Mouth β emotion-specific curve | |
| mouth_y = int(cy + self.img_size * 0.18) | |
| if emotion == 'Happy': | |
| pts = np.array([[cx-10, mouth_y], [cx, mouth_y+8], [cx+10, mouth_y]], np.int32) | |
| elif emotion == 'Sad': | |
| pts = np.array([[cx-10, mouth_y+6], [cx, mouth_y-2], [cx+10, mouth_y+6]], np.int32) | |
| elif emotion == 'Surprise': | |
| cv2.ellipse(img, (cx, mouth_y), | |
| (int(self.img_size*0.08), int(self.img_size*0.10)), | |
| 0, 0, 360, 40, -1) | |
| pts = None | |
| elif emotion == 'Angry': | |
| pts = np.array([[cx-10, mouth_y+3], [cx, mouth_y], [cx+10, mouth_y+3]], np.int32) | |
| else: | |
| pts = np.array([[cx-8, mouth_y], [cx, mouth_y+2], [cx+8, mouth_y]], np.int32) | |
| if pts is not None: | |
| cv2.polylines(img, [pts], False, 50, 2) | |
| # Eyebrows β raised for Surprise/Fear, furrowed for Angry | |
| brow_y = eye_y - int(self.img_size * 0.1) | |
| for bx in [int(cx - self.img_size*0.18), int(cx + self.img_size*0.18)]: | |
| offset = -4 if emotion in ('Surprise','Fear') else (3 if emotion=='Angry' else 0) | |
| cv2.line(img, | |
| (bx - int(self.img_size*0.08), brow_y + offset), | |
| (bx + int(self.img_size*0.08), brow_y - offset), | |
| 40, 2) | |
| # Noise & contrast | |
| noise = np.random.normal(0, p['noise'] * 255, img.shape).astype(np.float32) | |
| img = np.clip(img * p['contrast'] * p['brightness'] + noise, 0, 255) | |
| # Augmentation jitter | |
| img = self._augment(img) | |
| return img.astype(np.uint8) | |
| def _augment(self, img): | |
| # Random flip | |
| if np.random.rand() > 0.5: | |
| img = np.fliplr(img) | |
| # Random rotation Β±10Β° | |
| angle = np.random.uniform(-10, 10) | |
| M = cv2.getRotationMatrix2D((self.img_size//2, self.img_size//2), angle, 1) | |
| img = cv2.warpAffine(img, M, (self.img_size, self.img_size)) | |
| # Random brightness shift | |
| img = np.clip(img + np.random.uniform(-20, 20), 0, 255) | |
| return img | |
| def generate(self): | |
| X, y = [], [] | |
| for emotion in EMOTIONS: | |
| n = self.counts[emotion] | |
| print(f" Generating {n:5d} samples for '{emotion}' β¦") | |
| for _ in range(n): | |
| X.append(self._generate_face(emotion)) | |
| y.append(EMOTIONS.index(emotion)) | |
| return np.array(X), np.array(y) | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| # 2. NUMPY CNN (no external DL framework) | |
| # βββββββββββββββββββββββββββββββββββββββββββββ | |
| class ConvLayer: | |
| """2-D convolution with ReLU, He init, no stride/dilation.""" | |
| def __init__(self, in_ch, out_ch, kernel=3, padding=1): | |
| scale = np.sqrt(2.0 / (in_ch * kernel * kernel)) | |
| self.W = np.random.randn(out_ch, in_ch, kernel, kernel).astype(np.float32) * scale | |
| self.b = np.zeros((out_ch, 1), dtype=np.float32) | |
| self.padding = padding | |
| self.kernel = kernel | |
| def _pad(self, X): | |
| p = self.padding | |
| return np.pad(X, ((0,0),(0,0),(p,p),(p,p)), mode='constant') if p else X | |
| def forward(self, X): | |
| self._X = X | |
| N, C, H, W_in = X.shape | |
| F, _, k, _ = self.W.shape | |
| Xp = self._pad(X) | |
| Ho, Wo = H, W_in # stride=1 + symmetric padding keeps size | |
| out = np.zeros((N, F, Ho, Wo), dtype=np.float32) | |
| for f in range(F): | |
| for c in range(C): | |
| for i in range(k): | |
| for j in range(k): | |
| out[:, f, :, :] += self.W[f, c, i, j] * Xp[:, c, i:i+Ho, j:j+Wo] | |
| out[:, f, :, :] += self.b[f] | |
| self._out = np.maximum(0, out) # ReLU | |
| return self._out | |
| def backward(self, dout): | |
| N, C, H, W_in = self._X.shape | |
| F, _, k, _ = self.W.shape | |
| dReLU = dout * (self._out > 0) | |
| Xp = self._pad(self._X) | |
| dXp = np.zeros_like(Xp) | |
| self.dW = np.zeros_like(self.W) | |
| self.db = np.zeros_like(self.b) | |
| Ho = Wo = H | |
| for f in range(F): | |
| self.db[f] = dReLU[:, f, :, :].sum() | |
| for c in range(C): | |
| for i in range(k): | |
| for j in range(k): | |
| self.dW[f,c,i,j] = (dReLU[:,f,:,:] * Xp[:,c,i:i+Ho,j:j+Wo]).sum() | |
| dXp[:,c,i:i+Ho,j:j+Wo] += self.W[f,c,i,j] * dReLU[:,f,:,:] | |
| p = self.padding | |
| dX = dXp[:, :, p:-p, p:-p] if p else dXp | |
| return dX | |
| class MaxPool2x2: | |
| def forward(self, X): | |
| self._X = X | |
| N,C,H,W = X.shape | |
| out = X.reshape(N, C, H//2, 2, W//2, 2).max(axis=(3,5)) | |
| self._out = out | |
| return out | |
| def backward(self, dout): | |
| N,C,H,W = self._X.shape | |
| Xr = self._X.reshape(N, C, H//2, 2, W//2, 2) | |
| mask = (Xr == self._out[:,:,:,np.newaxis,:,np.newaxis]) | |
| dXr = np.zeros_like(Xr) | |
| dXr[mask] = np.broadcast_to(dout[:,:,:,np.newaxis,:,np.newaxis], Xr.shape)[mask] | |
| return dXr.reshape(N, C, H, W) | |
| class BatchNorm: | |
| def __init__(self, C, eps=1e-5, momentum=0.9): | |
| self.gamma = np.ones( C, dtype=np.float32) | |
| self.beta = np.zeros(C, dtype=np.float32) | |
| self.rm = np.zeros(C, dtype=np.float32) # running mean | |
| self.rv = np.ones( C, dtype=np.float32) # running var | |
| self.eps = eps | |
| self.momentum= momentum | |
| self.training= True | |
| def forward(self, X): | |
| # X: (N, C, H, W) | |
| if self.training: | |
| mu = X.mean(axis=(0,2,3)) | |
| var = X.var(axis=(0,2,3)) | |
| self.rm = self.momentum*self.rm + (1-self.momentum)*mu | |
| self.rv = self.momentum*self.rv + (1-self.momentum)*var | |
| else: | |
| mu = self.rm | |
| var = self.rv | |
| self._mu = mu | |
| self._var = var | |
| Xn = (X - mu[None,:,None,None]) / np.sqrt(var[None,:,None,None] + self.eps) | |
| self._Xn = Xn | |
| return self.gamma[None,:,None,None]*Xn + self.beta[None,:,None,None] | |
| def backward(self, dout): | |
| N,C,H,W = dout.shape | |
| dgamma = (dout * self._Xn).sum(axis=(0,2,3)) | |
| dbeta = dout.sum(axis=(0,2,3)) | |
| dXn = dout * self.gamma[None,:,None,None] | |
| # simplified straight-through gradient | |
| dX = dXn / np.sqrt(self._var[None,:,None,None]+self.eps) | |
| self.dgamma = dgamma | |
| self.dbeta = dbeta | |
| return dX | |
| class Dropout: | |
| def __init__(self, p=0.5): | |
| self.p = p | |
| self.training= True | |
| def forward(self, X): | |
| if self.training: | |
| self._mask = (np.random.rand(*X.shape) > self.p) / (1 - self.p) | |
| return X * self._mask | |
| return X | |
| def backward(self, dout): | |
| return dout * self._mask if self.training else dout | |
| class Dense: | |
| def __init__(self, in_f, out_f): | |
| scale = np.sqrt(2.0 / in_f) | |
| self.W = np.random.randn(in_f, out_f).astype(np.float32) * scale | |
| self.b = np.zeros(out_f, dtype=np.float32) | |
| def forward(self, X): | |
| self._X = X | |
| return X @ self.W + self.b | |
| def backward(self, dout): | |
| self.dW = self._X.T @ dout | |
| self.db = dout.sum(axis=0) | |
| return dout @ self.W.T | |
| class Softmax: | |
| def forward(self, X): | |
| e = np.exp(X - X.max(axis=1, keepdims=True)) | |
| self._out = e / e.sum(axis=1, keepdims=True) | |
| return self._out | |
| def backward(self, y_oh): | |
| return (self._out - y_oh) / y_oh.shape[0] | |
| class EmotionCNN: | |
| """ | |
| Architecture: | |
| Conv(1β32,3Γ3) β BN β Pool | |
| Conv(32β64,3Γ3) β BN β Pool | |
| Conv(64β128,3Γ3) β BN β Pool | |
| Flatten | |
| Dense(128*6*6β256) β Dropout(0.5) | |
| Dense(256β128) β Dropout(0.3) | |
| Dense(128β7) β Softmax | |
| """ | |
| def __init__(self): | |
| self.layers = [ | |
| ConvLayer(1, 32), BatchNorm(32), MaxPool2x2(), | |
| ConvLayer(32, 64), BatchNorm(64), MaxPool2x2(), | |
| ConvLayer(64, 128), BatchNorm(128), MaxPool2x2(), | |
| ] | |
| flat = 128 * 6 * 6 | |
| self.fc1 = Dense(flat, 256) | |
| self.drop1 = Dropout(0.5) | |
| self.fc2 = Dense(256, 128) | |
| self.drop2 = Dropout(0.3) | |
| self.fc3 = Dense(128, NUM_CLASSES) | |
| self.sm = Softmax() | |
| self.history = {'train_loss':[], 'val_loss':[], 'train_acc':[], 'val_acc':[]} | |
| def _set_training(self, flag): | |
| for l in self.layers: | |
| if isinstance(l, (BatchNorm, Dropout)): | |
| l.training = flag | |
| self.drop1.training = flag | |
| self.drop2.training = flag | |
| def forward(self, X): | |
| out = X | |
| for l in self.layers: | |
| out = l.forward(out) | |
| N = out.shape[0] | |
| out = out.reshape(N, -1) | |
| out = np.maximum(0, self.fc1.forward(out)) | |
| out = self.drop1.forward(out) | |
| out = np.maximum(0, self.fc2.forward(out)) | |
| out = self.drop2.forward(out) | |
| out = self.fc3.forward(out) | |
| return self.sm.forward(out) | |
| def backward(self, y_oh, lr): | |
| dout = self.sm.backward(y_oh) | |
| dout = self.fc3.backward(dout) | |
| dout = self.drop2.backward(dout * (self.fc2.forward(self.fc2._X) > 0) if False else dout) | |
| dout = self.fc2.backward(dout) | |
| dout = self.drop1.backward(dout) | |
| dout = dout * (self.fc1._X @ self.fc1.W + self.fc1.b > 0) | |
| dout = self.fc1.backward(dout) | |
| N = self.layers[-1]._out.shape[0] | |
| dout = dout.reshape(N, 128, 6, 6) | |
| for l in reversed(self.layers): | |
| dout = l.backward(dout) | |
| self._update(lr) | |
| def _update(self, lr): | |
| """SGD with momentum (simplified: vanilla SGD here).""" | |
| for l in self.layers: | |
| if isinstance(l, ConvLayer): | |
| l.W -= lr * l.dW | |
| l.b -= lr * l.db | |
| elif isinstance(l, BatchNorm): | |
| l.gamma -= lr * l.dgamma | |
| l.beta -= lr * l.dbeta | |
| for fc in [self.fc1, self.fc2, self.fc3]: | |
| fc.W -= lr * fc.dW | |
| fc.b -= lr * fc.db | |
| def cross_entropy(self, probs, y_oh): | |
| return -np.mean(np.sum(y_oh * np.log(probs + 1e-9), axis=1)) | |
| def train_epoch(self, X, y_oh, lr, batch_size=BATCH_SIZE): | |
| self._set_training(True) | |
| idx = np.random.permutation(len(X)) | |
| X, y_oh = X[idx], y_oh[idx] | |
| losses, accs = [], [] | |
| for i in range(0, len(X), batch_size): | |
| Xb = X[i:i+batch_size] | |
| yb = y_oh[i:i+batch_size] | |
| p = self.forward(Xb) | |
| losses.append(self.cross_entropy(p, yb)) | |
| accs.append((p.argmax(1) == yb.argmax(1)).mean()) | |
| self.backward(yb, lr) | |
| return np.mean(losses), np.mean(accs) | |
| def evaluate(self, X, y_oh, batch_size=256): | |
| self._set_training(False) | |
| losses, accs = [], [] | |
| for i in range(0, len(X), batch_size): | |
| Xb = X[i:i+batch_size] | |
| yb = y_oh[i:i+batch_size] | |
| p = self.forward(Xb) | |
| losses.append(self.cross_entropy(p, yb)) | |
| accs.append((p.argmax(1) == yb.argmax(1)).mean()) | |
| return np.mean(losses), np.mean(accs) | |
| def predict(self, X): | |
| self._set_training(False) | |
| return self.forward(X) | |
| def save_weights(self, path): | |
| data = { | |
| 'conv_W': [l.W for l in self.layers if isinstance(l, ConvLayer)], | |
| 'conv_b': [l.b for l in self.layers if isinstance(l, ConvLayer)], | |
| 'bn_gamma': [l.gamma for l in self.layers if isinstance(l, BatchNorm)], | |
| 'bn_beta': [l.beta for l in self.layers if isinstance(l, BatchNorm)], | |
| 'fc1_W': self.fc1.W, 'fc1_b': self.fc1.b, | |
| 'fc2_W': self.fc2.W, 'fc2_b': self.fc2.b, | |
| 'fc3_W': self.fc3.W, 'fc3_b': self.fc3.b, | |
| 'history': self.history, | |
| } | |
| np.save(path, data, allow_pickle=True) | |
| print(f" β Weights saved β {path}") | |
| def load_weights(self, path): | |
| data = np.load(path, allow_pickle=True).item() | |
| convs = [l for l in self.layers if isinstance(l, ConvLayer)] | |
| bns = [l for l in self.layers if isinstance(l, BatchNorm)] | |
| for l, W, b in zip(convs, data['conv_W'], data['conv_b']): | |
| l.W, l.b = W, b | |
| for l, g, bt in zip(bns, data['bn_gamma'], data['bn_beta']): | |
| l.gamma, l.beta = g, bt | |
| self.fc1.W, self.fc1.b = data['fc1_W'], data['fc1_b'] | |
| self.fc2.W, self.fc2.b = data['fc2_W'], data['fc2_b'] | |
| self.fc3.W, self.fc3.b = data['fc3_W'], data['fc3_b'] | |
| self.history = data.get('history', self.history) | |
| print(f" β Weights loaded β {path}") | |