Spaces:
Sleeping
Sleeping
Create train_model.py
Browse files- train_model.py +52 -0
train_model.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
from tensorflow.keras.models import Sequential
|
4 |
+
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
|
5 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
6 |
+
from tensorflow.keras.optimizers import Adam
|
7 |
+
|
8 |
+
# Set paths to the dataset (adjust paths based on your directory structure)
|
9 |
+
train_dir = './data/train'
|
10 |
+
validation_dir = './data/validation'
|
11 |
+
|
12 |
+
# Define the CNN model
|
13 |
+
def create_cnn_model(input_shape=(224, 224, 3)):
|
14 |
+
model = Sequential()
|
15 |
+
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
|
16 |
+
model.add(MaxPooling2D((2, 2)))
|
17 |
+
|
18 |
+
model.add(Conv2D(64, (3, 3), activation='relu'))
|
19 |
+
model.add(MaxPooling2D((2, 2)))
|
20 |
+
|
21 |
+
model.add(Conv2D(128, (3, 3), activation='relu'))
|
22 |
+
model.add(MaxPooling2D((2, 2)))
|
23 |
+
|
24 |
+
model.add(Flatten())
|
25 |
+
model.add(Dense(128, activation='relu'))
|
26 |
+
model.add(Dense(1, activation='sigmoid')) # Binary classification (Normal vs Abnormal)
|
27 |
+
|
28 |
+
model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])
|
29 |
+
return model
|
30 |
+
|
31 |
+
# Create the CNN model
|
32 |
+
model = create_cnn_model()
|
33 |
+
|
34 |
+
# ImageDataGenerator for training and validation
|
35 |
+
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=40, width_shift_range=0.2,
|
36 |
+
height_shift_range=0.2, shear_range=0.2, zoom_range=0.2,
|
37 |
+
horizontal_flip=True, fill_mode='nearest')
|
38 |
+
|
39 |
+
validation_datagen = ImageDataGenerator(rescale=1./255)
|
40 |
+
|
41 |
+
# Flow training and validation data from directories
|
42 |
+
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(224, 224),
|
43 |
+
batch_size=32, class_mode='binary')
|
44 |
+
|
45 |
+
validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(224, 224),
|
46 |
+
batch_size=32, class_mode='binary')
|
47 |
+
|
48 |
+
# Train the model
|
49 |
+
history = model.fit(train_generator, epochs=10, validation_data=validation_generator)
|
50 |
+
|
51 |
+
# Save the trained model
|
52 |
+
model.save('classification_model.h5')
|