Преобразование одномерного в многомерное прогнозирование временных рядов с помощью LSTM - PullRequest
1 голос
/ 06 января 2020

Я новичок в мире искусственных нейронных сетей, поэтому, если я сделаю несколько ошибок, извините меня и поправьте меня, если можете. Я хотел бы использовать модель LSTM, чтобы прогнозировать цену bitcoin на рынке. Я знаю практические ограничения модели, но я создаю ее для образовательных целей.

Я не знаю, определить ли это многослойную или многомерную модель (если кто-то может объяснить разницу, я был бы признателен) в основном модель, которая обучалась на цене закрытия, называемой «закрытием», может предсказать цену закрытия следующего дня, наблюдая за предыдущими 60 днями.

У меня не было проблем при построении модели отсюда, я только что говорил с вами, проблема в том, что я хотел бы обучить модель другой информации, такой как объем или максимальная цена за день. Важно иметь возможность решить, какие два типа информации вставить в модель. Я нашел сайт, где подробно описывается многомерное прогнозирование временных рядов с помощью LSTM в Keras , но я не могу применить его к конкретному случаю c. Не могли бы вы помочь мне интегрировать переменную «объем» в модель, чтобы увидеть, улучшается или ухудшается предсказательная сила будущей цены закрытия «закрытия»?

Данные относятся к этому типу и могут быть загружены здесь с сайта kaggle. -> Скачать enter image description here

import pandas as pd
import math
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt


#Create a new dataframe with only the 'Close column
data = df.filter(['close'])
#Convert the dataframe to a numpy array
dataset = data.values
#Get the number of rows to train the model on
training_data_len = math.ceil( len(dataset) * .8 )

#scale data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)

#Create the scaled training data set
train_data = scaled_data[0:training_data_len , :]
#Split the data into x_train and y_train data sets
x_train = []
y_train = []

for i in range(60, len(train_data)):
  x_train.append(train_data[i-60:i, 0])
  y_train.append(train_data[i, 0])
  # if i<= 61:
    # print(x_train)
    # print(y_train)
    # print()

#Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)

#Reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
print (x_train.shape)

#Build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape= (x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences= False))
model.add(Dense(25))
model.add(Dense(1))

#Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
#Train the model
model.fit(x_train, y_train, batch_size=1, epochs=1)

#Create the testing data set
#Create a new array containing scaled values 
test_data = scaled_data[training_data_len - 60: , :]
#Create the data sets x_test and y_test
x_test = []
y_test = dataset[training_data_len:, :]
for i in range(60, len(test_data)):
  x_test.append(test_data[i-60:i, 0])

#Convert the data to a numpy array
x_test = np.array(x_test)
#Reshape the data

x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1 ))

# print (len(x_test))
# #Get the models predicted price values
predictions = model.predict(x_test)

predictions = scaler.inverse_transform(predictions)
print(predictions)

#Get the root mean squared error (RMSE)
rmse=np.sqrt(np.mean(((predictions- y_test)**2)))
print (rmse)
...