【问题标题】:Convolutional neural networks for time-series时间序列的卷积神经网络
【发布时间】:2014-12-09 19:43:11
【问题描述】:

我想知道是否存在训练卷积神经网络进行时间序列分类的代码。

我看过一些最近的论文 (http://www.fer.unizg.hr/_download/repository/KDI-Djalto.pdf),但我不确定是否存在某些东西,或者我是否自己编写过代码。

【问题讨论】:

  • 此网站需要凭据才能阅读提供的 pdf。请考虑在您的问题中发布凭据或在某个免费位置提供凭据或托管文档​​

标签: neural-network


【解决方案1】:

完全可以使用 CNN 进行时间序列预测,无论是回归还是分类。 CNN 擅长发现局部模式,事实上 CNN 的工作假设是局部模式在任何地方都是相关的。卷积也是时间序列和信号处理中众所周知的操作。相对于 RNN 的另一个优势是它们的计算速度非常快,因为它们可以并行化,而不是 RNN 的顺序性质。

在下面的代码中,我将演示一个案例研究,其中可以使用 keras 预测 R 中的电力需求。请注意,这不是分类问题(我没有手边的示例),但修改代码以处理分类问题并不难(使用 softmax 输出而不是线性输出和交叉熵损失)。

数据集在 fpp2 库中可用:

library(fpp2)
library(keras)

data("elecdemand")

elec <- as.data.frame(elecdemand)

dm <- as.matrix(elec[, c("WorkDay", "Temperature", "Demand")])

接下来我们创建一个数据生成器。这用于创建要在训练过程中使用的批量训练和验证数据。请注意,此代码是 manning 出版物的“Deep Learning with R”一书(及其视频版本“Deep Learning with R in Motion”)中数据生成器的更简单版本。

data_gen <- function(dm, batch_size, ycol, lookback, lookahead) {

  num_rows <- nrow(dm) - lookback - lookahead
  num_batches <- ceiling(num_rows/batch_size)
  last_batch_size <- if (num_rows %% batch_size == 0) batch_size else num_rows %% batch_size
  i <- 1
  start_idx <- 1
  return(function(){
    running_batch_size <<- if (i == num_batches) last_batch_size else batch_size
    end_idx <- start_idx + running_batch_size - 1
    start_indices <- start_idx:end_idx

    X_batch <- array(0, dim = c(running_batch_size,
                                lookback,
                                ncol(dm)))
    y_batch <- array(0, dim = c(running_batch_size, 
                                length(ycol)))

    for (j in 1:running_batch_size){
      row_indices <- start_indices[j]:(start_indices[j]+lookback-1)
      X_batch[j,,] <- dm[row_indices,]
      y_batch[j,] <- dm[start_indices[j]+lookback-1+lookahead, ycol]
    }
    i <<- i+1
    start_idx <<- end_idx+1 
    if (i > num_batches){
      i <<- 1
      start_idx <<- 1
    }

    list(X_batch, y_batch)

  })
}

接下来,我们指定一些要传递给数据生成器的参数(我们创建了两个生成器,一个用于训练,一个用于验证)。

lookback <- 72
lookahead <- 1
batch_size <- 168
ycol <- 3

lookback 参数是我们想要查看过去多远,而lookahead 是我们想要预测未来多远。

接下来我们拆分数据集并创建两个生成器:

train_dm

val_dm <- dm[15001:16000,]
test_dm <- dm[16001:nrow(dm),]

train_gen <- data_gen(
  train_dm,
  batch_size = batch_size,
  ycol = ycol,
  lookback = lookback,
  lookahead = lookahead
)


val_gen <- data_gen(
  val_dm,
  batch_size = batch_size,
  ycol = ycol,
  lookback = lookback,
  lookahead = lookahead
)

接下来我们创建一个带有卷积层的神经网络并训练模型:

model <- keras_model_sequential() %>%
  layer_conv_1d(filters=64, kernel_size=4, activation="relu", input_shape=c(lookback, dim(dm)[[-1]])) %>%
  layer_max_pooling_1d(pool_size=4) %>%
  layer_flatten() %>%
  layer_dense(units=lookback * dim(dm)[[-1]], activation="relu") %>%
  layer_dropout(rate=0.2) %>%
  layer_dense(units=1, activation="linear")


model %>% compile(
  optimizer = optimizer_rmsprop(lr=0.001),
  loss = "mse",
  metric = "mae"
)

val_steps <- 48

history <- model %>% fit_generator(
  train_gen,
  steps_per_epoch = 50,
  epochs = 50,
  validation_data = val_gen,
  validation_steps = val_steps
)

最后,我们可以创建一些代码来使用一个简单的过程来预测 24 个数据点的序列,在 R cmets 中进行了解释。

####### How to create predictions ####################

#We will create a predict_forecast function that will do the following: 
#The function will be given a dataset that will contain weather forecast values and Demand values for the lookback duration. The rest of the MW values will be non-available and 
#will be "filled-in" by the deep network (predicted). We will do this with the test_dm dataset.

horizon <- 24

#Store all target values in a vector
goal_predictions <- test_dm[1:(lookback+horizon),ycol]
#get a copy of the dm_test
test_set <- test_dm[1:(lookback+horizon),]
#Set all the Demand values, except the lookback values, in the test set to be equal to NA.
test_set[(lookback+1):nrow(test_set), ycol] <- NA

predict_forecast <- function(model, test_data, ycol, lookback, horizon) {
  i <-1
  for (i in 1:horizon){
    start_idx <- i
    end_idx <- start_idx + lookback - 1
    predict_idx <- end_idx + 1
    input_batch <- test_data[start_idx:end_idx,]
    input_batch <- input_batch %>% array_reshape(dim = c(1, dim(input_batch)))
    prediction <- model %>% predict_on_batch(input_batch)
    test_data[predict_idx, ycol] <- prediction
  }

  test_data[(lookback+1):(lookback+horizon), ycol]
}

preds <- predict_forecast(model, test_set, ycol, lookback, horizon)

targets <- goal_predictions[(lookback+1):(lookback+horizon)]

pred_df <- data.frame(x = 1:horizon, y = targets, y_hat = preds)

瞧:

还不错。

【讨论】:

猜你喜欢
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2020-10-07
  • 2020-10-19
  • 2020-10-19
相关资源
最近更新 更多