Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. from random import randint
  2. from numpy import array
  3. from numpy import argmax
  4. from pandas import DataFrame
  5. from pandas import concat
  6. from keras.models import Sequential
  7. from keras.layers import LSTM
  8. from keras.layers import Dense
  9. from keras.layers import TimeDistributed
  10.  
  11. # generate a sequence of random numbers in [0, 99]
  12. def generate_sequence(length=25):
  13. return [randint(0, 99) for _ in range(length)]
  14.  
  15. # one hot encode sequence
  16. def one_hot_encode(sequence, n_unique=100):
  17. encoding = list()
  18. for value in sequence:
  19. vector = [0 for _ in range(n_unique)]
  20. vector[value] = 1
  21. encoding.append(vector)
  22. return array(encoding)
  23.  
  24. # decode a one hot encoded string
  25. def one_hot_decode(encoded_seq):
  26. return [argmax(vector) for vector in encoded_seq]
  27.  
  28. # convert encoded sequence to supervised learning
  29. def to_supervised(sequence, n_in, n_out):
  30. # create lag copies of the sequence
  31. df = DataFrame(sequence)
  32. df = concat([df.shift(n_in-i-1) for i in range(n_in)], axis=1)
  33. # drop rows with missing values
  34. df.dropna(inplace=True)
  35. # specify columns for input and output pairs
  36. values = df.values
  37. width = sequence.shape[1]
  38. X = values.reshape(len(values), n_in, width)
  39. y = values[:, 0:(n_out*width)].reshape(len(values), n_out, width)
  40. return X, y
  41.  
  42. # prepare data for the LSTM
  43. def get_data(n_in, n_out):
  44. # generate random sequence
  45. sequence = generate_sequence()
  46. # one hot encode
  47. encoded = one_hot_encode(sequence)
  48. # convert to X,y pairs
  49. X,y = to_supervised(encoded, n_in, n_out)
  50. return X,y
  51.  
  52. # define LSTM
  53. n_in = 5
  54. n_out = 5
  55.  
  56. X,y = get_data(n_in, n_out)
  57. print(X[1])
  58. one_hot_decode(X[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement