-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageClassification
More file actions
152 lines (104 loc) · 4.57 KB
/
ImageClassification
File metadata and controls
152 lines (104 loc) · 4.57 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
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
import tensorflow as tf
from keras.utils import to_categorical
from tensorflow.python.data import AUTOTUNE
from keras.models import load_model
from keras import layers
from keras.applications import EfficientNetB0
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.optimizers import SGD
from keras.applications import imagenet_utils
from sklearn.metrics import classification_report
import imutils
from imutils import paths
import random
import cv2
import os
import numpy as np
import pandas as pd
import shutil
import matplotlib.pyplot as plt
main_path = '...\\A\\Desktop\\Day\\aDay\\trayDataset\\'
all_images = list(paths.list_images(main_path))
random_images = random.choices(all_images, k=3)
for i in random_images:
random_image = cv2.imread(i)
random_images = cv2.cvtColor(random_image, cv2.COLOR_BGR2RGB)
random_image = imutils.resize(random_image, height=400)
cv2.imshow("example", random_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
random.shuffle(all_images)
i = int(len(all_images)*0.8)
trainData = all_images[:i]
testData = all_images[i:]
i = int(len(trainData)*0.10)
validData = trainData[:i]
trainData = trainData[i:]
train_path = main_path+'training'
test_path = main_path+'test'
valid_path = main_path+'valid'
datasets = [("training", trainData, train_path ), ("validation", validData, valid_path), ("testing", testData, test_path)]
for (dtype, imagepaths, out_path) in datasets:
if not os.path.exists(out_path):
os.makedirs(out_path)
for inputpath in imagepaths:
filename = inputpath.split(os.path.sep)[-1]
label = inputpath.split(os.path.sep)[-2]
labelPath = os.path.sep.join([out_path, label])
if not os.path.exists(labelPath):
os.makedirs(labelPath)
p = os.path.sep.join([labelPath, filename])
shutil.copy2(inputpath, p)
def load_images(imagePath):
image = tf.io.read_file(imagePath)
image = tf.io.decode_jpeg(image, channels=3)
image = tf.image.resize(image, (48, 48)) / 255.0
label = tf.strings.split(imagePath, os.path.sep)[-2]
label = tf.strings.to_number(label, tf.int32)
print(label)
return (image, label)
def augment(image, label):
image = tf.image.random_flip_up_down(image)
image = tf.image.random_flip_left_right(image)
image = tf.image.random_brightness(image,0.2)
return (image, label)
trainPaths = list(paths.list_images(train_path))
valPaths = list(paths.list_images(valid_path))
testPaths = list(paths.list_images(test_path))
trainDS = tf.data.Dataset.from_tensor_slices(trainPaths)
trainDS = (trainDS.shuffle(len(trainPaths)).map(load_images, num_parallel_calls=AUTOTUNE).map(augment,num_parallel_calls=AUTOTUNE).cache().batch(64).prefetch(AUTOTUNE))
valDS = tf.data.Dataset.from_tensor_slices(valPaths)
valDS = (valDS.map(load_images, num_parallel_calls=AUTOTUNE).cache().batch(64).prefetch(AUTOTUNE))
testDS = tf.data.Dataset.from_tensor_slices(testPaths)
testDS = (testDS.map(load_images, num_parallel_calls=AUTOTUNE).cache().batch(64).prefetch(AUTOTUNE))
NUM_CLASSES = 2
IMG_SIZE = 48
size = (IMG_SIZE, IMG_SIZE,3)
inputs = layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))
model = EfficientNetB0(include_top=False, input_shape=size)
flat1 = layers.Flatten()(model.layers[-1].output)
class1 = layers.Dense(1024, activation='relu')(flat1)
output = layers.Dense(1, activation='sigmoid')(class1)
model = tf.keras.Model(inputs=model.inputs, outputs=output)
model.summary()
opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
early_s = EarlyStopping(monitor="val_loss", patience = 10, restore_best_weights=True)
save_b = ModelCheckpoint(filepath ="...\\A\\Desktop\\Gun\\", monitor="val_loss", verbose = 1 )
callbacks = [early_s, save_b]
hist = model.fit(x = trainDS, validation_data=valDS, epochs= 15, callbacks=callbacks, verbose=1)
plt.figure()
plt.plot(hist.history["loss"], label="train_loss")
plt.plot(hist.history["val_loss"], label="val_loss")
plt.plot(hist.history["accuracy"], label="train_acc")
plt.plot(hist.history["val_accuracy"], label="val_acc")
plt.title("training loss and accuracy")
plt.xlabel("Epoch #")
plt.ylabel("loss/accuracy")
plt.legend(loc="lower left")
plt.show()
test_paths = list(paths.list_images(test_path))
testlabels = [int(p.split(os.path.sep)[-2]) for p in test_paths]
testlabels = to_categorical(testlabels)
predictions = model.predict(testDS)
print(classification_report(testlabels.argmax(axis=1), predictions.argmax(axis=1), target_names=["0", "1"]))