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

model.py 2.7 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
  1. # Import modules and packages
  2. import tensorflow as tf
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # Functions and procedures
  6. def plot_predictions(train_data, train_labels, test_data, test_labels, predictions):
  7. """
  8. Plots training data, test data and compares predictions.
  9. """
  10. plt.figure(figsize=(6, 5))
  11. # Plot training data in blue
  12. plt.scatter(train_data, train_labels, c="b", label="Training data")
  13. # Plot test data in green
  14. plt.scatter(test_data, test_labels, c="g", label="Testing data")
  15. # Plot the predictions in red (predictions were made on the test data)
  16. plt.scatter(test_data, predictions, c="r", label="Predictions")
  17. # Show the legend
  18. plt.legend(shadow='True')
  19. # Set grids
  20. plt.grid(which='major', c='#cccccc', linestyle='--', alpha=0.5)
  21. # Some text
  22. plt.title('Model Results', family='Arial', fontsize=14)
  23. plt.xlabel('X axis values', family='Arial', fontsize=11)
  24. plt.ylabel('Y axis values', family='Arial', fontsize=11)
  25. # Show
  26. plt.savefig('model_results.png', dpi=120)
  27. def mae(y_test, y_pred):
  28. """
  29. Calculuates mean absolute error between y_test and y_preds.
  30. """
  31. return tf.metrics.mean_absolute_error(y_test, y_pred)
  32. def mse(y_test, y_pred):
  33. """
  34. Calculates mean squared error between y_test and y_preds.
  35. """
  36. return tf.metrics.mean_squared_error(y_test, y_pred)
  37. # Check Tensorflow version
  38. print(tf.__version__)
  39. # Create features
  40. X = np.arange(-100, 100, 4)
  41. # Create labels
  42. y = np.arange(-90, 110, 4)
  43. # Split data into train and test sets
  44. N = 25
  45. X_train = X[:N] # first 40 examples (80% of data)
  46. y_train = y[:N]
  47. X_test = X[N:] # last 10 examples (20% of data)
  48. y_test = y[N:]
  49. # Take a single example of X
  50. input_shape = X[0].shape
  51. # Take a single example of y
  52. output_shape = y[0].shape
  53. # Set random seed
  54. tf.random.set_seed(1989)
  55. # Create a model using the Sequential API
  56. model = tf.keras.Sequential([
  57. tf.keras.layers.Dense(1),
  58. tf.keras.layers.Dense(1)
  59. ])
  60. # Compile the model
  61. model.compile(loss = tf.keras.losses.mae,
  62. optimizer = tf.keras.optimizers.SGD(),
  63. metrics = ['mae'])
  64. # Fit the model
  65. model.fit(X_train, y_train, epochs=100)
  66. # Make and plot predictions for model_1
  67. y_preds = model.predict(X_test)
  68. plot_predictions(train_data=X_train, train_labels=y_train, test_data=X_test, test_labels=y_test, predictions=y_preds)
  69. # Calculate model_1 metrics
  70. mae_1 = np.round(float(mae(y_test, y_preds.squeeze()).numpy()), 2)
  71. mse_1 = np.round(float(mse(y_test, y_preds.squeeze()).numpy()), 2)
  72. print(f'\nMean Absolute Error = {mae_1}, Mean Squared Error = {mse_1}.')
  73. # Write metrics to file
  74. with open('metrics.txt', 'w') as outfile:
  75. outfile.write(f'\nMean Absolute Error = {mae_1}, Mean Squared Error = {mse_1}.')
Tip!

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

Comments

Loading...