Asmitha3 commited on
Commit
5de67dd
·
verified ·
1 Parent(s): 9002522

Upload train_model.py

Browse files
Files changed (1) hide show
  1. train_model.py +59 -0
train_model.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ # --- FIX: Set environment variable to prevent Protobuf/TensorFlow crash ---
3
+ os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'
4
+ # -----------------------------------------------------------------------
5
+
6
+ import numpy as np
7
+ from tensorflow.keras.models import Sequential
8
+ from tensorflow.keras.layers import LSTM, Dense
9
+ from tensorflow.keras.utils import to_categorical
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.metrics import accuracy_score
12
+
13
+ # --- 1. Data Loading and Setup ---
14
+ DATA_PATH = os.path.join('ML_Data')
15
+ ACTIONS = np.array(sorted(os.listdir(DATA_PATH)))
16
+ SEQUENCE_LENGTH = 20
17
+ label_map = {label:num for num, label in enumerate(ACTIONS)}
18
+ NUM_CLASSES = len(ACTIONS)
19
+
20
+ sequences, labels = [], []
21
+ for action in ACTIONS:
22
+ for sequence in range(15):
23
+ window = []
24
+ for frame_num in range(SEQUENCE_LENGTH):
25
+ try:
26
+ # Load the 63 features (21 landmarks * 3 coords)
27
+ res = np.load(os.path.join(DATA_PATH, action, str(sequence), f"{frame_num}.npy"))
28
+ window.append(res)
29
+ except:
30
+ continue
31
+ if len(window) == SEQUENCE_LENGTH:
32
+ sequences.append(window)
33
+ labels.append(label_map[action])
34
+
35
+ X = np.array(sequences)
36
+ y = to_categorical(labels).astype(int)
37
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05)
38
+
39
+ # --- 2. Define the Neural Network Model (LSTM) ---
40
+ model = Sequential()
41
+ model.add(LSTM(64, return_sequences=True, activation='relu', input_shape=(SEQUENCE_LENGTH, 63)))
42
+ model.add(LSTM(128, return_sequences=True, activation='relu'))
43
+ model.add(LSTM(64, return_sequences=False, activation='relu'))
44
+ model.add(Dense(64, activation='relu'))
45
+ model.add(Dense(32, activation='relu'))
46
+ model.add(Dense(NUM_CLASSES, activation='softmax'))
47
+
48
+ # --- 3. Compile, Train, and Save ---
49
+ model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'])
50
+ print(f"Starting Training for {NUM_CLASSES} signs...")
51
+
52
+ model.fit(X_train, y_train, epochs=100, callbacks=[])
53
+
54
+ res = model.predict(X_test)
55
+ y_pred = np.argmax(res, axis=1)
56
+ y_true = np.argmax(y_test, axis=1)
57
+ print(f"\nModel Accuracy on Test Data: {accuracy_score(y_true, y_pred)*100:.2f}%")
58
+ model.save('/tmp/sign_language_model.h5')
59
+ print("Model trained and saved as sign_language_model.h5")