Advertisement
snowcatman

3 How to Make a Neural Network: A Beginners Guide - By Patrick Cooper

Nov 15th, 2021
1,307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. # I got this off the youtube channel https://www.youtube.com/watch?v=swJFNjIjxIE. By Patrick Cooper
  2. # but it seems that one Cannot register 2 metrics with the same name: /tensorflow/api/keras/optimizers...
  3. # I must have not set up my workspace correctly, I am assuming. By Snowcatman
  4.  
  5. from tensorflow import keras
  6. from tensorflow.keras import layers
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9.  
  10. x = np.random.uniform(-10, 10, 100000)
  11. y = (x**2+5)*2
  12.  
  13. print(x)
  14.  
  15. def build_model():
  16.   model = keras.Sequential([
  17.     layers.Dense(64, input_dim=1, activation='relu'),
  18.     layers.Dense(128, activation='relu'),
  19.     layers.Dense(128, activation='relu'),
  20.     layers.Dense(64, activation='relu'),
  21.     layers.Dense(1)
  22.   ])
  23.  
  24.   # mean square error will work for our purposes here
  25.   model.compile(loss='mean_squared_error', optimizer='adam')
  26.   return model
  27.  
  28. model = build_model()
  29.  
  30. model.summary()
  31.  
  32. model.fit(x, y, epochs=12, batch_size=500)
  33.  
  34. eval_set_in = x[:3]
  35. eval_set_out = y[:3]
  36. print("Generate predictions for 3 samples using neural network model:")
  37. print("First 3 Evaluation Inputs:", eval_set_in)
  38. dl_predictions = model.predict(eval_set_in).flatten()
  39. print("First 3 Actual Outputs:", eval_set_out)
  40. print("First 3 Evaluation Outputs:", dl_predictions)
  41. print("Error:", abs(eval_set_out - dl_predictions))
  42.  
  43. poly_line = np.linspace(-10, 10, num=20)
  44.  
  45. plt.title('Input (x) versus Output (y)')
  46. plt.xlabel('Input Variable (x)')
  47. plt.ylabel('Output Variable (y)')
  48. plt.plot(poly_line, model.predict(poly_line), linewidth=8, color="blue",
  49.          label="Approximated")
  50. plt.plot(poly_line, (poly_line**2+5)*2, linewidth=4, color="lightblue",
  51.          label="Actual")
  52. plt.legend()
  53. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement