-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestnet50.py
198 lines (164 loc) · 7.32 KB
/
restnet50.py
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
# -*- coding: utf-8 -*-
"""restnet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1XetosiGq5Ytpperu9shCCDG5N4KcvEca
! pip install -q kaggle
from google.colab import files
files.upload()
! mkdir ~/.kaggle
! cp kaggle.json ~/.kaggle/
! chmod 600 ~/.kaggle/kaggle.json
!kaggle datasets download -d crowww/a-large-scale-fish-dataset
!unzip a-large-scale-fish-dataset.zip
"""
!pip install wandb -q
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import os
import seaborn
import wandb
from wandb.keras import WandbCallback
from PIL import Image
from tqdm import tqdm
import warnings
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import seaborn as sns
from sklearn.metrics import classification_report, confusion_matrix
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
warnings.filterwarnings("ignore")
os.environ['KAGGLE_CONFIG_DIR'] = "../input/a-large-scale-fish-dataset"
plt.style.use("seaborn-darkgrid")
sns.set_context("paper", font_scale=1.4)
BATCH_SIZE = 32
EPOCHS = 100
LEARNING_RATE = 0.001
RANDOM_STATE = 42
LOSS = "categorical_crossentropy"
OPTIMIZER = "adam"
METRICS = [
"accuracy",
"precision",
"recall"
]
def get_dataset():
main_directory = "/content/Fish_Dataset/Fish_Dataset"
images = []
labels = []
for directory in tqdm(os.listdir(main_directory)):
next_directory = f"{main_directory}/{directory}"
if directory in ["README.txt", "license.txt", "Segmentation_example_script.m"]:
continue
for images_directory in os.listdir(next_directory):
if "GT" not in images_directory:
final_directory = f"{next_directory}/{images_directory}"
for image in os.listdir(final_directory):
images.append(np.array(Image.open(f"{final_directory}/{image}").resize((224, 224))))
labels.append(images_directory)
images = np.array(images)
labels = np.array(labels)
return images, labels
def plot_training_images(images, labels):
plot_images = []
plot_labels = []
for i, j in zip(images, labels):
if j in plot_labels:
continue
else:
plot_images.append(i)
plot_labels.append(j)
fig, axes = plt.subplots(nrows = 3, ncols = 3, sharex=False, figsize=(12, 12))
for i in range(3):
for j in range(3):
axes[i][j].imshow(plot_images[i * 3 + j])
axes[i][j].set_xlabel(plot_labels[i * 3 + j])
axes[i][j].set_xticks([])
axes[i][j].set_yticks([])
plt.tight_layout()
plt.show()
def get_tf_dataset(images, labels):
return tf.data.Dataset.from_tensor_slices((images, labels)).batch(BATCH_SIZE).prefetch(1)
def split_dataset(images, labels, test_size = 0.2, valid_size = 0.2):
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size = test_size, random_state = RANDOM_STATE)
train_images, valid_images, train_labels, valid_labels = train_test_split(train_images, train_labels, test_size = valid_size, random_state = RANDOM_STATE)
return (train_images, train_labels), (valid_images, valid_labels), (test_images, test_labels)
def plot_cm(test_labels, prediction_labels, encoder):
plt.figure(figsize=(15, 15))
cm = confusion_matrix(test_labels, prediction_labels)
df_cm = pd.DataFrame(cm, index = [i for i in encoder.categories_[0]],
columns = [i for i in encoder.categories_[0]])
sns.set(font_scale=1.4)
sns.heatmap(df_cm, annot=True, annot_kws={"size": 16}, fmt='g')
plt.show()
def plot_history(history):
fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize=(20, 10))
# Training
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["loss"], ax = axes[0][0])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["accuracy"], ax = axes[0][1])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["precision"], ax = axes[1][0])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["recall"], ax = axes[1][1])
# Validation
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["val_loss"], ax = axes[0][0])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["val_accuracy"], ax = axes[0][1])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["val_precision"], ax = axes[1][0])
sns.lineplot(range(1, len(history.history["loss"]) + 1), history.history["val_recall"], ax = axes[1][1])
axes[0][0].set_title("Loss Comparison", fontdict = {'fontsize': 20})
axes[0][0].set_xlabel("Epoch")
axes[0][0].set_ylabel("Loss")
axes[0][1].set_title("Accuracy Comparison", fontdict = {'fontsize': 20})
axes[0][1].set_xlabel("Epoch")
axes[0][1].set_ylabel("Accuracy")
axes[1][0].set_title("Precision Comparison", fontdict = {'fontsize': 20})
axes[1][0].set_xlabel("Epoch")
axes[1][0].set_ylabel("Precision")
axes[1][1].set_title("Recall Comparison", fontdict = {'fontsize': 20})
axes[1][1].set_xlabel("Epoch")
axes[1][1].set_ylabel("Recall")
plt.tight_layout()
plt.show()
def get_resnet(categories):
conv_block = tf.keras.applications.resnet.ResNet50(include_top = False, weights = "imagenet")
output = tf.keras.layers.GlobalAveragePooling2D()(conv_block.output)
output = tf.keras.layers.Dense(categories, activation = "softmax")(output)
model = tf.keras.Model(inputs = [conv_block.input], outputs = [output])
return model, "ResNet50"
images, labels = get_dataset()
(train_images, train_labels), (valid_images, valid_labels), (test_images, test_labels) = split_dataset(images, labels)
encoder = OneHotEncoder(sparse = False)
train_labels = encoder.fit_transform(train_labels.reshape(-1, 1))
valid_labels = encoder.transform(valid_labels.reshape(-1, 1))
test_labels = encoder.transform(test_labels.reshape(-1, 1))
train_dataset = get_tf_dataset(train_images, train_labels)
valid_dataset = get_tf_dataset(valid_images, valid_labels)
plot_training_images(train_images, encoder.inverse_transform(train_labels).reshape(-1,))
model, model_name = get_resnet(len(encoder.categories_[0]))
config_defaults = {
"learning_rate": LEARNING_RATE,
"epochs": EPOCHS,
"batch_size": BATCH_SIZE,
"model_name": model_name,
"loss": LOSS,
"random_state": RANDOM_STATE,
"optimizer": OPTIMIZER,
"metrics": METRICS
}
wandb.init(project="Fish_Dataset_Classification", id="resnet50", config = config_defaults)
model.compile(loss = LOSS, optimizer = OPTIMIZER, metrics = ["accuracy", tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
history = model.fit(train_dataset,
validation_data = valid_dataset,
batch_size = BATCH_SIZE,
epochs = 20,
callbacks = [tf.keras.callbacks.EarlyStopping(monitor = "val_accuracy", patience = 5, restore_best_weights = True), WandbCallback(save_model=False, save_graph=False)])
result_inter = model.predict(test_images)
prediction_index = np.argmax(result_inter, axis = -1)
result = np.zeros(shape = test_labels.shape, dtype = test_labels.dtype)
for i in range(result.shape[0]):
result[i][prediction_index[i]] = 1.0
test_labels = encoder.inverse_transform(test_labels)
prediction_labels = encoder.inverse_transform(result)
print(classification_report(test_labels, prediction_labels))
plot_cm(test_labels, prediction_labels, encoder)
plot_history(history)