File size: 13,075 Bytes
c3893d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"""
Deep learning models for respiratory disease detection.
Includes CNN and LSTM architectures.
"""

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, models, callbacks
from tensorflow.keras.utils import to_categorical
from typing import Tuple, Optional, Dict
import pickle
from pathlib import Path


class CNNModel:
    """Convolutional Neural Network for audio classification."""
    
    def __init__(self, input_shape: Tuple, num_classes: int, model_name: str = "cnn_model"):
        """
        Initialize CNN model.
        
        Args:
            input_shape: Shape of input (height, width, channels)
            num_classes: Number of output classes
            model_name: Name of the model
        """
        self.input_shape = input_shape
        self.num_classes = num_classes
        self.model_name = model_name
        self.model = None
        self.history = None
    
    def build_model(self, dropout_rate: float = 0.3):
        """
        Build CNN architecture.
        
        Args:
            dropout_rate: Dropout rate for regularization
        """
        model = models.Sequential(name=self.model_name)
        
        # First convolutional block
        model.add(layers.Conv2D(32, (3, 3), activation='relu', 
                               padding='same', input_shape=self.input_shape))
        model.add(layers.BatchNormalization())
        model.add(layers.MaxPooling2D((2, 2)))
        model.add(layers.Dropout(dropout_rate))
        
        # Second convolutional block
        model.add(layers.Conv2D(64, (3, 3), activation='relu', padding='same'))
        model.add(layers.BatchNormalization())
        model.add(layers.MaxPooling2D((2, 2)))
        model.add(layers.Dropout(dropout_rate))
        
        # Third convolutional block
        model.add(layers.Conv2D(128, (3, 3), activation='relu', padding='same'))
        model.add(layers.BatchNormalization())
        model.add(layers.MaxPooling2D((2, 2)))
        model.add(layers.Dropout(dropout_rate))
        
        # Fourth convolutional block
        model.add(layers.Conv2D(256, (3, 3), activation='relu', padding='same'))
        model.add(layers.BatchNormalization())
        model.add(layers.GlobalAveragePooling2D())
        
        # Dense layers
        model.add(layers.Dense(256, activation='relu'))
        model.add(layers.Dropout(dropout_rate))
        model.add(layers.Dense(128, activation='relu'))
        model.add(layers.Dropout(dropout_rate))
        
        # Output layer
        if self.num_classes == 2:
            model.add(layers.Dense(1, activation='sigmoid'))
        else:
            model.add(layers.Dense(self.num_classes, activation='softmax'))
        
        self.model = model
        print(f"\n{self.model_name} architecture:")
        self.model.summary()
        
        return model
    
    def compile_model(self, learning_rate: float = 0.001):
        """Compile the model."""
        if self.model is None:
            raise ValueError("Model must be built before compilation")
        
        optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
        
        if self.num_classes == 2:
            loss = 'binary_crossentropy'
            metrics = ['accuracy', keras.metrics.AUC(name='auc')]
        else:
            loss = 'sparse_categorical_crossentropy'
            metrics = ['accuracy']
        
        self.model.compile(
            optimizer=optimizer,
            loss=loss,
            metrics=metrics
        )
        
        print(f"Model compiled with optimizer={optimizer.__class__.__name__}, loss={loss}")
    
    def train(self, X_train: np.ndarray, y_train: np.ndarray,
              X_val: np.ndarray, y_val: np.ndarray,
              epochs: int = 50, batch_size: int = 32,
              model_dir: str = 'models'):
        """
        Train the CNN model.
        
        Args:
            X_train: Training features
            y_train: Training labels
            X_val: Validation features
            y_val: Validation labels
            epochs: Number of training epochs
            batch_size: Batch size
            model_dir: Directory to save model checkpoints
        """
        if self.model is None:
            raise ValueError("Model must be built and compiled before training")
        
        # Create model directory
        model_path = Path(model_dir)
        model_path.mkdir(parents=True, exist_ok=True)
        
        # Define callbacks
        checkpoint_path = model_path / f"{self.model_name}_best.keras"
        callbacks_list = [
            callbacks.ModelCheckpoint(
                str(checkpoint_path),
                monitor='val_loss',
                save_best_only=True,
                verbose=1
            ),
            callbacks.EarlyStopping(
                monitor='val_loss',
                patience=10,
                restore_best_weights=True,
                verbose=1
            ),
            callbacks.ReduceLROnPlateau(
                monitor='val_loss',
                factor=0.5,
                patience=5,
                min_lr=1e-7,
                verbose=1
            )
        ]
        
        print(f"\nTraining {self.model_name}...")
        print(f"Training samples: {len(X_train)}, Validation samples: {len(X_val)}")
        print(f"Epochs: {epochs}, Batch size: {batch_size}")
        
        # Train model
        self.history = self.model.fit(
            X_train, y_train,
            validation_data=(X_val, y_val),
            epochs=epochs,
            batch_size=batch_size,
            callbacks=callbacks_list,
            verbose=1
        )
        
        print(f"\nTraining complete. Best model saved to {checkpoint_path}")
        
        return self.history
    
    def evaluate(self, X_test: np.ndarray, y_test: np.ndarray) -> Dict:
        """Evaluate model on test set."""
        if self.model is None:
            raise ValueError("Model must be trained before evaluation")
        
        print(f"\nEvaluating {self.model_name}...")
        results = self.model.evaluate(X_test, y_test, verbose=1)
        
        # Get predictions
        y_pred_proba = self.model.predict(X_test)
        
        if self.num_classes == 2:
            y_pred = (y_pred_proba > 0.5).astype(int).flatten()
        else:
            y_pred = np.argmax(y_pred_proba, axis=1)
        
        evaluation_results = {
            'loss': results[0],
            'accuracy': results[1],
            'predictions': y_pred,
            'probabilities': y_pred_proba
        }
        
        if len(results) > 2:
            evaluation_results['auc'] = results[2]
        
        print(f"Test Loss: {results[0]:.4f}")
        print(f"Test Accuracy: {results[1]:.4f}")
        
        return evaluation_results
    
    def save(self, filepath: str):
        """Save model to disk."""
        self.model.save(filepath)
        print(f"Model saved to {filepath}")
    
    @classmethod
    def load(cls, filepath: str):
        """Load model from disk."""
        model = keras.models.load_model(filepath)
        print(f"Model loaded from {filepath}")
        return model


class LSTMModel:
    """LSTM model for sequential audio classification."""
    
    def __init__(self, input_shape: Tuple, num_classes: int, model_name: str = "lstm_model"):
        """
        Initialize LSTM model.
        
        Args:
            input_shape: Shape of input (time_steps, features)
            num_classes: Number of output classes
            model_name: Name of the model
        """
        self.input_shape = input_shape
        self.num_classes = num_classes
        self.model_name = model_name
        self.model = None
        self.history = None
    
    def build_model(self, dropout_rate: float = 0.3):
        """
        Build LSTM architecture.
        
        Args:
            dropout_rate: Dropout rate for regularization
        """
        model = models.Sequential(name=self.model_name)
        
        # LSTM layers
        model.add(layers.LSTM(128, return_sequences=True, input_shape=self.input_shape))
        model.add(layers.Dropout(dropout_rate))
        model.add(layers.BatchNormalization())
        
        model.add(layers.LSTM(64, return_sequences=True))
        model.add(layers.Dropout(dropout_rate))
        model.add(layers.BatchNormalization())
        
        model.add(layers.LSTM(32))
        model.add(layers.Dropout(dropout_rate))
        
        # Dense layers
        model.add(layers.Dense(64, activation='relu'))
        model.add(layers.Dropout(dropout_rate))
        
        # Output layer
        if self.num_classes == 2:
            model.add(layers.Dense(1, activation='sigmoid'))
        else:
            model.add(layers.Dense(self.num_classes, activation='softmax'))
        
        self.model = model
        print(f"\n{self.model_name} architecture:")
        self.model.summary()
        
        return model
    
    def compile_model(self, learning_rate: float = 0.001):
        """Compile the model."""
        if self.model is None:
            raise ValueError("Model must be built before compilation")
        
        optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
        
        if self.num_classes == 2:
            loss = 'binary_crossentropy'
            metrics = ['accuracy', keras.metrics.AUC(name='auc')]
        else:
            loss = 'sparse_categorical_crossentropy'
            metrics = ['accuracy']
        
        self.model.compile(
            optimizer=optimizer,
            loss=loss,
            metrics=metrics
        )
        
        print(f"Model compiled with optimizer={optimizer.__class__.__name__}, loss={loss}")
    
    def train(self, X_train: np.ndarray, y_train: np.ndarray,
              X_val: np.ndarray, y_val: np.ndarray,
              epochs: int = 50, batch_size: int = 32,
              model_dir: str = 'models'):
        """Train the LSTM model."""
        if self.model is None:
            raise ValueError("Model must be built and compiled before training")
        
        # Create model directory
        model_path = Path(model_dir)
        model_path.mkdir(parents=True, exist_ok=True)
        
        # Define callbacks
        checkpoint_path = model_path / f"{self.model_name}_best.keras"
        callbacks_list = [
            callbacks.ModelCheckpoint(
                str(checkpoint_path),
                monitor='val_loss',
                save_best_only=True,
                verbose=1
            ),
            callbacks.EarlyStopping(
                monitor='val_loss',
                patience=10,
                restore_best_weights=True,
                verbose=1
            ),
            callbacks.ReduceLROnPlateau(
                monitor='val_loss',
                factor=0.5,
                patience=5,
                min_lr=1e-7,
                verbose=1
            )
        ]
        
        print(f"\nTraining {self.model_name}...")
        print(f"Training samples: {len(X_train)}, Validation samples: {len(X_val)}")
        
        # Train model
        self.history = self.model.fit(
            X_train, y_train,
            validation_data=(X_val, y_val),
            epochs=epochs,
            batch_size=batch_size,
            callbacks=callbacks_list,
            verbose=1
        )
        
        print(f"\nTraining complete. Best model saved to {checkpoint_path}")
        
        return self.history
    
    def evaluate(self, X_test: np.ndarray, y_test: np.ndarray) -> Dict:
        """Evaluate model on test set."""
        if self.model is None:
            raise ValueError("Model must be trained before evaluation")
        
        print(f"\nEvaluating {self.model_name}...")
        results = self.model.evaluate(X_test, y_test, verbose=1)
        
        # Get predictions
        y_pred_proba = self.model.predict(X_test)
        
        if self.num_classes == 2:
            y_pred = (y_pred_proba > 0.5).astype(int).flatten()
        else:
            y_pred = np.argmax(y_pred_proba, axis=1)
        
        evaluation_results = {
            'loss': results[0],
            'accuracy': results[1],
            'predictions': y_pred,
            'probabilities': y_pred_proba
        }
        
        if len(results) > 2:
            evaluation_results['auc'] = results[2]
        
        print(f"Test Loss: {results[0]:.4f}")
        print(f"Test Accuracy: {results[1]:.4f}")
        
        return evaluation_results
    
    def save(self, filepath: str):
        """Save model to disk."""
        self.model.save(filepath)
        print(f"Model saved to {filepath}")
    
    @classmethod
    def load(cls, filepath: str):
        """Load model from disk."""
        model = keras.models.load_model(filepath)
        print(f"Model loaded from {filepath}")
        return model


if __name__ == "__main__":
    print("Deep learning models module loaded successfully")
    print("Available models: CNNModel, LSTMModel")