<jupyter_start><jupyter_text>Recurrent Neural Network with LSTM<jupyter_code>from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.layers import Activation, Dense, Dropout
from keras import optimizers
from pandas import Series
import math

data = pd.read_csv('BTC-USD.csv')
data = data.set_index(pd.DatetimeIndex(data['Date']))['Close']

def difference(dataset, interval = 1):
    diffList = list()
    for i in range(interval, len(dataset)):
        num = dataset[i] - dataset[i - interval]
        diffList.append(num)
    return Series(diffList)

backView = 3
    
def create_dataset(dataset, backView = 1):
    dataX, dataY = [], []
    for i in range(len(dataset) - backView - 1):
        a = dataset[i:(i + backView), 0]
        dataX.append(a)
        dataY.append(dataset[i + backView, 0])
    return numpy.array(dataX), numpy.array(dataY)

# fix random seed for reproducibility
numpy.random.seed(0)

# loading dataset
dataframe = data
dataset = dataframe.values
dataset = dataset.astype('float64').reshape(-1, 1)

# normalizing dataset
scaler = MinMaxScaler()
dataset = scaler.fit_transform(dataset)

# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset), :]

# reshape into Y = t + 1 and X = t
trainX, trainY = create_dataset(train, backView)
testX, testY = create_dataset(test, backView)

# reshape input to [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

# create and fit the LSTM network
model = Sequential()

model.add(LSTM(256, return_sequences = True, input_shape = (1, backView)))
model.add(LSTM(256))

model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs = 50, verbose = 1, shuffle = False, batch_size = 50)

# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])

# calculate root mean squared error
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))

predictions = numpy.empty_like(dataset)
predictions[:, :] = numpy.nan
predictions[backView:len(trainPredict) + backView, :] = trainPredict
predictions[len(trainPredict) + (backView * 2) + 1:len(dataset) - 1, :] = testPredict

predictionsDF = pd.DataFrame(predictions,columns = ["predicted"],index = dataframe.index)
ans = pd.concat([dataframe,predictionsDF],axis = 1)
print(ans, [backView, trainScore,testScore])

#   shift train predictions for plotting
trainPredictPlot = numpy.empty_like(dataset)
trainPredictPlot[:, :] = numpy.nan
trainPredictPlot[backView:len(trainPredict) + backView, :] = trainPredict

#   shift test predictions for plotting
testPredictPlot = numpy.empty_like(dataset)
testPredictPlot[:, :] = numpy.nan
testPredictPlot[len(trainPredict) + (backView * 2) + 1:len(dataset) - 1, :] = testPredict
    
#   plot baseline and predictions
plt.plot(scaler.inverse_transform(dataset), label = 'Actual')
plt.plot(trainPredictPlot, label = 'Training')
plt.plot(testPredictPlot, label = 'Testing')
plt.legend()
plt.show()
ans.plot()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13011152416356878, 'fraction_numerical': 0.012745618693574084, 'mean_word_length': 5.726785714285715, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '239945', 'license': 'MIT', 'n_tokens_mistral': 1324, 'n_tokens_neox': 1249, 'n_words': 292, 'path': 'BitcoinPrediction.ipynb', 'repo_name': 'huangelton/bitcoin-predict-algo', 'size': '3766'}