Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

helper_functions.py 10 KB

You have to be logged in to leave a comment. Sign In
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
  1. ### We create a bunch of helpful functions throughout the course.
  2. ### Storing them here so they're easily accessible.
  3. import tensorflow as tf
  4. # Create a function to import an image and resize it to be able to be used with our model
  5. def load_and_prep_image(filename, img_shape=224, scale=True):
  6. """
  7. Reads in an image from filename, turns it into a tensor and reshapes into
  8. (224, 224, 3).
  9. Parameters
  10. ----------
  11. filename (str): string filename of target image
  12. img_shape (int): size to resize target image to, default 224
  13. scale (bool): whether to scale pixel values to range(0, 1), default True
  14. """
  15. # Read in the image
  16. img = tf.io.read_file(filename)
  17. # Decode it into a tensor
  18. img = tf.image.decode_jpeg(img)
  19. # Resize the image
  20. img = tf.image.resize(img, [img_shape, img_shape])
  21. if scale:
  22. # Rescale the image (get all values between 0 and 1)
  23. return img/255.
  24. else:
  25. return img
  26. # Note: The following confusion matrix code is a remix of Scikit-Learn's
  27. # plot_confusion_matrix function - https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html
  28. import itertools
  29. import matplotlib.pyplot as plt
  30. import numpy as np
  31. from sklearn.metrics import confusion_matrix
  32. # Our function needs a different name to sklearn's plot_confusion_matrix
  33. def make_confusion_matrix(y_true, y_pred, classes=None, figsize=(10, 10), text_size=15, norm=False, savefig=False):
  34. """Makes a labelled confusion matrix comparing predictions and ground truth labels.
  35. If classes is passed, confusion matrix will be labelled, if not, integer class values
  36. will be used.
  37. Args:
  38. y_true: Array of truth labels (must be same shape as y_pred).
  39. y_pred: Array of predicted labels (must be same shape as y_true).
  40. classes: Array of class labels (e.g. string form). If `None`, integer labels are used.
  41. figsize: Size of output figure (default=(10, 10)).
  42. text_size: Size of output figure text (default=15).
  43. norm: normalize values or not (default=False).
  44. savefig: save confusion matrix to file (default=False).
  45. Returns:
  46. A labelled confusion matrix plot comparing y_true and y_pred.
  47. Example usage:
  48. make_confusion_matrix(y_true=test_labels, # ground truth test labels
  49. y_pred=y_preds, # predicted labels
  50. classes=class_names, # array of class label names
  51. figsize=(15, 15),
  52. text_size=10)
  53. """
  54. # Create the confustion matrix
  55. cm = confusion_matrix(y_true, y_pred)
  56. cm_norm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis] # normalize it
  57. n_classes = cm.shape[0] # find the number of classes we're dealing with
  58. # Plot the figure and make it pretty
  59. fig, ax = plt.subplots(figsize=figsize)
  60. cax = ax.matshow(cm, cmap=plt.cm.Blues) # colors will represent how 'correct' a class is, darker == better
  61. fig.colorbar(cax)
  62. # Are there a list of classes?
  63. if classes:
  64. labels = classes
  65. else:
  66. labels = np.arange(cm.shape[0])
  67. # Label the axes
  68. ax.set(title="Confusion Matrix",
  69. xlabel="Predicted label",
  70. ylabel="True label",
  71. xticks=np.arange(n_classes), # create enough axis slots for each class
  72. yticks=np.arange(n_classes),
  73. xticklabels=labels, # axes will labeled with class names (if they exist) or ints
  74. yticklabels=labels)
  75. # Make x-axis labels appear on bottom
  76. ax.xaxis.set_label_position("bottom")
  77. ax.xaxis.tick_bottom()
  78. # Set the threshold for different colors
  79. threshold = (cm.max() + cm.min()) / 2.
  80. # Plot the text on each cell
  81. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
  82. if norm:
  83. plt.text(j, i, f"{cm[i, j]} ({cm_norm[i, j]*100:.1f}%)",
  84. horizontalalignment="center",
  85. color="white" if cm[i, j] > threshold else "black",
  86. size=text_size)
  87. else:
  88. plt.text(j, i, f"{cm[i, j]}",
  89. horizontalalignment="center",
  90. color="white" if cm[i, j] > threshold else "black",
  91. size=text_size)
  92. # Save the figure to the current working directory
  93. if savefig:
  94. fig.savefig("confusion_matrix.png")
  95. # Make a function to predict on images and plot them (works with multi-class)
  96. def pred_and_plot(model, filename, class_names):
  97. """
  98. Imports an image located at filename, makes a prediction on it with
  99. a trained model and plots the image with the predicted class as the title.
  100. """
  101. # Import the target image and preprocess it
  102. img = load_and_prep_image(filename)
  103. # Make a prediction
  104. pred = model.predict(tf.expand_dims(img, axis=0))
  105. # Get the predicted class
  106. if len(pred[0]) > 1: # check for multi-class
  107. pred_class = class_names[pred.argmax()] # if more than one output, take the max
  108. else:
  109. pred_class = class_names[int(tf.round(pred)[0][0])] # if only one output, round
  110. # Plot the image and predicted class
  111. plt.imshow(img)
  112. plt.title(f"Prediction: {pred_class}")
  113. plt.axis(False);
  114. import datetime
  115. def create_tensorboard_callback(dir_name, experiment_name):
  116. """
  117. Creates a TensorBoard callback instand to store log files.
  118. Stores log files with the filepath:
  119. "dir_name/experiment_name/current_datetime/"
  120. Args:
  121. dir_name: target directory to store TensorBoard log files
  122. experiment_name: name of experiment directory (e.g. efficientnet_model_1)
  123. """
  124. log_dir = dir_name + "/" + experiment_name + "/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
  125. tensorboard_callback = tf.keras.callbacks.TensorBoard(
  126. log_dir=log_dir
  127. )
  128. print(f"Saving TensorBoard log files to: {log_dir}")
  129. return tensorboard_callback
  130. # Plot the validation and training data separately
  131. import matplotlib.pyplot as plt
  132. def plot_loss_curves(history):
  133. """
  134. Returns separate loss curves for training and validation metrics.
  135. Args:
  136. history: TensorFlow model History object (see: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/History)
  137. """
  138. loss = history.history['loss']
  139. val_loss = history.history['val_loss']
  140. accuracy = history.history['accuracy']
  141. val_accuracy = history.history['val_accuracy']
  142. epochs = range(len(history.history['loss']))
  143. # Plot loss
  144. plt.plot(epochs, loss, label='training_loss')
  145. plt.plot(epochs, val_loss, label='val_loss')
  146. plt.title('Loss')
  147. plt.xlabel('Epochs')
  148. plt.legend()
  149. # Plot accuracy
  150. plt.figure()
  151. plt.plot(epochs, accuracy, label='training_accuracy')
  152. plt.plot(epochs, val_accuracy, label='val_accuracy')
  153. plt.title('Accuracy')
  154. plt.xlabel('Epochs')
  155. plt.legend();
  156. def compare_historys(original_history, new_history, initial_epochs=5):
  157. """
  158. Compares two TensorFlow model History objects.
  159. Args:
  160. original_history: History object from original model (before new_history)
  161. new_history: History object from continued model training (after original_history)
  162. initial_epochs: Number of epochs in original_history (new_history plot starts from here)
  163. """
  164. # Get original history measurements
  165. acc = original_history.history["accuracy"]
  166. loss = original_history.history["loss"]
  167. val_acc = original_history.history["val_accuracy"]
  168. val_loss = original_history.history["val_loss"]
  169. # Combine original history with new history
  170. total_acc = acc + new_history.history["accuracy"]
  171. total_loss = loss + new_history.history["loss"]
  172. total_val_acc = val_acc + new_history.history["val_accuracy"]
  173. total_val_loss = val_loss + new_history.history["val_loss"]
  174. # Make plots
  175. plt.figure(figsize=(8, 8))
  176. plt.subplot(2, 1, 1)
  177. plt.plot(total_acc, label='Training Accuracy')
  178. plt.plot(total_val_acc, label='Validation Accuracy')
  179. plt.plot([initial_epochs-1, initial_epochs-1],
  180. plt.ylim(), label='Start Fine Tuning') # reshift plot around epochs
  181. plt.legend(loc='lower right')
  182. plt.title('Training and Validation Accuracy')
  183. plt.subplot(2, 1, 2)
  184. plt.plot(total_loss, label='Training Loss')
  185. plt.plot(total_val_loss, label='Validation Loss')
  186. plt.plot([initial_epochs-1, initial_epochs-1],
  187. plt.ylim(), label='Start Fine Tuning') # reshift plot around epochs
  188. plt.legend(loc='upper right')
  189. plt.title('Training and Validation Loss')
  190. plt.xlabel('epoch')
  191. plt.show()
  192. # Create function to unzip a zipfile into current working directory
  193. # (since we're going to be downloading and unzipping a few files)
  194. import zipfile
  195. def unzip_data(filename):
  196. """
  197. Unzips filename into the current working directory.
  198. Args:
  199. filename (str): a filepath to a target zip folder to be unzipped.
  200. """
  201. zip_ref = zipfile.ZipFile(filename, "r")
  202. zip_ref.extractall()
  203. zip_ref.close()
  204. # Walk through an image classification directory and find out how many files (images)
  205. # are in each subdirectory.
  206. import os
  207. def walk_through_dir(dir_path):
  208. """
  209. Walks through dir_path returning its contents.
  210. Args:
  211. dir_path (str): target directory
  212. Returns:
  213. A print out of:
  214. number of subdiretories in dir_path
  215. number of images (files) in each subdirectory
  216. name of each subdirectory
  217. """
  218. for dirpath, dirnames, filenames in os.walk(dir_path):
  219. print(f"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.")
  220. # Function to evaluate: accuracy, precision, recall, f1-score
  221. from sklearn.metrics import accuracy_score, precision_recall_fscore_support
  222. def calculate_results(y_true, y_pred):
  223. """
  224. Calculates model accuracy, precision, recall and f1 score of a binary classification model.
  225. Args:
  226. y_true: true labels in the form of a 1D array
  227. y_pred: predicted labels in the form of a 1D array
  228. Returns a dictionary of accuracy, precision, recall, f1-score.
  229. """
  230. # Calculate model accuracy
  231. model_accuracy = accuracy_score(y_true, y_pred) * 100
  232. # Calculate model precision, recall and f1 score using "weighted average
  233. model_precision, model_recall, model_f1, _ = precision_recall_fscore_support(y_true, y_pred, average="weighted")
  234. model_results = {"accuracy": model_accuracy,
  235. "precision": model_precision,
  236. "recall": model_recall,
  237. "f1": model_f1}
  238. return model_results
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...