Skip to content

Commit c4e5f92

Browse files
authored
Separated classification and regression functions
1 parent 178bc1d commit c4e5f92

File tree

1 file changed

+174
-108
lines changed

1 file changed

+174
-108
lines changed

Notebooks/utils/DL_utils.py

Lines changed: 174 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,175 @@
1-
# Utility functions for deep learning with Keras
2-
# Dr. Tirthajyoti Sarkar, Fremont, CA 94536
3-
4-
import tensorflow as tf
5-
import numpy as np
6-
import matplotlib.pyplot as plt
7-
8-
class myCallback(tf.keras.callbacks.Callback):
9-
"""
10-
User can pass on the desired accuracy threshold while creating an instance of the class
11-
"""
12-
def __init__(self,acc_threshold=0.9,print_msg=True):
13-
self.acc_threshold=acc_threshold
14-
self.print_msg = print_msg
15-
16-
def on_epoch_end(self, epoch, logs={}):
17-
if(logs.get('acc')>self.acc_threshold):
18-
if self.print_msg:
19-
print("\nReached 90% accuracy so cancelling the training!")
20-
self.model.stop_training = True
21-
else:
22-
if self.print_msg:
23-
print("\nAccuracy not high enough. Starting another epoch...\n")
24-
25-
26-
def build_model(num_layers=1, architecture=[32],act_func='relu',
27-
input_shape=(28,28), output_class=10):
28-
"""
29-
Builds a densely connected neural network model from user input
30-
num_layers: Number of hidden layers
31-
architecture: Architecture of the hidden layers (densely connected)
32-
act_func: Activation function. Could be 'relu', 'sigmoid', or 'tanh'.
33-
input_shape: Dimension of the input vector
34-
output_class: Number of classes in the output vector
35-
"""
36-
layers=[tf.keras.layers.Flatten(input_shape=input_shape)]
37-
if act_func=='relu':
38-
activation=tf.nn.relu
39-
elif act_func=='sigmoid':
40-
activation=tf.nn.sigmoid
41-
elif act_func=='tanh':
42-
activation=tf.nn.tanh
43-
44-
for i in range(num_layers):
45-
layers.append(tf.keras.layers.Dense(architecture[i], activation=tf.nn.relu))
46-
layers.append(tf.keras.layers.Dense(output_class, activation=tf.nn.softmax))
47-
48-
model = tf.keras.models.Sequential(layers)
49-
return model
50-
51-
52-
def compile_train_model(model,x_train, y_train, callbacks=None,
53-
learning_rate=0.001,batch_size=1,epochs=10,verbose=0):
54-
"""
55-
Compiles and trains a given Keras model with the given data.
56-
Assumes Adam optimizer for this implementation.
57-
58-
# Arguments
59-
learning_rate: Learning rate for the optimizer Adam
60-
batch_size: Batch size for the mini-batch optimization
61-
epochs: Number of epochs to train
62-
verbose: Verbosity of the training process
63-
64-
# Returns
65-
A copy of the model
66-
"""
67-
68-
model_copy = model
69-
model_copy.compile(optimizer=tf.keras.optimizers.Adam(lr=learning_rate),
70-
loss='sparse_categorical_crossentropy',
71-
metrics=['accuracy'])
72-
73-
model_copy.fit(x_train, y_train, epochs=epochs, batch_size=batch_size,
74-
callbacks=[callbacks],verbose=verbose)
75-
return model_copy
76-
77-
78-
79-
def plot_loss_acc(model,target_acc=0.9, title=None):
80-
"""
81-
Takes a deep learning model and plots the loss ans accuracy over epochs
82-
Users can supply a title if needed
83-
target_acc: The desired/ target acc. This parameter is needed for this function to show a horizontal bar.
84-
"""
85-
e=np.array(model.history.epoch)+1 # Add one to the list of epochs which is zero-indexed
86-
l=np.array(model.history.history['loss'])
87-
a=np.array(model.history.history['acc'])
88-
89-
fig, ax1 = plt.subplots()
90-
91-
color = 'tab:red'
92-
ax1.set_xlabel('Epochs',fontsize=15)
93-
ax1.set_ylabel('Loss', color=color,fontsize=15)
94-
ax1.plot(e, l, color=color,lw=2)
95-
ax1.tick_params(axis='y', labelcolor=color)
96-
ax1.grid(True)
97-
98-
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
99-
100-
color = 'tab:blue'
101-
ax2.set_ylabel('Accuracy', color=color,fontsize=15) # we already handled the x-label with ax1
102-
ax2.plot(e, a, color=color,lw=2)
103-
ax2.tick_params(axis='y', labelcolor=color)
104-
105-
fig.tight_layout() # otherwise the right y-label is slightly clipped
106-
if title!=None:
107-
plt.title(title)
108-
plt.hlines(y=target_acc,xmin=1,xmax=e.max(),colors='k', linestyles='dashed',lw=3)
1+
# Utility functions for deep learning with Keras
2+
# Dr. Tirthajyoti Sarkar, Fremont, CA 94536
3+
4+
import tensorflow as tf
5+
import numpy as np
6+
import matplotlib.pyplot as plt
7+
8+
class myCallback(tf.keras.callbacks.Callback):
9+
"""
10+
User can pass on the desired accuracy threshold while creating an instance of the class
11+
"""
12+
def __init__(self,acc_threshold=0.9,print_msg=True):
13+
self.acc_threshold=acc_threshold
14+
self.print_msg = print_msg
15+
16+
def on_epoch_end(self, epoch, logs={}):
17+
if(logs.get('acc')>self.acc_threshold):
18+
if self.print_msg:
19+
print("\nReached 90% accuracy so cancelling the training!")
20+
self.model.stop_training = True
21+
else:
22+
if self.print_msg:
23+
print("\nAccuracy not high enough. Starting another epoch...\n")
24+
25+
26+
def build_classification_model(num_layers=1, architecture=[32],act_func='relu',
27+
input_shape=(28,28), output_class=10):
28+
"""
29+
Builds a densely connected neural network model from user input
30+
31+
Arguments
32+
num_layers: Number of hidden layers
33+
architecture: Architecture of the hidden layers (densely connected)
34+
act_func: Activation function. Could be 'relu', 'sigmoid', or 'tanh'.
35+
input_shape: Dimension of the input vector
36+
output_class: Number of classes in the output vector
37+
Returns
38+
A neural net (Keras) model for classification
39+
"""
40+
layers=[tf.keras.layers.Flatten(input_shape=input_shape)]
41+
if act_func=='relu':
42+
activation=tf.nn.relu
43+
elif act_func=='sigmoid':
44+
activation=tf.nn.sigmoid
45+
elif act_func=='tanh':
46+
activation=tf.nn.tanh
47+
48+
for i in range(num_layers):
49+
layers.append(tf.keras.layers.Dense(architecture[i], activation=tf.nn.relu))
50+
layers.append(tf.keras.layers.Dense(output_class, activation=tf.nn.softmax))
51+
52+
model = tf.keras.models.Sequential(layers)
53+
return model
54+
55+
def build_regression_model(input_neurons=10,input_dim=1,num_layers=1, architecture=[32],act_func='relu'):
56+
"""
57+
Builds a densely connected neural network model from user input
58+
59+
Arguments
60+
num_layers: Number of hidden layers
61+
architecture: Architecture of the hidden layers (densely connected)
62+
act_func: Activation function. Could be 'relu', 'sigmoid', or 'tanh'.
63+
input_shape: Dimension of the input vector
64+
Returns
65+
A neural net (Keras) model for regression
66+
"""
67+
if act_func=='relu':
68+
activation=tf.nn.relu
69+
elif act_func=='sigmoid':
70+
activation=tf.nn.sigmoid
71+
elif act_func=='tanh':
72+
activation=tf.nn.tanh
73+
74+
layers=[tf.keras.layers.Dense(input_neurons,input_dim=input_dim,activation=activation)]
75+
76+
for i in range(num_layers):
77+
layers.append(tf.keras.layers.Dense(architecture[i], activation=activation))
78+
layers.append(tf.keras.layers.Dense(1))
79+
80+
model = tf.keras.models.Sequential(layers)
81+
return model
82+
83+
84+
def compile_train_classification_model(model,x_train, y_train, callbacks=None,
85+
learning_rate=0.001,batch_size=1,epochs=10,verbose=0):
86+
"""
87+
Compiles and trains a given Keras model with the given data.
88+
Assumes Adam optimizer for this implementation.
89+
Assumes categorical cross-entropy loss.
90+
91+
Arguments
92+
learning_rate: Learning rate for the optimizer Adam
93+
batch_size: Batch size for the mini-batch optimization
94+
epochs: Number of epochs to train
95+
verbose: Verbosity of the training process
96+
97+
Returns
98+
A copy of the model
99+
"""
100+
101+
model_copy = model
102+
model_copy.compile(optimizer=tf.keras.optimizers.Adam(lr=learning_rate),
103+
loss='sparse_categorical_crossentropy',
104+
metrics=['accuracy'])
105+
106+
if callbacks!=None:
107+
model_copy.fit(x_train, y_train, epochs=epochs, batch_size=batch_size,
108+
callbacks=[callbacks],verbose=verbose)
109+
else:
110+
model_copy.fit(x_train, y_train, epochs=epochs, batch_size=batch_size,
111+
verbose=verbose)
112+
return model_copy
113+
114+
def compile_train_regression_model(model,x_train, y_train, callbacks=None,
115+
learning_rate=0.001,batch_size=1,epochs=10,verbose=0):
116+
"""
117+
Compiles and trains a given Keras model with the given data for regression.
118+
Assumes Adam optimizer for this implementation.
119+
Assumes mean-squared-error loss
120+
121+
Arguments
122+
learning_rate: Learning rate for the optimizer Adam
123+
batch_size: Batch size for the mini-batch operation
124+
epochs: Number of epochs to train
125+
verbose: Verbosity of the training process
126+
127+
Returns
128+
A copy of the model
129+
"""
130+
131+
model_copy = model
132+
model_copy.compile(optimizer=tf.keras.optimizers.Adam(lr=learning_rate),
133+
loss='mean_squared_error',
134+
metrics=['accuracy'])
135+
if callbacks!=None:
136+
model_copy.fit(x_train, y_train, epochs=epochs, batch_size=batch_size,
137+
callbacks=[callbacks],verbose=verbose)
138+
else:
139+
model_copy.fit(x_train, y_train, epochs=epochs, batch_size=batch_size,
140+
verbose=verbose)
141+
return model_copy
142+
143+
144+
145+
def plot_loss_acc(model,target_acc=0.9, title=None):
146+
"""
147+
Takes a deep learning model and plots the loss ans accuracy over epochs
148+
Users can supply a title if needed
149+
target_acc: The desired/ target acc. This parameter is needed for this function to show a horizontal bar.
150+
"""
151+
e=np.array(model.history.epoch)+1 # Add one to the list of epochs which is zero-indexed
152+
l=np.array(model.history.history['loss'])
153+
a=np.array(model.history.history['acc'])
154+
155+
fig, ax1 = plt.subplots()
156+
157+
color = 'tab:red'
158+
ax1.set_xlabel('Epochs',fontsize=15)
159+
ax1.set_ylabel('Loss', color=color,fontsize=15)
160+
ax1.plot(e, l, color=color,lw=2)
161+
ax1.tick_params(axis='y', labelcolor=color)
162+
ax1.grid(True)
163+
164+
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
165+
166+
color = 'tab:blue'
167+
ax2.set_ylabel('Accuracy', color=color,fontsize=15) # we already handled the x-label with ax1
168+
ax2.plot(e, a, color=color,lw=2)
169+
ax2.tick_params(axis='y', labelcolor=color)
170+
171+
fig.tight_layout() # otherwise the right y-label is slightly clipped
172+
if title!=None:
173+
plt.title(title)
174+
plt.hlines(y=target_acc,xmin=1,xmax=e.max(),colors='k', linestyles='dashed',lw=3)
109175
plt.show()

0 commit comments

Comments
 (0)