Skip to content

Instantly share code, notes, and snippets.

View esmitt's full-sized avatar
🐢
As fast as a Pentium I

esmitt esmitt

🐢
As fast as a Pentium I
View GitHub Profile
@esmitt
esmitt / precision-example.py
Created July 24, 2020 19:23
An example in how to compute the precision metric in Tensorflow 2
precision = Precision()
precision.update_state(y_train, y_train_pred)
precision.result().numpy()
@esmitt
esmitt / plot-confusion-matrix.py
Last active October 15, 2020 20:37
Plotting a confusion matrix for binary classification using matplotlib
from sklearn.metrics import confusion_matrix
import seaborn as sns
# notice the threshold
def plot_cm(labels: numpy.ndarray, predictions: numpy.ndarray, p: float=0.5) -> ():
cm = confusion_matrix(labels, predictions > p)
# you can normalize the confusion matrix
plt.figure(figsize=(5,5))
sns.heatmap(cm, annot=True, fmt="d")
@esmitt
esmitt / evaluate-model.py
Created July 24, 2020 19:19
Evaluation of a model in Tensorflow
# Evaluate the model on the test data using `evaluate`
print("Evaluate on test data")
score_test = model.evaluate(test_ds.batch(batch_size))
for name, value in zip(model.metrics_names, score_test):
print(name, ': ', value)
@esmitt
esmitt / plot-metrics.py
Last active October 15, 2020 20:36
Plotting the metrics using matplotlib
def plot_metrics(history: History) -> ():
metrics = ['loss', 'precision', 'recall', 'auc', 'tp', 'sensitivity']
for n, metric in enumerate(metrics):
name = metric.replace("_"," ").capitalize()
plt.subplot(3, 2, n+1) # adjust according to metrics
plt.plot(history.epoch, history.history[metric], color=colors[0], label='Train')
plt.plot(history.epoch, history.history['val_'+metric],
color=colors[0], linestyle="--", label='Val')
plt.xlabel('Epoch')
plt.ylabel(name)
@esmitt
esmitt / plot-loss.py
Last active October 15, 2020 20:36
Plotting the loss function using a log scale using Matplotlib
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['figure.figsize'] = (12, 10)
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
def plot_log_loss(history: History, title_label: str, n: int) -> ():
# Use a log scale to show the wide range of values.
plt.semilogy(history.epoch, history.history['loss'],
color=colors[n], label='Train '+title_label)
@esmitt
esmitt / fit-model.py
Last active October 15, 2020 20:35
Fit model function in Tensorflow 2
batch_size = 64
"""
Training the model for 60 epochs using our dataset.
The batch size (64) is the same for the validation data.
Only 1 callback was used, but could be more like TensorBoard, ModelCheckpoint, etc.
"""
history = model.fit(train_ds.batch(batch_size=batch_size),
epochs=60,
validation_data=validation_ds.batch(batch_size=batch_size),
@esmitt
esmitt / early-stopping.py
Last active October 15, 2020 20:35
Early stopping callback in Tensorflow 2
from tensorflow.keras.callbacks import EarlyStopping
"""
This callback will stop the training when there is no improvement in the validation accuracy across epochs
"""
early_callback = EarlyStopping(monitor='val_auc',
verbose=1,
patience=10,
mode='max',
restore_best_weights=True)
@esmitt
esmitt / compile-model.py
Last active October 15, 2020 20:34
Compiling a Tensorflow model
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import TruePositives, FalsePositives, TrueNegatives, FalseNegatives, BinaryAccuracy, Precision, Recall, AUC
from tensorflow.keras.metrics import SpecificityAtSensitivity
"""
Definition of metrics commonly used on medical imaging classification, segmentation, and localization problems.
The metrics will appear on each iteration of the training process to monitor the progress of our design.
"""
METRICS = [
@esmitt
esmitt / plot-model-tensorflow.py
Last active July 24, 2020 19:02
Displaying a Tensorflow model
from tensorflow.keras.utils import plot_model
plot_model(model, 'my-CNNmodel.png', show_shapes=True)
@esmitt
esmitt / functional-model.py
Last active October 15, 2020 20:33
Functional design using Tensorflow 2
from tensorflow.keras import Model
from tensorflow.keras.layers import Input, Convolution2D, MaxPool2D, BatchNormalization, Flatten, Dropout, Dense
from tensorflow.keras.regularizers import l2
from tensorflow.keras.activations import relu, sigmoid
from tensorflow.keras.initializers import GlorotNormal
# this configuration uses backend.set_image_data_format('channels_first')
"""
This design creates the same network than before but using the layer by layer configuration.