-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensorflowHelper.py
More file actions
104 lines (86 loc) · 3.79 KB
/
tensorflowHelper.py
File metadata and controls
104 lines (86 loc) · 3.79 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
import zipfile
import os
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers
import datetime
class TensorFlowHelper:
@staticmethod
def extract_zipFiles(file_name: str):
"""
Extract any zip file/folder
:param file_name: Provide the file name in String (with full path)
"""
zip_ref = zipfile.ZipFile(file_name)
zip_ref.extractall()
zip_ref.close()
@staticmethod
def walk_through_directories(file_name: str):
"""
Walks through and print all the files folders in a directory.
:param file_name: Provide the file name in String (with full path)
"""
for dirPath, dirNames, filesNames in os.walk(file_name):
print(f"There are {len(dirNames)} directories and {len(filesNames)} files in '{dirPath}'")
@staticmethod
def plot_loss_curve(history):
"""
Returns separate loss curves for training and validation metrics.
:param history: Tensorflow History object.
:return: Plots of training/validation loss and accuracy metrics.
"""
loss = history.history["loss"]
val_loss = history.history["val_loss"]
accuracy = history.history["accuracy"]
val_accuracy = history.history["val_accuracy"]
epochs = range(len(history.history["loss"]))
# Plot loss
plt.plot(epochs, loss, label="training_loss")
plt.plot(epochs, val_loss, label="val_loss")
plt.title("Loss")
plt.xlabel("Epochs")
plt.legend()
# Plot accuracy
plt.figure()
plt.plot(epochs, accuracy, label="training_accuracy")
plt.plot(epochs, val_accuracy, label="val_accuracy")
plt.title("Accuracy")
plt.xlabel("Epochs")
plt.legend()
@staticmethod
def tl_create_model(model_url, num_classes=10, Image_shape=(224, 224)):
"""
Takes a TensorFlow Hub URL and create a Keras Sequential model with it.
Used for transfer learning...
For Image classification
:param model_url: A TensorFlow Hub feature extraction URL.
:param num_classes: Number of output neurons in the output layer,
should be equal to number of target classes, default 10.
:param Image_shape: Image shape for the input layer
:return: An un compiled Keras Sequential model with model_url as feature extractor
layer and Dense output layer with num_classes output neurons.
"""
# Download the pretrained model and save it KerasLayer
feature_extractor_layer = hub.KerasLayer(model_url,
trainable=False, # freeze the already learned patterns
name="feature_extractor_model",
input_shape=Image_shape + (3,))
# Create our own model
model = tf.keras.Sequential([
feature_extractor_layer,
layers.Dense(num_classes, activation="softmax", name="output_layer")
])
return model
@staticmethod
def create_tensorboard_callback(dir_name, experiment_name):
"""
Creates a tensorboard callback to save the model and check it out in future use or compare with other model
:param dir_name: Give the directory name
:param experiment_name: Give the model name.
:return: the callback directory/path where the file is saved
"""
log_dir = dir_name + "/" + experiment_name + "/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)
print(f"Saving TensorFlow log files to: {log_dir}")
return tensorboard_callback