1

我正在尝试复制 Siraj 的代码以预测 R 中的股票价格(https://github.com/llSourcell/How-to-Predict-Stock-Prices-Easily-Demo)。

这是我的代码:

url <- "https://raw.githubusercontent.com/llSourcell/How-to-Predict-Stock-Prices-Easily-Demo/master/sp500.csv"
sp500 <- read.csv(url, header = FALSE, stringsAsFactors = FALSE)
colnames(sp500) <- "closingPrice"

# choose sequence length
seq_length <- 50
sequence_length <- seq_length + 1
result <- list()
for (i in 1:(nrow(sp500) - seq_length)){
  result[[i]] <- sp500[i : (i + seq_length),1]
}

# normalised data
normalised_data <- list()
for (i in 1:length(result)){
  normalised_window <- ((result[[i]] / result[[i]][[1]]) - 1)
  normalised_data[[i]] <- normalised_window
}
result <- normalised_data

# test <- do.call(rbind, result)
# define train and test datasets
row <- round(0.9 * length(result))
train <- result[1:as.integer(row)]
# train <- sample(train)
x_train <- lapply(train, '[', -length(train[[1]]))
y_train <- lapply(train, '[', length(train[[1]]))
test = result[(as.integer(row)+1):length(result)]
x_test <- lapply(test, '[', -length(test[[1]]))
y_test <- lapply(test, '[', length(test[[1]]))

x_train <- array(x_train, dim = c(3709, 51, 1))
x_test <- array(x_test, dim = c(412, 51, 1))


#########################
# Step 2: Build a model #
#########################

library(keras)

model <- keras_model_sequential()
model %>% layer_lstm(units = 51L, return_sequences = TRUE, input_shape = c(NULL, 1L))

最后一行返回错误:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: Input 0 is incompatible with layer lstm_5: expected ndim=3, found ndim=2

在原始代码中,Siraj 使用LSTM 层input_dimoutput_dim参数,但layer_lstm()R 中的函数不包含此参数。我发现它在 Keras 2 中已贬值,我应该使用unitsand input_shape,但我尝试了input_shape = c(1L), input_shape = c(NULL, 1L), input_shape = c("None", 1L)...,但它不起作用。

4

0 回答 0