Guest User

Untitled

a guest
Jun 8th, 2022
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. model = tf.keras.models.Sequential([
  6. tf.keras.layers.Dense(10, activation='relu'),
  7. tf.keras.layers.Dense(100, activation='relu'),
  8. tf.keras.layers.Dense(100, activation='relu'),
  9. tf.keras.layers.Dense(1, activation='relu')
  10. ])
  11. model.compile(optimizer='adam',
  12. loss='mse',
  13. metrics=['accuracy'])
  14.  
  15.  
  16. def train_function(x):
  17. return x
  18.  
  19.  
  20. def split_sequence(sequence, n_steps):
  21. X, y = list(), list()
  22. for i in range(len(sequence)):
  23. end_ix = i + n_steps
  24. if end_ix > len(sequence)-1:
  25. break
  26. seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
  27. X.append(seq_x)
  28. y.append(seq_y)
  29. return np.array(X), np.array(y)# define input sequence
  30.  
  31.  
  32. xaxis = np.arange(-50*np.pi, 50*np.pi, 0.1)
  33. train_seq = train_function(xaxis)
  34. n_steps = 20
  35. X, y = split_sequence(train_seq, n_steps)# reshape from [samples, timesteps] into [samples, timesteps, features]
  36. n_features = 1
  37. X = X.reshape((X.shape[0], X.shape[1], n_features))
  38. print("X.shape = {}".format(X.shape))
  39. print("y.shape = {}".format(y.shape))
  40.  
  41. history = model.fit(X, y, epochs=20, verbose=1)
  42. plt.plot(history.history['loss'], label="loss")
  43. plt.legend(loc="upper right")
  44. plt.show()
  45.  
  46. test_xaxis = np.arange(0, 10*np.pi, 0.1)
  47.  
  48.  
  49. def test_function(x):
  50. return train_function(x)
  51.  
  52.  
  53. calc_y = test_function(test_xaxis)# start with initial n values, rest will be predicted
  54. test_y = calc_y[:n_steps]
  55. results = []
  56.  
  57. for i in range( len(test_xaxis) - n_steps ):
  58. net_input = test_y[i : i + n_steps]
  59. net_input = net_input.reshape((1, n_steps, n_features))
  60. y = model.predict(net_input, verbose=0)
  61. test_y = np.append(test_y, y)
  62.  
  63. plt.plot(test_xaxis[n_steps:], test_y[n_steps:], label="predicitons")
  64. plt.plot(test_xaxis, calc_y, label="ground truth")
  65. plt.plot(test_xaxis[:n_steps], test_y[:n_steps], label="initial sequence", color="red")
  66. plt.legend(loc='upper left')
  67. plt.ylim(-2, 2)
  68. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment