Spaces:
Runtime error
Runtime error
File size: 3,296 Bytes
6a9bfde | 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 104 105 106 107 108 109 110 111 112 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow import keras
from tensorflow.keras.layers import Bidirectional, LSTM, Dropout, Activation, Dense
RANDOM_SEED = 42
SEQ_LEN = 100
DROPOUT = 0.2
WINDOW_SIZE = SEQ_LEN - 1
BATCH_SIZE = 64
def load_data(csv_path):
df = pd.read_csv(csv_path, parse_dates=['Date'])
df = df.sort_values('Date')
return df
def plot_data(df):
ax = df.plot(x='Date', y='Close')
ax.set_xlabel("Date")
ax.set_ylabel("Close Price (USD)")
def scale_data(data):
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(data.values.reshape(-1, 1))
scaled_data = scaled_data[~pd.isnull(scaled_data)]
return scaled_data.reshape(-1, 1), scaler
def to_sequences(data, seq_len):
d = []
for index in range(len(data) - seq_len):
d.append(data[index: index + seq_len])
return np.array(d)
def preprocess(data_raw, seq_len, train_split):
data = to_sequences(data_raw, seq_len)
num_train = int(train_split * data.shape[0])
X_train = data[:num_train, :-1, :]
y_train = data[:num_train, -1, :]
X_test = data[num_train:, :-1, :]
y_test = data[num_train:, -1, :]
return X_train, y_train, X_test, y_test
def build_model(X_train):
model = keras.Sequential()
model.add(
Bidirectional(LSTM(WINDOW_SIZE, return_sequences=True), input_shape=(WINDOW_SIZE, X_train.shape[-1])))
model.add(Dropout(rate=DROPOUT))
model.add(Bidirectional(LSTM((WINDOW_SIZE * 2), return_sequences=True)))
model.add(Dropout(rate=DROPOUT))
model.add(Bidirectional(LSTM(WINDOW_SIZE, return_sequences=False)))
model.add(Dense(units=1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
return model
def train_model(model, X_train, y_train):
return model.fit(
X_train,
y_train,
epochs=50,
batch_size=BATCH_SIZE,
shuffle=False,
validation_split=0.1
)
def plot_model_loss(history):
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
def plot_predicted_price(X_test, y_test, model, scaler):
y_hat_inverse = scaler.inverse_transform(model.predict(X_test))
y_test_inverse = scaler.inverse_transform(y_test)
plt.plot(y_test_inverse, label="Actual Price", color='green')
plt.plot(y_hat_inverse, label="Predicted Price", color='red')
plt.title('Bitcoin price prediction')
plt.xlabel('Time [days]')
plt.ylabel('Price')
plt.legend(loc='best')
plt.show()
def main():
csv_path = "https://raw.githubusercontent.com/curiousily/Deep-Learning-For-Hackers/master/data/3.stock-prediction/BTC-USD.csv"
df = load_data(csv_path)
plot_data(df)
scaled_data, scaler = scale_data(df['Close'])
X_train, y_train, X_test, y_test = preprocess(scaled_data, SEQ_LEN, train_split=0.95)
model = build_model(X_train)
history = train_model(model, X_train, y_train)
plot_model_loss(history)
plot_predicted_price(X_test, y_test, model, scaler)
if __name__ == "__main__":
main()
|