Last active
June 8, 2017 03:37
-
-
Save hughdbrown/8cf48569f7f136314dae0fbb010934f9 to your computer and use it in GitHub Desktop.
Sample LSTM code for keras
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From: | |
# http://machinelearningmastery.com/5-step-life-cycle-long-short-term-memory-models-keras/ | |
# Example of LSTM to learn a sequence | |
from pandas import DataFrame | |
from pandas import concat | |
from keras.models import Sequential | |
from keras.layers import Dense | |
from keras.layers import LSTM | |
# create sequence | |
length = 10 | |
sequence = [i/float(length) for i in range(length)] | |
print(sequence) | |
# create X/y pairs | |
df = DataFrame(sequence) | |
df = concat([df.shift(1), df], axis=1) | |
df.dropna(inplace=True) | |
# convert to LSTM friendly format | |
values = df.values | |
X, y = values[:, 0], values[:, 1] | |
X = X.reshape(len(X), 1, 1) | |
# 1. define network | |
model = Sequential() | |
model.add(LSTM(10, input_shape=(1,1))) | |
model.add(Dense(1)) | |
# 2. compile network | |
model.compile(optimizer='adam', loss='mean_squared_error') | |
# 3. fit network | |
history = model.fit(X, y, epochs=1000, batch_size=len(X), verbose=0) | |
# 4. evaluate network | |
loss = model.evaluate(X, y, verbose=0) | |
print(loss) | |
# 5. make predictions | |
predictions = model.predict(X, verbose=0) | |
print(predictions[:, 0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment