-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
85 lines (69 loc) · 2.63 KB
/
train.py
File metadata and controls
85 lines (69 loc) · 2.63 KB
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
# -*- coding: utf-8 -*-
"""train.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1m_MwpBggmETJ3cK3kfpG0Hj2t-eIYKqx
"""
import cv2
import os
import numpy as np
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
#Preprocessing Function
def preprocess_image(img_path, target_size=(32, 32)):
img = cv2.imread(img_path)
img_resized = cv2.resize(img, target_size)
return img_resized
#This is Google Collab Formatting
image_dir_positive = "/content/Positive"
image_dir_negative = "/content/Negative"
output_dir = "/content/Preprocessed"
preprocessed_images = []
labels = []
#Importing Positive Files
for filename in os.listdir(image_dir_positive):
if filename.endswith(".jpg"):
img_path = os.path.join(image_dir_positive, filename)
preprocessed_img = preprocess_image(img_path)
preprocessed_images.append(preprocessed_img)
label = 1 #Positive Label
labels.append(int(label))
output_path = os.path.join(output_dir, filename)
cv2.imwrite(output_path, preprocessed_img)
#Importing Negative Files
for filename in os.listdir(image_dir_negative):
if filename.endswith(".jpg"):
img_path = os.path.join(image_dir_negative, filename)
preprocessed_img = preprocess_image(img_path)
preprocessed_images.append(preprocessed_img)
label = 0 #Negative Label
labels.append(int(label))
output_path = os.path.join(output_dir, filename)
cv2.imwrite(output_path, preprocessed_img)
# Convert the list of images and labels to NumPy arrays
dataset = np.array(preprocessed_images)
labels = np.array(labels)
np.savez("/content/preprocess.npz", dataset=dataset, labels=labels)
X_train, X_test, y_train, y_test = train_test_split(dataset, labels, test_size=0.2, random_state=42)
#Very Simplistic CNN model
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid')
])
#Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
#Train the model
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))
#Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print("Test Loss:", loss)
print("Test Accuracy:", accuracy)
#Save the model
model.save("Homework4_ImageModel.h5")