-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
116 lines (83 loc) · 2.74 KB
/
model.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
#! usr/bin/env python3
__name__ ='Akash Manna'
__date__ ='02/01/2022'
# Import modules and packages
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#Functions and procedures
def plot_predictions(train_data, train_labels, test_data, test_labels, predictions):
'''
plots training data, test data and compare predictions
'''
plt.figure(figsize= (6, 5))
#plot training data in blue
plt.scatter(train_data, train_labels, c= 'b', label= 'Training data')
#Plot test data in green
plt.scatter(test_data, test_labels, c= 'g', label= 'Testing data')
#Plot the prediction in red
plt.scatter(test_data, predictions, c= 'r', label= 'predictions')
#Show the legends
plt.legend(shadow= 'True')
#Set grids
plt.grid(which= 'major', c= '#cccccc', linestyle= '--', alpha= 0.5)
#Some text
plt.title('Model Results', family= 'Arial', fontsize= 14)
plt.xlabel('X axis values', family= 'Arial', fontsize=11)
plt.ylabel('Y axis values', family = 'Arial', fontsize= 11)
#Show
plt.savefig('model_results.png', dpi= 120)
def mae(y_test, y_pred):
'''
Calculates the MAE between y_test and y_preds
'''
return tf.metrics.mean_absolute_error(y_test, y_pred)
def mse(y_test, y_pred):
'''
Calculates the mean squared error between y_test and y_pred
'''
return tf.metrics.mean_squared_error(y_test, y_pred)
#Check the tensorflow version
print(tf.__version__)
#Create features
X = np.arange(-100, 100, 4)
#Create labels
y = np.arange(-90, 110, 4)
#Split data info train and test sets
X_train = X[:40]
y_train = y[:40]
X_test= X[40:]
y_test = y[40:]
# Take a single example of X
input_shape = X[0].shape
#take a single example of y
output_shape = y[0].shape
#Set random seed
tf.random.set_seed(42)
#Craete the model
model = tf.keras.Sequential(
[
tf.keras.layers.Dense(1, input_shape=[1]),
tf.keras.layers.Dense(1),
tf.keras.layers.Dense(1)
]
)
#compile the model
model.compile(
loss = tf.keras.losses.mae,
optimizer = tf.keras.optimizers.SGD(),
metrics = ['mae']
)
#Fit the model
model.fit(X_train, y_train, epochs =1000)
#Make plot and predictions of the model
y_preds = model.predict(X_test)
plot_predictions(train_data= X_train, train_labels= y_train,
test_data= X_test, test_labels= y_test, predictions= y_preds)
#Calculate the model metrics
mae_1 = np.round(float(mae(y_test, y_preds.squeeze()).numpy()), 2)
mse_1 = np.round(float(mse(y_test, y_preds.squeeze()).numpy()), 2)
print(f'\n Mean Absolute error = {mae_1}, mean Squred Error = {mse_1}.')
# #Write metrics to file
# with open('metrics.txt', 'w') as outfile:
# outfile.write(f'\n Mean Absolute Error = {mae_1}, Mean Squred error = {mse_1}. ')