Prime810 commited on
Commit
db8c322
·
verified ·
1 Parent(s): 4e386e1

Update Training/Code/train.py

Browse files
Files changed (1) hide show
  1. Training/Code/train.py +57 -72
Training/Code/train.py CHANGED
@@ -1,72 +1,57 @@
1
- # Importing Libraries
2
- import os
3
- import numpy as np
4
- import cv2
5
- from keras.models import Sequential
6
- from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Input
7
- from keras.optimizers import Adam
8
- from keras_preprocessing.image import ImageDataGenerator
9
- from keras.callbacks import EarlyStopping, ModelCheckpoint
10
-
11
- # Define paths using os.path for portability
12
- base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
13
- train_dir = os.path.join(base_dir, 'Data/train')
14
- val_dir = os.path.join(base_dir, 'Data/test')
15
-
16
- # Data augmentation and rescaling
17
- train_datagen = ImageDataGenerator(
18
- rescale=1./255,
19
- rotation_range=30,
20
- zoom_range=0.2,
21
- horizontal_flip=True,
22
- shear_range=0.2,
23
- width_shift_range=0.2,
24
- height_shift_range=0.2
25
- )
26
- val_datagen = ImageDataGenerator(rescale=1./255)
27
-
28
- train_generator = train_datagen.flow_from_directory(
29
- train_dir, target_size=(48, 48), batch_size=64, color_mode='grayscale', class_mode='categorical')
30
-
31
- validation_generator = val_datagen.flow_from_directory(
32
- val_dir, target_size=(48, 48), batch_size=64, color_mode='grayscale', class_mode='categorical')
33
-
34
- # Building the Convolutional Network Architecture
35
- emotion_model = Sequential()
36
- emotion_model.add(Input(shape=(48, 48, 1)))
37
- emotion_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu'))
38
- emotion_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
39
- emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
40
- emotion_model.add(Dropout(0.25))
41
-
42
- emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
43
- emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
44
- emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
45
- emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
46
- emotion_model.add(Dropout(0.25))
47
-
48
- emotion_model.add(Flatten())
49
- emotion_model.add(Dense(1024, activation='relu'))
50
- emotion_model.add(Dropout(0.5))
51
- emotion_model.add(Dense(7, activation='softmax'))
52
-
53
- # Compile the model
54
- emotion_model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=0.0001), metrics=['accuracy'])
55
-
56
- # Define callbacks
57
- callbacks = [
58
- EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True),
59
- ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)
60
- ]
61
-
62
- # Train the model
63
- emotion_model_info = emotion_model.fit(
64
- train_generator,
65
- epochs=50,
66
- validation_data=validation_generator,
67
- callbacks=callbacks
68
- )
69
-
70
- # Save the full model
71
- emotion_model.save("emotion_model.keras")
72
-
 
1
+ import os
2
+ import numpy as np
3
+ from keras.models import Model
4
+ from keras.layers import Dense, Dropout, GlobalAveragePooling2D, Input
5
+ from keras.optimizers import Adam
6
+ from keras_preprocessing.image import ImageDataGenerator
7
+ from keras.applications import MobileNetV2
8
+ from keras.callbacks import EarlyStopping, ModelCheckpoint
9
+
10
+ # Define paths
11
+ base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
12
+ train_dir = os.path.join(base_dir, 'Data/train')
13
+ val_dir = os.path.join(base_dir, 'Data/test')
14
+
15
+ # Image generators with augmentation
16
+ train_datagen = ImageDataGenerator(
17
+ rescale=1./255,
18
+ rotation_range=30,
19
+ zoom_range=0.2,
20
+ horizontal_flip=True,
21
+ shear_range=0.2,
22
+ width_shift_range=0.2,
23
+ height_shift_range=0.2
24
+ )
25
+ val_datagen = ImageDataGenerator(rescale=1./255)
26
+
27
+ train_generator = train_datagen.flow_from_directory(
28
+ train_dir, target_size=(96, 96), batch_size=32, color_mode='rgb', class_mode='categorical')
29
+
30
+ validation_generator = val_datagen.flow_from_directory(
31
+ val_dir, target_size=(96, 96), batch_size=32, color_mode='rgb', class_mode='categorical')
32
+
33
+ # Load base model
34
+ base_model = MobileNetV2(include_top=False, input_shape=(96, 96, 3), weights='imagenet')
35
+ base_model.trainable = False # Freeze base layers
36
+
37
+ # Add custom layers
38
+ x = base_model.output
39
+ x = GlobalAveragePooling2D()(x)
40
+ x = Dense(256, activation='relu')(x)
41
+ x = Dropout(0.5)(x)
42
+ predictions = Dense(7, activation='softmax')(x)
43
+
44
+ model = Model(inputs=base_model.input, outputs=predictions)
45
+ model.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
46
+
47
+ # Callbacks
48
+ callbacks = [
49
+ EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True),
50
+ ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)
51
+ ]
52
+
53
+ # Train the model
54
+ model.fit(train_generator, validation_data=validation_generator, epochs=30, callbacks=callbacks)
55
+
56
+ # Save model
57
+ model.save("emotion_model.keras")