时间序列深度学习:seq2seq 模型预测太阳黑子

本文翻译自《Time Series Deep Learning, Part 2: Predicting Sunspot Frequency With Keras Lstm in R》,略有删减

原文链接

深度学习于商业的用途之一是提高时间序列预测的准确性。之前的教程显示了如何利用自相关性预测未来 10 年的月度太阳黑子数量。本教程将借助 RStudio 重新审视太阳黑子数据集,并且使用到 TensorFlow for R 中一些高级的深度学习功能,展示基于 keras 的深度学习教程遇到 tfruns(用于追踪、可视化和管理 TensorFlow 训练、实验的一整套工具)后产生出的有趣结果。

学习路线

深度学习教程将教会你:

  • 时间序列深度学习如何应用于商业
  • 深度学习预测太阳黑子
  • 如何建立 LSTM 模型
  • 如何回测 LSTM 模型

事实上,最酷的事之一是你能画出 LSTM 预测的回测结果。

商业中的时间序列深度学习

时间序列预测是商业中实现投资回报率(ROI)的一个关键领域。想一想:预测准确度提高 10% 就可以为机构节省数百万美元。这怎么可能?下面让我们来看看。

我们将以 NVIDIA 为例,一家为 Artificial IntelligenceDeep Learning 生产最先进芯片的半导体厂商。NVIDIA 生产的图形处理器或 GPU,这对于高性能深度学习所要求的大规模数值计算来说是必需的。芯片看起来像这样。

与所有制造商一样,NVIDIA 需要预测其产品的需求。为什么? 因为他们据此可以为客户提供合适数量的芯片。这个预测很关键,需要很多技巧和一些运气才能做到这一点。

我们所讨论的是销售预测,它推动了 NVIDIA 做出的所有生产制造决策。这包括购买多少原材料,有多少人来制造芯片,以及需要多少预算用于加工和装配操作。销售预测中的错误越多,NVIDIA 产生的成本就越大,因为所有这些活动(供应链、库存管理、财务规划等)都会变得没有意义!

商业中应用时间序列深度学习

时间序列深度学习对于预测具有高自相关性的数据非常准确,因为包括 LSTMGRU 在内的算法可以从序列中学习信息,无论模式何时发生。这些特殊的 RNN 旨在具有长期记忆性,这意味着它们善于在最近发生的观察和很久之前发生的观察之间学习模式。这使它们非常适合时间序列!但它们对销售数据有用吗?也许,来!我们讨论一下。

销售数据混合了各种特征,但通常有季节性模式趋势趋势可以是平坦的、线性的、指数的等等。这通常不是 LSTM 擅长的地方,但其他传统的预测方法可以检测趋势。但是,季节性不同。销售数据中的季节性是一种可以在多个频率(年度、季度、月度、周度甚至每天)上出现的模式。LSTM 非常适合检测季节性,因为它通常具有自相关性。因此,LSTM 和 GRU 可以很好地帮助改进季节性检测,从而减少销售预测中的整体预测误差。

深度学习时间序列预测:使用 keras 预测太阳黑子

这一节我们将借助基本的 R 工具在太阳黑子数据集上做时间序列预测。太阳黑子是太阳表面的低温区域,这里有一张来自 NASA 的太阳黑子图片。

我们使用月度数据集 sunspots.month(也有一个年度频率的版本),它包括 265 年间(1749 - 2013)的月度太阳黑子观测。

预测该数据集具有相当的挑战性,因为短期内的高变异性以及长期内明显的不规则周期性。例如,低频周期达到的最大幅度差异很大,达到最大低频周期高度所需的高频周期步数也是如此。(译注:数据中的局部高点之间间隔大约为 11 年)

我们的文章将重点关注两个主要方面:如何将深度学习应用于时间序列预测,以及如何在该领域中正确应用交叉验证。对于后者,我们将使用 rsample 包来允许对时间序列数据进行重新抽样。对于前者,我们的目标不是达到最佳表现,而是显示使用递归神经网络对此类数据进行建模时的一般操作过程。

递归神经网络

当我们的数据具有序列结构时,我们就用递归神经网络(RNN)进行建模。

目前为止,在 RNN 中,建立的最佳架构是 GRU(门递归单元)和 LSTM(长短期记忆网络)。今天,我们不要放大它们自身独特的东西,而是集中于它们与最精简的 RNN 的共同点上:基本的递归结构。

与通常称为多层感知器(MLP)的神经网络的原型相比,RNN 具有随时间推移的状态。来自 Goodfellow 等人的著作——“深度学习的圣经”,从这个图中可以很好地看出这一点:

每次,状态是当前输入和先前隐含状态的组合。这让人联想到自回归模型,但是对于神经网络,我们必须在某种程度上停止依赖。

因为那是为了确定权重,我们会不断计算输入变化后我们的损失如何变化。现在,如果我们必须考虑的输入在任意时间步无限地返回,那么我们将无法计算所有这些梯度。然而,在实践中,我们的隐含状态将在每次迭代中通过固定数量的步骤继续前进。

一旦我们加载并预处理数据,我们就会回过头来。

设置、预处理与探索

所用的包

这里是该教程所涉及到的包。

  1. # Core Tidyverse
  2. library(tidyverse)
  3. library(glue)
  4. library(forcats)
  5. # Time Series
  6. library(timetk)
  7. library(tidyquant)
  8. library(tibbletime)
  9. # Visualization
  10. library(cowplot)
  11. # Preprocessing
  12. library(recipes)
  13. # Sampling / Accuracy
  14. library(rsample)
  15. library(yardstick)
  16. # Modeling
  17. library(keras)
  18. library(tfruns)

如果你之前没有在 R 中运行过 Keras,你需要用 install_keras() 函数安装 Keras。

  1. # Install Keras if you have not installed before
  2. install_keras()

数据

数据集 sunspot.month 是一个 ts 类对象(非 tidy 类),所以我们将使用 timetk 中的 tk_tbl() 函数转换为 tidy 数据集。我们使用这个函数而不是来自 tibbleas.tibble(),用来自动将时间序列索引保存为zoo yearmon 索引。最后,我们将使用 lubridate::as_date()(使用 tidyquant 时加载)将 zoo 索引转换为日期,然后转换为 tbl_time 对象以使时间序列操作起来更容易。

  1. sun_spots <- datasets::sunspot.month %>%
  2. tk_tbl() %>%
  3. mutate(index = as_date(index)) %>%
  4. as_tbl_time(index = index)
  5. sun_spots
  1. # A time tibble: 3,177 x 2
  2. # Index: index
  3. index value
  4. <date> <dbl>
  5. 1 1749-01-01 58
  6. 2 1749-02-01 62.6
  7. 3 1749-03-01 70
  8. 4 1749-04-01 55.7
  9. 5 1749-05-01 85
  10. 6 1749-06-01 83.5
  11. 7 1749-07-01 94.8
  12. 8 1749-08-01 66.3
  13. 9 1749-09-01 75.9
  14. 10 1749-10-01 75.5
  15. # ... with 3,167 more rows

探索性数据分析

时间序列很长(有 265 年!)。我们可以将时间序列的全部(265 年)以及前 50 年的数据可视化,以获得该时间系列的直观感受。

使用 cowplot 可视化太阳黑子数据

我们将创建若干 ggplot 对象并借助 cowplot::plot_grid() 把这些对象组合起来。对于需要缩放的部分,我们使用 tibbletime::time_filter(),可以方便的实现基于时间的过滤。

  1. p1 <- sun_spots %>%
  2. ggplot(aes(index, value)) +
  3. geom_point(
  4. color = palette_light()[[1]],
  5. alpha = 0.5) +
  6. theme_tq() +
  7. labs(
  8. title = "From 1749 to 2013 (Full Data Set)")
  9. p2 <- sun_spots %>%
  10. filter_time("start" ~ "1800") %>%
  11. ggplot(aes(index, value)) +
  12. geom_line(
  13. color = palette_light()[[1]],
  14. alpha = 0.5) +
  15. geom_point(color = palette_light()[[1]]) +
  16. geom_smooth(
  17. method = "loess",
  18. span = 0.2, se = FALSE) +
  19. theme_tq() +
  20. labs(
  21. title = "1749 to 1759 (Zoomed In To Show Changes over the Year)",
  22. caption = "datasets::sunspot.month")
  23. p_title <- ggdraw() +
  24. draw_label(
  25. "Sunspots", size = 18,
  26. fontface = "bold",
  27. colour = palette_light()[[1]])
  28. plot_grid(
  29. p_title, p1, p2,
  30. ncol = 1, rel_heights = c(0.1, 1, 1))

回测:时间序列交叉验证

在序列数据上执行交叉验证时,必须保留对以前时间样本的时间依赖性。我们可以通过平移窗口的方式选择连续子样本,进而创建交叉验证抽样计划。实质上,由于没有未来测试数据,我们需要创造若干人造“未来”数据来解决这个问题,在金融领域这通常被称为“回测”。

之前的教程提到过,rsample包含回测功能。“Time Series Analysis Example”描述了一个使用 rolling_origin() 函数为时间序列交叉验证创建样本的过程。我们将使用这种方法。

开发一个回测策略

我们创建的抽样计划使用 100 年(initial = 12 x 100)的数据作为训练集,50 年(assess = 12 x 50)的数据用于测试集。我们选择大约 22 年的跳跃跨度(skip = 12 x 22 - 1),将样本均匀分布到 6 组中,跨越整个 265 年的太阳黑子历史。最后,我们选择 cumulative = FALSE 来允许平移起始点,这确保了较近期数据上的模型相较那些不太新近的数据没有不公平的优势(使用更多的观测数据)。rolling_origin_resamples 是一个 tibble 型的返回值。

  1. periods_train <- 12 * 100
  2. periods_test <- 12 * 50
  3. skip_span <- 12 * 22 - 1
  4. rolling_origin_resamples <- rolling_origin(
  5. sun_spots,
  6. initial = periods_train,
  7. assess = periods_test,
  8. cumulative = FALSE,
  9. skip = skip_span)
  10. rolling_origin_resamples
  1. # Rolling origin forecast resampling
  2. # A tibble: 6 x 2
  3. splits id
  4. <list> <chr>
  5. 1 <S3: rsplit> Slice1
  6. 2 <S3: rsplit> Slice2
  7. 3 <S3: rsplit> Slice3
  8. 4 <S3: rsplit> Slice4
  9. 5 <S3: rsplit> Slice5
  10. 6 <S3: rsplit> Slice6

可视化回测策略

我们可以用两个自定义函数来可视化再抽样。首先是 plot_split(),使用 ggplot2 绘制一个再抽样分割图。请注意,expand_y_axis 参数默认将日期范围扩展成整个 sun_spots 数据集的日期范围。当我们将所有的图形同时可视化时,这将变得有用。

  1. # Plotting function for a single split
  2. plot_split <- function(split,
  3. expand_y_axis = TRUE,
  4. alpha = 1,
  5. size = 1,
  6. base_size = 14)
  7. {
  8. # Manipulate data
  9. train_tbl <- training(split) %>%
  10. add_column(key = "training")
  11. test_tbl <- testing(split) %>%
  12. add_column(key = "testing")
  13. data_manipulated <- bind_rows(
  14. train_tbl, test_tbl) %>%
  15. as_tbl_time(index = index) %>%
  16. mutate(
  17. key = fct_relevel(
  18. key, "training", "testing"))
  19. # Collect attributes
  20. train_time_summary <- train_tbl %>%
  21. tk_index() %>%
  22. tk_get_timeseries_summary()
  23. test_time_summary <- test_tbl %>%
  24. tk_index() %>%
  25. tk_get_timeseries_summary()
  26. # Visualize
  27. g <- data_manipulated %>%
  28. ggplot(
  29. aes(x = index, y = value, color = key)) +
  30. geom_line(size = size, alpha = alpha) +
  31. theme_tq(base_size = base_size) +
  32. scale_color_tq() +
  33. labs(
  34. title = glue("Split: {split$id}"),
  35. subtitle = glue(
  36. "{train_time_summary$start} to {test_time_summary$end}"),
  37. y = "",
  38. x = "") +
  39. theme(legend.position = "none")
  40. if (expand_y_axis)
  41. {
  42. sun_spots_time_summary <- sun_spots %>%
  43. tk_index() %>%
  44. tk_get_timeseries_summary()
  45. g <- g +
  46. scale_x_date(
  47. limits = c(
  48. sun_spots_time_summary$start,
  49. sun_spots_time_summary$end))
  50. }
  51. return(g)
  52. }

plot_split() 函数接受一个分割(在本例中为 Slice01),并可视化抽样策略。我们使用 expand_y_axis = TRUE 将横坐标范围扩展到整个数据集的日期范围。

  1. rolling_origin_resamples$splits[[1]] %>%
  2. plot_split(expand_y_axis = TRUE) +
  3. theme(legend.position = "bottom")

第二个函数是 plot_sampling_plan(),使用 purrrcowplotplot_split() 函数应用到所有样本上。

  1. # Plotting function that scales to all splits
  2. plot_sampling_plan <- function(sampling_tbl,
  3. expand_y_axis = TRUE,
  4. ncol = 3,
  5. alpha = 1,
  6. size = 1,
  7. base_size = 14,
  8. title = "Sampling Plan")
  9. {
  10. # Map plot_split() to sampling_tbl
  11. sampling_tbl_with_plots <- sampling_tbl %>%
  12. mutate(
  13. gg_plots = map(
  14. splits, plot_split,
  15. expand_y_axis = expand_y_axis,
  16. alpha = alpha, base_size = base_size))
  17. # Make plots with cowplot
  18. plot_list <- sampling_tbl_with_plots$gg_plots
  19. p_temp <- plot_list[[1]] +
  20. theme(legend.position = "bottom")
  21. legend <- get_legend(p_temp)
  22. p_body <- plot_grid(
  23. plotlist = plot_list, ncol = ncol)
  24. p_title <- ggdraw() +
  25. draw_label(
  26. title, size = 14,
  27. fontface = "bold",
  28. colour = palette_light()[[1]])
  29. g <- plot_grid(
  30. p_title, p_body,
  31. legend, ncol = 1,
  32. rel_heights = c(0.05, 1, 0.05))
  33. return(g)
  34. }

现在我们可以使用 plot_sampling_plan() 可视化整个回测策略!我们可以看到抽样计划如何平移抽样窗口逐渐切分出训练和测试子样本。

  1. rolling_origin_resamples %>%
  2. plot_sampling_plan(
  3. expand_y_axis = T, ncol = 3,
  4. alpha = 1, size = 1, base_size = 10,
  5. title = "Backtesting Strategy: Rolling Origin Sampling Plan")

此外,我们可以让 expand_y_axis = FALSE,对每个样本进行缩放。

  1. rolling_origin_resamples %>%
  2. plot_sampling_plan(
  3. expand_y_axis = F, ncol = 3,
  4. alpha = 1, size = 1, base_size = 10,
  5. title = "Backtesting Strategy: Zoomed In")

当在太阳黑子数据集上测试 LSTM 模型准确性时,我们将使用这种回测策略(来自一个时间序列的 6 个样本,每个时间序列分为 100/50 两部分,并且样本之间有大约 22 年的偏移)。

LSTM 模型

首先,我们将在回测策略的某个样本上用 Keras 开发一个状态 LSTM 模型,通常是最近的一个。然后,我们将模型套用到所有样本,以测试和验证模型性能。

  1. example_split <- rolling_origin_resamples$splits[[6]]
  2. example_split_id <- rolling_origin_resamples$id[[6]]

我么可以用 plot_split() 函数可视化该分割,设定 expand_y_axis = FALSE 以便将横坐标缩放到样本本身的范围。

  1. plot_split(
  2. example_split,
  3. expand_y_axis = FALSE,
  4. size = 0.5) +
  5. theme(legend.position = "bottom") +
  6. ggtitle(glue("Split: {example_split_id}"))

数据准备

为了帮助进行超参数调整,除了训练集之外,我们还需要一个验证集。例如,我们将使用一个回调函数 callback_early_stopping,当验证集上没有显着的表现时,它会停止训练(多少算显著由你决定)。

我们将分析集的三分之二用于训练,三分之一用于验证。

  1. df_trn <- analysis(example_split)[1:800, , drop = FALSE]
  2. df_val <- analysis(example_split)[801:1200, , drop = FALSE]
  3. df_tst <- assessment(example_split)

首先,我们将训练和测试数据集合成一个数据集,并使用列 key 来标记它们来自哪个集合(trainingtesting)。请注意,tbl_time 对象需要在调用 bind_rows() 时重新指定索引,但是这个问题应该很快在 dplyr 包中得到纠正。

  1. df <- bind_rows(
  2. df_trn %>% add_column(key = "training"),
  3. df_val %>% add_column(key = "validation"),
  4. df_tst %>% add_column(key = "testing")) %>%
  5. as_tbl_time(index = index)
  6. df
  1. # A time tibble: 1,800 x 3
  2. # Index: index
  3. index value key
  4. <date> <dbl> <chr>
  5. 1 1849-06-01 81.1 training
  6. 2 1849-07-01 78 training
  7. 3 1849-08-01 67.7 training
  8. 4 1849-09-01 93.7 training
  9. 5 1849-10-01 71.5 training
  10. 6 1849-11-01 99 training
  11. 7 1849-12-01 97 training
  12. 8 1850-01-01 78 training
  13. 9 1850-02-01 89.4 training
  14. 10 1850-03-01 82.6 training
  15. # ... with 1,790 more rows

recipe 做数据预处理

LSTM 算法通常要求输入数据经过中心化并标度化。我们可以使用 recipe 包预处理数据。我们用 step_sqrt 来转换数据以减少异常值的影响,再结合 step_centerstep_scale 对数据进行中心化和标度化。最后,数据使用 bake() 函数实现处理转换。

  1. rec_obj <- recipe(
  2. value ~ ., df) %>%
  3. step_sqrt(value) %>%
  4. step_center(value) %>%
  5. step_scale(value) %>%
  6. prep()
  7. df_processed_tbl <- bake(rec_obj, df)
  8. df_processed_tbl
  1. # A tibble: 1,800 x 3
  2. index value key
  3. <date> <dbl> <fct>
  4. 1 1849-06-01 0.714 training
  5. 2 1849-07-01 0.660 training
  6. 3 1849-08-01 0.473 training
  7. 4 1849-09-01 0.922 training
  8. 5 1849-10-01 0.544 training
  9. 6 1849-11-01 1.01 training
  10. 7 1849-12-01 0.974 training
  11. 8 1850-01-01 0.660 training
  12. 9 1850-02-01 0.852 training
  13. 10 1850-03-01 0.739 training
  14. # ... with 1,790 more rows

接着,记录中心化和标度化的信息,以便在建模完成之后可以将数据逆向转换回去。平方根转换可以通过乘方运算逆转回去,但要在逆转中心化和标度化之后。

  1. center_history <- rec_obj$steps[[2]]$means["value"]
  2. scale_history <- rec_obj$steps[[3]]$sds["value"]
  3. c("center" = center_history, "scale" = scale_history)
  1. center.value scale.value
  2. 6.694468 3.238935

调整数据形状

Keras LSTM 希望输入和目标数据具有特定的形状。输入必须是 3 维数组,维度大小为 num_samplesnum_timestepsnum_features

这里,num_samples 是集合中观测的数量。这将以每份 batch_size 大小的分量分批提供给模型。第二个维度 num_timesteps 是我们上面讨论的隐含状态的长度。最后,第三个维度是我们正在使用的预测变量的数量。对于单变量时间序列,这是 1。

隐含状态的长度应该选择多少?这通常取决于数据集和我们的目标。如果我们提前一步预测,即仅预测下个月,我们主要关注的是选择一个状态长度,以便学习数据中存在的任何模式。

现在说我们想要预测 12 个月的数据,就像 SILSO(世界数据中心,用于生产、保存和传播国际太阳黑子观测)所做的。我们通过 Keras 实现这一目标的方法是使 LSTM 隐藏状态与后续输出有相同的长度。因此,如果我们想要产生 12 个月的预测,我们的 LSTM 隐藏状态长度应该是 12。(译注:原始数据的周期大约是 10 到 11 年,使用相邻两年的数据不能涵盖一个完整的周期,致使模型无法学习到和周期有关的模式,最终表现可能不佳。)

然后使用 time_distributed() 包装器将这 12 个时间步连接到 12 个线性预测器单元。该包装器的任务是将相同的计算(即,相同的权重矩阵)应用于它接收的每个状态输入。

目标数组的格式应该是什么?由于我们在这里预测了几个时间步,目标数据也需要是 3 维的。维度 1 同样是批量维度,维度 2 同样对应于时间步(被预测的),维度 3 是包装层的大小。在我们的例子中,包装层是单个单元的 layer_dense(),因为我们希望每个时间点只有一个预测。

所以,让我们调整数据形状。这里的主要动作是用滑动窗口创建长度 12 的输入,后续 12 个观测作为输出。举个更简单的例子,假设我们的输入是从 1 到 10 的数字,我们选择的序列长度(状态大小)是 4,下面就是我们希望我们的训练输入看起来的样子:

  1. 1,2,3,4
  2. 2,3,4,5
  3. 3,4,5,6

相应的目标数据:

  1. 5,6,7,8
  2. 6,7,8,9
  3. 7,8,9,10

我们将定义一个简短的函数,对给定的数据集进行调整。最后,我们形式上添加了需要的第三个维度(即使在我们的例子中该维度的大小为 1)。

  1. # these variables are being defined just because of the order in which
  2. # we present things in this post (first the data, then the model)
  3. # they will be superseded by FLAGS$n_timesteps, FLAGS$batch_size and n_predictions
  4. # in the following snippet
  5. n_timesteps <- 12
  6. n_predictions <- n_timesteps
  7. batch_size <- 10
  8. # functions used
  9. build_matrix <- function(tseries,
  10. overall_timesteps)
  11. {
  12. t(sapply(
  13. 1:(length(tseries) - overall_timesteps + 1),
  14. function(x) tseries[x:(x + overall_timesteps - 1)]))
  15. }
  16. reshape_X_3d <- function(X)
  17. {
  18. dim(X) <- c(dim(X)[1], dim(X)[2], 1)
  19. X
  20. }
  21. # extract values from data frame
  22. train_vals <- df_processed_tbl %>%
  23. filter(key == "training") %>%
  24. select(value) %>%
  25. pull()
  26. valid_vals <- df_processed_tbl %>%
  27. filter(key == "validation") %>%
  28. select(value) %>%
  29. pull()
  30. test_vals <- df_processed_tbl %>%
  31. filter(key == "testing") %>%
  32. select(value) %>%
  33. pull()
  34. # build the windowed matrices
  35. train_matrix <- build_matrix(
  36. train_vals, n_timesteps + n_predictions)
  37. valid_matrix <- build_matrix(
  38. valid_vals, n_timesteps + n_predictions)
  39. test_matrix <- build_matrix(
  40. test_vals, n_timesteps + n_predictions)
  41. # separate matrices into training and testing parts
  42. # also, discard last batch if there are fewer than batch_size samples
  43. # (a purely technical requirement)
  44. X_train <- train_matrix[, 1:n_timesteps]
  45. y_train <- train_matrix[, (n_timesteps + 1):(n_timesteps * 2)]
  46. X_train <- X_train[1:(nrow(X_train) %/% batch_size * batch_size), ]
  47. y_train <- y_train[1:(nrow(y_train) %/% batch_size * batch_size), ]
  48. X_valid <- valid_matrix[, 1:n_timesteps]
  49. y_valid <- valid_matrix[, (n_timesteps + 1):(n_timesteps * 2)]
  50. X_valid <- X_valid[1:(nrow(X_valid) %/% batch_size * batch_size), ]
  51. y_valid <- y_valid[1:(nrow(y_valid) %/% batch_size * batch_size), ]
  52. X_test <- test_matrix[, 1:n_timesteps]
  53. y_test <- test_matrix[, (n_timesteps + 1):(n_timesteps * 2)]
  54. X_test <- X_test[1:(nrow(X_test) %/% batch_size * batch_size), ]
  55. y_test <- y_test[1:(nrow(y_test) %/% batch_size * batch_size), ]
  56. # add on the required third axis
  57. X_train <- reshape_X_3d(X_train)
  58. X_valid <- reshape_X_3d(X_valid)
  59. X_test <- reshape_X_3d(X_test)
  60. y_train <- reshape_X_3d(y_train)
  61. y_valid <- reshape_X_3d(y_valid)
  62. y_test <- reshape_X_3d(y_test)

构建 LSTM 模型

现在我们的数据具有了所需的形式,让我们构建最终模型。与深度学习一样,一项重要且经常耗时的工作是调整超参数。为了使这篇文章保持独立,并且考虑到这主要是关于如何在 R 中使用 LSTM 的教程,让我们假设在经过大量实验后发现了以下设置(实际上实验确实发生了,但没有达到最佳的表现)。

我们没有硬编码超参数,而是使用 tfruns 设置了一个环境,在环境中可以轻松地实现网格搜索。

我们会注释这些参数的作用,但具体含义留到以后再解释。

  1. FLAGS <- flags(
  2. # There is a so-called "stateful LSTM" in Keras. While LSTM is stateful per se,
  3. # this adds a further tweak where the hidden states get initialized with values
  4. # from the item at same position in the previous batch.
  5. # This is helpful just under specific circumstances, or if you want to create an
  6. # "infinite stream" of states, in which case you'd use 1 as the batch size.
  7. # Below, we show how the code would have to be changed to use this, but it won't be further
  8. # discussed here.
  9. flag_boolean("stateful", FALSE),
  10. # Should we use several layers of LSTM?
  11. # Again, just included for completeness, it did not yield any superior performance on this task.
  12. # This will actually stack exactly one additional layer of LSTM units.
  13. flag_boolean("stack_layers", FALSE),
  14. # number of samples fed to the model in one go
  15. flag_integer("batch_size", 10),
  16. # size of the hidden state, equals size of predictions
  17. flag_integer("n_timesteps", 12),
  18. # how many epochs to train for
  19. flag_integer("n_epochs", 100),
  20. # fraction of the units to drop for the linear transformation of the inputs
  21. flag_numeric("dropout", 0.2),
  22. # fraction of the units to drop for the linear transformation of the recurrent state
  23. flag_numeric("recurrent_dropout", 0.2),
  24. # loss function. Found to work better for this specific case than mean squared error
  25. flag_string("loss", "logcosh"),
  26. # optimizer = stochastic gradient descent. Seemed to work better than adam or rmsprop here
  27. # (as indicated by limited testing)
  28. flag_string("optimizer_type", "sgd"),
  29. # size of the LSTM layer
  30. flag_integer("n_units", 128),
  31. # learning rate
  32. flag_numeric("lr", 0.003),
  33. # momentum, an additional parameter to the SGD optimizer
  34. flag_numeric("momentum", 0.9),
  35. # parameter to the early stopping callback
  36. flag_integer("patience", 10))
  37. # the number of predictions we'll make equals the length of the hidden state
  38. n_predictions <- FLAGS$n_timesteps
  39. # how many features = predictors we have
  40. n_features <- 1
  41. # just in case we wanted to try different optimizers, we could add here
  42. optimizer <- switch(
  43. FLAGS$optimizer_type,
  44. sgd = optimizer_sgd(
  45. lr = FLAGS$lr,
  46. momentum = FLAGS$momentum))
  47. # callbacks to be passed to the fit() function
  48. # We just use one here: we may stop before n_epochs if the loss on the validation set
  49. # does not decrease (by a configurable amount, over a configurable time)
  50. callbacks <- list(
  51. callback_early_stopping(
  52. patience = FLAGS$patience))

经过所有这些准备工作,构建和训练模型的代码就相当简短!让我们首先快速查看“长版本”,这将允许你测试堆叠多个 LSTM 或使用状态 LSTM,然后通过最终的短版本(两者都不做)并对其进行评论。

完整的代码,仅供参考。

  1. model <- keras_model_sequential()
  2. model %>%
  3. layer_lstm(
  4. units = FLAGS$n_units,
  5. batch_input_shape = c(
  6. FLAGS$batch_size,
  7. FLAGS$n_timesteps,
  8. n_features),
  9. dropout = FLAGS$dropout,
  10. recurrent_dropout = FLAGS$recurrent_dropout,
  11. return_sequences = TRUE,
  12. stateful = FLAGS$stateful)
  13. if (FLAGS$stack_layers)
  14. {
  15. model %>%
  16. layer_lstm(
  17. units = FLAGS$n_units,
  18. dropout = FLAGS$dropout,
  19. recurrent_dropout = FLAGS$recurrent_dropout,
  20. return_sequences = TRUE,
  21. stateful = FLAGS$stateful)
  22. }
  23. model %>% time_distributed(
  24. layer_dense(units = 1))
  25. model %>%
  26. compile(
  27. loss = FLAGS$loss,
  28. optimizer = optimizer,
  29. metrics = list("mean_squared_error"))
  30. if (!FLAGS$stateful) {
  31. model %>% fit(
  32. x = X_train,
  33. y = y_train,
  34. validation_data = list(X_valid, y_valid),
  35. batch_size = FLAGS$batch_size,
  36. epochs = FLAGS$n_epochs,
  37. callbacks = callbacks)
  38. } else
  39. {
  40. for (i in 1:FLAGS$n_epochs)
  41. {
  42. model %>% fit(
  43. x = X_train,
  44. y = y_train,
  45. validation_data = list(X_valid, y_valid),
  46. callbacks = callbacks,
  47. batch_size = FLAGS$batch_size,
  48. epochs = 1,
  49. shuffle = FALSE)
  50. model %>% reset_states()
  51. }
  52. }
  53. if (FLAGS$stateful)
  54. model %>% reset_states()

现在让我们逐步完成下面更简单但更好(或同样)的配置。

  1. # create the model
  2. model <- keras_model_sequential()
  3. # add layers
  4. # we have just two, the LSTM and the time_distributed
  5. model %>%
  6. layer_lstm(
  7. units = FLAGS$n_units,
  8. # the first layer in a model needs to know the shape of the input data
  9. batch_input_shape = c(
  10. FLAGS$batch_size, FLAGS$n_timesteps, n_features),
  11. dropout = FLAGS$dropout,
  12. recurrent_dropout = FLAGS$recurrent_dropout,
  13. # by default, an LSTM just returns the final state
  14. return_sequences = TRUE) %>%
  15. time_distributed(layer_dense(units = 1))
  16. model %>%
  17. compile(
  18. loss = FLAGS$loss,
  19. optimizer = optimizer,
  20. # in addition to the loss, Keras will inform us about current MSE while training
  21. metrics = list("mean_squared_error"))
  22. history <- model %>% fit(
  23. x = X_train,
  24. y = y_train,
  25. validation_data = list(X_valid, y_valid),
  26. batch_size = FLAGS$batch_size,
  27. epochs = FLAGS$n_epochs,
  28. callbacks = callbacks)

正如我们所见,训练在约 55 个周期后停止,因为验证集损失不再减少。我们还发现验证集上的表现比训练集上的性能差——通常表明过度拟合。

这个话题,我们将在另一个时间单独讨论,但有趣的是,使用更高 dropoutrecurrent_dropout(与增加的模型容量相结合)的正则化并没有产生更好的泛化表现。这可能与我们在介绍中提到的这个特定时间序列的特征有关。

  1. plot(history, metrics = "loss")

现在让我们看看该模型捕捉训练集特征的效果如何。

  1. pred_train <- model %>%
  2. predict(
  3. X_train,
  4. batch_size = FLAGS$batch_size) %>%
  5. .[, , 1]
  6. # Retransform values to original scale
  7. pred_train <- (pred_train * scale_history + center_history) ^2
  8. compare_train <- df %>%
  9. filter(key == "training")
  10. # build a dataframe that has both actual and predicted values
  11. for (i in 1:nrow(pred_train))
  12. {
  13. varname <- paste0("pred_train", i)
  14. compare_train <- mutate(
  15. compare_train,
  16. !!varname := c(
  17. rep(NA, FLAGS$n_timesteps + i - 1),
  18. pred_train[i,],
  19. rep(NA,
  20. nrow(compare_train) - FLAGS$n_timesteps * 2 - i + 1)))
  21. }

我们计算所有预测序列的平均 RSME。

  1. coln <- colnames(compare_train)[4:ncol(compare_train)]
  2. cols <- map(coln, quo(sym(.)))
  3. rsme_train <- map_dbl(
  4. cols,
  5. function(col)
  6. {
  7. rmse(
  8. compare_train,
  9. truth = value,
  10. estimate = !!col,
  11. na.rm = TRUE)
  12. }) %>%
  13. mean()
  14. rsme_train
  1. 21.01495

这些预测看起来如何?由于所有预测序列的可视化看起来会非常拥挤,我们会间隔地选择起始点。

  1. ggplot(
  2. compare_train,
  3. aes(x = index, y = value)) +
  4. geom_line() +
  5. geom_line(aes(y = pred_train1), color = "cyan") +
  6. geom_line(aes(y = pred_train50), color = "red") +
  7. geom_line(aes(y = pred_train100), color = "green") +
  8. geom_line(aes(y = pred_train150), color = "violet") +
  9. geom_line(aes(y = pred_train200), color = "cyan") +
  10. geom_line(aes(y = pred_train250), color = "red") +
  11. geom_line(aes(y = pred_train300), color = "red") +
  12. geom_line(aes(y = pred_train350), color = "green") +
  13. geom_line(aes(y = pred_train400), color = "cyan") +
  14. geom_line(aes(y = pred_train450), color = "red") +
  15. geom_line(aes(y = pred_train500), color = "green") +
  16. geom_line(aes(y = pred_train550), color = "violet") +
  17. geom_line(aes(y = pred_train600), color = "cyan") +
  18. geom_line(aes(y = pred_train650), color = "red") +
  19. geom_line(aes(y = pred_train700), color = "red") +
  20. geom_line(aes(y = pred_train750), color = "green") +
  21. ggtitle("Predictions on the training set")

看起来像当好。对于验证集,我们并不认为有同样好的结果。

  1. pred_test <- model %>%
  2. predict(
  3. X_test,
  4. batch_size = FLAGS$batch_size) %>%
  5. .[, , 1]
  6. # Retransform values to original scale
  7. pred_test <- (pred_test * scale_history + center_history) ^2
  8. pred_test[1:10, 1:5] %>% print()
  9. compare_test <- df %>% filter(key == "testing")
  10. # build a dataframe that has both actual and predicted values
  11. for (i in 1:nrow(pred_test))
  12. {
  13. varname <- paste0("pred_test", i)
  14. compare_test <-mutate(
  15. compare_test,
  16. !!varname := c(
  17. rep(NA, FLAGS$n_timesteps + i - 1),
  18. pred_test[i,],
  19. rep(NA,
  20. nrow(compare_test) - FLAGS$n_timesteps * 2 - i + 1)))
  21. }
  22. compare_test %>% write_csv(
  23. str_replace(model_path, ".hdf5", ".test.csv"))
  24. compare_test[FLAGS$n_timesteps:(FLAGS$n_timesteps + 10), c(2, 4:8)] %>%
  25. print()
  26. coln <- colnames(compare_test)[4:ncol(compare_test)]
  27. cols <- map(coln, quo(sym(.)))
  28. rsme_test <- map_dbl(
  29. cols,
  30. function(col)
  31. {
  32. rmse(
  33. compare_test,
  34. truth = value,
  35. estimate = !!col,
  36. na.rm = TRUE)
  37. }) %>%
  38. mean()
  39. rsme_test
  1. 31.31616
  1. ggplot(
  2. compare_test,
  3. aes(x = index, y = value)) +
  4. geom_line() +
  5. geom_line(aes(y = pred_test1), color = "cyan") +
  6. geom_line(aes(y = pred_test50), color = "red") +
  7. geom_line(aes(y = pred_test100), color = "green") +
  8. geom_line(aes(y = pred_test150), color = "violet") +
  9. geom_line(aes(y = pred_test200), color = "cyan") +
  10. geom_line(aes(y = pred_test250), color = "red") +
  11. geom_line(aes(y = pred_test300), color = "green") +
  12. geom_line(aes(y = pred_test350), color = "cyan") +
  13. geom_line(aes(y = pred_test400), color = "red") +
  14. geom_line(aes(y = pred_test450), color = "green") +
  15. geom_line(aes(y = pred_test500), color = "cyan") +
  16. geom_line(aes(y = pred_test550), color = "violet") +
  17. ggtitle("Predictions on test set")

这不如训练集那么好,但也不错,因为这个时间序列非常具有挑战性。

在手动选择的示例分割中定义并运行我们的模型后,让我们现在回到我们的整体重新抽样框架。

在所有分割上回测模型

为了获得所有分割的预测,我们将上面的代码移动到一个函数中并将其应用于所有分割。它返回包含两个数据框的列表,分别对应训练和测试集,每个数据框包含模型的预测以及实际值。

  1. obtain_predictions <- function(split)
  2. {
  3. df_trn <- analysis(split)[1:800, , drop = FALSE]
  4. df_val <- analysis(split)[801:1200, , drop = FALSE]
  5. df_tst <- assessment(split)
  6. df <- bind_rows(
  7. df_trn %>% add_column(key = "training"),
  8. df_val %>% add_column(key = "validation"),
  9. df_tst %>% add_column(key = "testing")) %>%
  10. as_tbl_time(index = index)
  11. rec_obj <- recipe(
  12. value ~ ., df) %>%
  13. step_sqrt(value) %>%
  14. step_center(value) %>%
  15. step_scale(value) %>%
  16. prep()
  17. df_processed_tbl <- bake(rec_obj, df)
  18. center_history <- rec_obj$steps[[2]]$means["value"]
  19. scale_history <- rec_obj$steps[[3]]$sds["value"]
  20. FLAGS <- flags(
  21. flag_boolean("stateful", FALSE),
  22. flag_boolean("stack_layers", FALSE),
  23. flag_integer("batch_size", 10),
  24. flag_integer("n_timesteps", 12),
  25. flag_integer("n_epochs", 100),
  26. flag_numeric("dropout", 0.2),
  27. flag_numeric("recurrent_dropout", 0.2),
  28. flag_string("loss", "logcosh"),
  29. flag_string("optimizer_type", "sgd"),
  30. flag_integer("n_units", 128),
  31. flag_numeric("lr", 0.003),
  32. flag_numeric("momentum", 0.9),
  33. flag_integer("patience", 10))
  34. n_predictions <- FLAGS$n_timesteps
  35. n_features <- 1
  36. optimizer <- switch(
  37. FLAGS$optimizer_type,
  38. sgd = optimizer_sgd(
  39. lr = FLAGS$lr, momentum = FLAGS$momentum))
  40. callbacks <- list(
  41. callback_early_stopping(patience = FLAGS$patience))
  42. train_vals <- df_processed_tbl %>%
  43. filter(key == "training") %>%
  44. select(value) %>%
  45. pull()
  46. valid_vals <- df_processed_tbl %>%
  47. filter(key == "validation") %>%
  48. select(value) %>%
  49. pull()
  50. test_vals <- df_processed_tbl %>%
  51. filter(key == "testing") %>%
  52. select(value) %>%
  53. pull()
  54. train_matrix <- build_matrix(
  55. train_vals, FLAGS$n_timesteps + n_predictions)
  56. valid_matrix <- build_matrix(
  57. valid_vals, FLAGS$n_timesteps + n_predictions)
  58. test_matrix <- build_matrix(
  59. test_vals, FLAGS$n_timesteps + n_predictions)
  60. X_train <- train_matrix[, 1:FLAGS$n_timesteps]
  61. y_train <- train_matrix[, (FLAGS$n_timesteps + 1):(FLAGS$n_timesteps * 2)]
  62. X_train <- X_train[1:(nrow(X_train) %/% FLAGS$batch_size * FLAGS$batch_size),]
  63. y_train <- y_train[1:(nrow(y_train) %/% FLAGS$batch_size * FLAGS$batch_size),]
  64. X_valid <- valid_matrix[, 1:FLAGS$n_timesteps]
  65. y_valid <- valid_matrix[, (FLAGS$n_timesteps + 1):(FLAGS$n_timesteps * 2)]
  66. X_valid <- X_valid[1:(nrow(X_valid) %/% FLAGS$batch_size * FLAGS$batch_size),]
  67. y_valid <- y_valid[1:(nrow(y_valid) %/% FLAGS$batch_size * FLAGS$batch_size),]
  68. X_test <- test_matrix[, 1:FLAGS$n_timesteps]
  69. y_test <- test_matrix[, (FLAGS$n_timesteps + 1):(FLAGS$n_timesteps * 2)]
  70. X_test <- X_test[1:(nrow(X_test) %/% FLAGS$batch_size * FLAGS$batch_size),]
  71. y_test <- y_test[1:(nrow(y_test) %/% FLAGS$batch_size * FLAGS$batch_size),]
  72. X_train <- reshape_X_3d(X_train)
  73. X_valid <- reshape_X_3d(X_valid)
  74. X_test <- reshape_X_3d(X_test)
  75. y_train <- reshape_X_3d(y_train)
  76. y_valid <- reshape_X_3d(y_valid)
  77. y_test <- reshape_X_3d(y_test)
  78. model <- keras_model_sequential()
  79. model %>%
  80. layer_lstm(
  81. units = FLAGS$n_units,
  82. batch_input_shape = c(
  83. FLAGS$batch_size, FLAGS$n_timesteps, n_features),
  84. dropout = FLAGS$dropout,
  85. recurrent_dropout = FLAGS$recurrent_dropout,
  86. return_sequences = TRUE) %>%
  87. time_distributed(layer_dense(units = 1))
  88. model %>%
  89. compile(
  90. loss = FLAGS$loss,
  91. optimizer = optimizer,
  92. metrics = list("mean_squared_error"))
  93. model %>% fit(
  94. x = X_train,
  95. y = y_train,
  96. validation_data = list(X_valid, y_valid),
  97. batch_size = FLAGS$batch_size,
  98. epochs = FLAGS$n_epochs,
  99. callbacks = callbacks)
  100. pred_train <- model %>%
  101. predict(
  102. X_train,
  103. batch_size = FLAGS$batch_size) %>%
  104. .[, , 1]
  105. # Retransform values
  106. pred_train <- (pred_train * scale_history + center_history) ^ 2
  107. compare_train <- df %>% filter(key == "training")
  108. for (i in 1:nrow(pred_train))
  109. {
  110. varname <- paste0("pred_train", i)
  111. compare_train <- mutate(
  112. compare_train,
  113. !!varname := c(
  114. rep(NA, FLAGS$n_timesteps + i - 1),
  115. pred_train[i, ],
  116. rep(NA,
  117. nrow(compare_train) - FLAGS$n_timesteps * 2 - i + 1)))
  118. }
  119. pred_test <- model %>%
  120. predict(
  121. X_test,
  122. batch_size = FLAGS$batch_size) %>%
  123. .[, , 1]
  124. # Retransform values
  125. pred_test <- (pred_test * scale_history + center_history) ^ 2
  126. compare_test <- df %>% filter(key == "testing")
  127. for (i in 1:nrow(pred_test))
  128. {
  129. varname <- paste0("pred_test", i)
  130. compare_test <- mutate(
  131. compare_test,
  132. !!varname := c(
  133. rep(NA, FLAGS$n_timesteps + i - 1),
  134. pred_test[i, ],
  135. rep(NA,
  136. nrow(compare_test) - FLAGS$n_timesteps * 2 - i + 1)))
  137. }
  138. list(
  139. train = compare_train,
  140. test = compare_test)
  141. }

将函数应用到所有分割上,得到一系列预测。

  1. all_split_preds <- rolling_origin_resamples %>%
  2. mutate(predict = map(splits, obtain_predictions))

计算所有分割的 RMSE:

  1. calc_rmse <- function(df)
  2. {
  3. coln <- colnames(df)[4:ncol(df)]
  4. cols <- map(coln, quo(sym(.)))
  5. map_dbl(
  6. cols,
  7. function(col)
  8. {
  9. rmse(
  10. df, truth = value,
  11. estimate = !!col, na.rm = TRUE)
  12. }) %>%
  13. mean()
  14. }
  15. all_split_preds <- all_split_preds %>% unnest(predict)
  16. all_split_preds_train <- all_split_preds[seq(1, 11, by = 2), ]
  17. all_split_preds_test <- all_split_preds[seq(2, 12, by = 2), ]
  18. all_split_rmses_train <- all_split_preds_train %>%
  19. mutate(rmse = map_dbl(predict, calc_rmse)) %>%
  20. select(id, rmse)
  21. all_split_rmses_test <- all_split_preds_test %>%
  22. mutate(rmse = map_dbl(predict, calc_rmse)) %>%
  23. select(id, rmse)

这是 6 个分割的 RMSE。

  1. all_split_rmses_train
  1. # A tibble: 6 x 2
  2. id rmse
  3. <chr> <dbl>
  4. 1 Slice1 22.2
  5. 2 Slice2 20.9
  6. 3 Slice3 18.8
  7. 4 Slice4 23.5
  8. 5 Slice5 22.1
  9. 6 Slice6 21.1
  1. all_split_rmses_test
  1. # A tibble: 6 x 2
  2. id rmse
  3. <chr> <dbl>
  4. 1 Slice1 21.6
  5. 2 Slice2 20.6
  6. 3 Slice3 21.3
  7. 4 Slice4 31.4
  8. 5 Slice5 35.2
  9. 6 Slice6 31.4

在这些数字中,我们看到了一些有趣的东西:时间序列的前三个分割上的泛化表现比后者更好。这证实了我们的印象,如上所述,数据似乎有一些隐藏的变化发展,这使预测更加困难。

这里是相应训练和测试集的预测可视化。

首先,训练集:

  1. plot_train <- function(slice,
  2. name)
  3. {
  4. ggplot(
  5. slice,
  6. aes(x = index, y = value)) +
  7. geom_line() +
  8. geom_line(aes(y = pred_train1), color = "cyan") +
  9. geom_line(aes(y = pred_train50), color = "red") +
  10. geom_line(aes(y = pred_train100), color = "green") +
  11. geom_line(aes(y = pred_train150), color = "violet") +
  12. geom_line(aes(y = pred_train200), color = "cyan") +
  13. geom_line(aes(y = pred_train250), color = "red") +
  14. geom_line(aes(y = pred_train300), color = "red") +
  15. geom_line(aes(y = pred_train350), color = "green") +
  16. geom_line(aes(y = pred_train400), color = "cyan") +
  17. geom_line(aes(y = pred_train450), color = "red") +
  18. geom_line(aes(y = pred_train500), color = "green") +
  19. geom_line(aes(y = pred_train550), color = "violet") +
  20. geom_line(aes(y = pred_train600), color = "cyan") +
  21. geom_line(aes(y = pred_train650), color = "red") +
  22. geom_line(aes(y = pred_train700), color = "red") +
  23. geom_line(aes(y = pred_train750), color = "green") +
  24. ggtitle(name)
  25. }
  26. train_plots <- map2(
  27. all_split_preds_train$predict,
  28. all_split_preds_train$id, plot_train)
  29. p_body_train <- plot_grid(
  30. plotlist = train_plots, ncol = 3)
  31. p_title_train <- ggdraw() +
  32. draw_label(
  33. "Backtested Predictions: Training Sets",
  34. size = 18, fontface = "bold")
  35. plot_grid(
  36. p_title_train, p_body_train,
  37. ncol = 1,
  38. rel_heights = c(0.05, 1, 0.05))

接着是测试集:

  1. plot_test <- function(slice,
  2. name)
  3. {
  4. ggplot(
  5. slice, aes(x = index, y = value)) +
  6. geom_line() +
  7. geom_line(aes(y = pred_test1), color = "cyan") +
  8. geom_line(aes(y = pred_test50), color = "red") +
  9. geom_line(aes(y = pred_test100), color = "green") +
  10. geom_line(aes(y = pred_test150), color = "violet") +
  11. geom_line(aes(y = pred_test200), color = "cyan") +
  12. geom_line(aes(y = pred_test250), color = "red") +
  13. geom_line(aes(y = pred_test300), color = "green") +
  14. geom_line(aes(y = pred_test350), color = "cyan") +
  15. geom_line(aes(y = pred_test400), color = "red") +
  16. geom_line(aes(y = pred_test450), color = "green") +
  17. geom_line(aes(y = pred_test500), color = "cyan") +
  18. geom_line(aes(y = pred_test550), color = "violet") +
  19. ggtitle(name)
  20. }
  21. test_plots <- map2(
  22. all_split_preds_test$predict,
  23. all_split_preds_test$id, plot_test)
  24. p_body_test <- plot_grid(
  25. plotlist = test_plots, ncol = 3)
  26. p_title_test <- ggdraw() +
  27. draw_label(
  28. "Backtested Predictions: Test Sets",
  29. size = 18, fontface = "bold")
  30. plot_grid(
  31. p_title_test, p_body_test,
  32. ncol = 1, rel_heights = c(0.05, 1, 0.05))

这是一个很长的帖子,必然会留下很多问题,首先是我们如何获得好的超参数设置(学习率、周期数、dropout)? 我们如何选择隐含状态的长度?或者甚至,我们能否直观了解 LSTM 在给定数据集上的表现(具有其特定特征)?我们将在未来的文章中解决上述问题。

时间序列深度学习:seq2seq 模型预测太阳黑子的更多相关文章

  1. 时间序列深度学习:状态 LSTM 模型预测太阳黑子

    目录 时间序列深度学习:状态 LSTM 模型预测太阳黑子 教程概览 商业应用 长短期记忆(LSTM)模型 太阳黑子数据集 构建 LSTM 模型预测太阳黑子 1 若干相关包 2 数据 3 探索性数据分析 ...

  2. 时间序列深度学习:状态 LSTM 模型预測太阳黑子(一)

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/kMD8d5R/article/details/82111558 作者:徐瑞龙,量化分析师,R语言中文 ...

  3. NVIDIA GPUs上深度学习推荐模型的优化

    NVIDIA GPUs上深度学习推荐模型的优化 Optimizing the Deep Learning Recommendation Model on NVIDIA GPUs 推荐系统帮助人在成倍增 ...

  4. deeplearning.ai学习seq2seq模型

    一.seq2seq架构图 seq2seq模型左边绿色的部分我们称之为encoder,左边的循环输入最终生成一个固定向量作为右侧的输入,右边紫色的部分我们称之为decoder.单看右侧这个结构跟我们之前 ...

  5. 深度学习VGG16模型核心模块拆解

    原文连接:https://blog.csdn.net/qq_40027052/article/details/79015827 注:这篇文章是上面连接作者的文章.在此仅作学习记录作用. 如今深度学习发 ...

  6. 在排序模型方面,点评搜索也经历了业界比较普遍的迭代过程:从早期的线性模型LR,到引入自动二阶交叉特征的FM和FFM,到非线性树模型GBDT和GBDT+LR,到最近全面迁移至大规模深度学习排序模型。

    https://mp.weixin.qq.com/s/wjgoH6-eJQDL1KUQD3aQUQ 大众点评搜索基于知识图谱的深度学习排序实践 原创: 非易 祝升 仲远 美团技术团队 前天    

  7. MXNET:深度学习计算-模型参数

    我们将深入讲解模型参数的访问和初始化,以及如何在多个层之间共享同一份参数. 之前我们一直在使用默认的初始函数,net.initialize(). from mxnet import init, nd ...

  8. MXNET:深度学习计算-模型构建

    进入更深的层次:模型构造.参数访问.自定义层和使用 GPU. 模型构建 在多层感知机的实现中,我们首先构造 Sequential 实例,然后依次添加两个全连接层.其中第一层的输出大小为 256,即隐藏 ...

  9. 深度学习中的Normalization模型

    Batch Normalization(简称 BN)自从提出之后,因为效果特别好,很快被作为深度学习的标准工具应用在了各种场合.BN 大法虽然好,但是也存在一些局限和问题,诸如当 BatchSize ...

随机推荐

  1. eclipse使用git命令行

    idea自带git命令,可以很方便的进行提交代码.eclipse怎么做呢,下面我简单操作一下: 第一步: 第二步: 第三步: 这样就调出来git提交的命令窗口了: 运行成功如下: 注意: git的安装 ...

  2. C++ 随机数字以及随机数字加字母生成

    #include <time.h>#include <sys/timeb.h>void MainWindow::slot_clicked(){ QString strRand; ...

  3. Oracle EBS 附件功能

    SELECT fde.table_name, fde.data_object_code, fdet.user_entity_name, fdet.user_entity_prompt, fat.app ...

  4. l2dct

    http://paste.ubuntu.com/15664711/ diff -crbB ns-allinone-2.35/ns-2.35/queue/red.cc ns-2.35/queue/red ...

  5. SQL SERVER Management Studio编写SQL时没有智能提示的解决方式

    1. 检查设置里是否启用智能感知(Intellisence),可以在“工具”→“选项”里设置 2. 如果启用后还是无效,可以新建一个查询窗口查询,输入关键词的前面几个字母看是否有提示(或者使用Ctrl ...

  6. 高性能网站架构缓存——redis集群

    相信你已经对redis有一定的了解,并能够安装上,进行简单的使用了,但是在咱们的实际应用中,使用redis肯定不会使用单机版,不光是redis不能使用单机版,其他的也不会使用,所以今天我们来说一下re ...

  7. [Luogu P4143] 采集矿石 [2018HN省队集训D5T3] 望乡台platform

    [Luogu P4143] 采集矿石 [2018HN省队集训D5T3] 望乡台platform 题意 给定一个小写字母构成的字符串, 每个字符有一个非负权值. 输出所有满足权值和等于这个子串在所有本质 ...

  8. 2018 徐州赛区网赛 G. Trace

    题目链接在这里 题意是:按时间先后有许多左下角固定为(0,0),右上角为(xi,yi)的矩形浪潮,每次浪潮会留下痕迹,但是后来的浪潮又会冲刷掉自己区域的老痕,留下新痕迹,问最后留下的痕迹长度为多少? ...

  9. iOS 网络缓存总结

    一.缓存策略: 1.缓存策略的配置: 缺省缓存策略的存储策略需要服务器的响应配置: 缺省缓存策略的使用需要请求端的配置: 2.缓存策略的缺陷: 移动端比较通用的缓存策略是先使用缓存同时更新本地数据: ...

  10. HBase学习之路 (十)HBase表的设计原则

    建表高级属性 下面几个 shell 命令在 hbase 操作中可以起到很大的作用,且主要体现在建表的过程中,看 下面几个 create 属性 1. BLOOMFILTER 默认是 NONE 是否使用布 ...