leonsimon23 commited on
Commit
6bb3aba
·
verified ·
1 Parent(s): 45f9119

Create app.R

Browse files
Files changed (1) hide show
  1. app.R +1029 -0
app.R ADDED
@@ -0,0 +1,1029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------- 数据预处理 ----------------------------
2
+ # rm(list=ls()) # 在 Spaces 中不推荐清空环境变量,每个运行都是独立的
3
+ # setwd("/users/songyingxiao/desktop/rworkspace") # 在 Spaces 中不推荐设置工作目录,使用相对路径
4
+
5
+ # 加载分析所需库
6
+ library(zoo) # 时间序列插值
7
+ library(forecast) # 时间序列预测
8
+ library(tseries) # 平稳性检验
9
+ library(ggplot2) # 可视化
10
+ library(uroot) # 季节性单位根检验
11
+ library(readxl) # 读取Excel数据
12
+ library(dplyr) # 数据处理
13
+ library(lubridate) # 日期处理
14
+ library(prophet) # Prophet模型
15
+ library(ggpubr) # 增强的可视化功能
16
+ library(patchwork) # 图形组合
17
+ library(scales) # 图形比例尺
18
+ library(parallel) # 并行计算
19
+ library(doParallel) # 并行计算
20
+ library(tidyr) # 用于 pivot_longer
21
+
22
+ # 为了解决中文乱码问题,可能需要设置字体
23
+ # 如果 Dockerfile 中安装了中文字体,这里可以尝试设置
24
+ # if (capabilities("cairo")) {
25
+ # # For cairo-based devices (e.g., png, svg)
26
+ # # For specific font files, you might need to use extrafont package.
27
+ # # For simplicity, if fonts-wqy-zenhei is installed, ggplot2 might pick it up.
28
+ # # Alternatively, use sysfonts and showtext for font handling in R.
29
+ # # library(sysfonts)
30
+ # # library(showtext)
31
+ # # font_add("SimHei", regular = "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc")
32
+ # # showtext_auto()
33
+ # }
34
+
35
+
36
+ # ---------------------------- 1. 数据清洗 ----------------------------
37
+ # 1.1 读取数据
38
+ df <- read_excel('gmqrkl.xlsx')
39
+
40
+ # 1.2 处理零值:将Value列中的0转换为缺失值
41
+ df$Value[df$Value == 0] <- NA
42
+
43
+ # 缺失值插值(线性插值)
44
+ df$Value <- na.approx(df$Value, rule = 2, method = "linear")
45
+
46
+ # 1.3 异常值检测与处理(Z-score法)
47
+ z_scores <- abs((df$Value - mean(df$Value, na.rm = TRUE)) / sd(df$Value, na.rm = TRUE))
48
+ threshold <- 3
49
+ outliers <- df[z_scores > threshold, ]
50
+ print("检测到的异常值:")
51
+ print(outliers)
52
+
53
+ # ---------------------------- 2. 时间序列转换 ----------------------------
54
+ ts_data <- ts(df$Value, start = c(2023, 1), frequency = 365)
55
+
56
+ # ---------------------------- 3. 平稳性检验与差分 ----------------------------
57
+ make_stationary <- function(data, max_diff = 3) {
58
+ diff_order <- 0 # 初始化差分阶数为 0
59
+ current_data <- data # 当前处理的时间序列数据
60
+
61
+ while(diff_order <= max_diff) { # 循环进行平稳性检验,直到达到最大差分阶数或数据平稳
62
+ # 检查数据长度是否足够进行 ADF 检验
63
+ if (length(current_data) <= 1) {
64
+ message("数据长度不足,无法进行ADF检验或进一步差分。")
65
+ break
66
+ }
67
+ adf_test <- adf.test(current_data, alternative = "stationary") # 进行ADF检验
68
+
69
+ # par(mfrow = c(2,1)) # 在非交互式环境中直接 plot 可能不会显示
70
+ # plot(current_data, main = paste("差分阶数 d =", diff_order), family = "SimHei") # 绘制时间序列图
71
+ # acf(current_data, main = paste("ACF | d =", diff_order), family = "SimHei") # 绘制自相关函数图
72
+
73
+ if(adf_test$p.value < 0.05) break # 如果ADF检验的 p 值小于 0.05,认为数据平稳,退出循环
74
+
75
+ current_data <- diff(current_data) # 对数据进行一次差分
76
+ diff_order <- diff_order + 1 # 差分阶数加 1
77
+ }
78
+
79
+ # par(mfrow = c(1,1)) # 恢复默认图形布局
80
+ return(list(stationary_data = current_data, d = diff_order)) # 返回平稳化后的数据和差分阶数
81
+ }
82
+
83
+ # 调用函数
84
+ stationary_result <- make_stationary(ts_data) # 传入时间序列数据 ts_data
85
+ ts_stationary <- stationary_result$stationary_data # 获取平稳化后的数据
86
+ d_order <- stationary_result$d # 获取差分阶数
87
+
88
+
89
+ # ---------------------------- 4. 白噪声检验 ----------------------------
90
+ # 确保 ts_stationary 有足够的长度
91
+ if (length(ts_stationary) < 2) {
92
+ stop("平稳化后的序列过短,无法进行白噪声检验。")
93
+ }
94
+
95
+ lb_lag <- min(2*d_order, length(ts_stationary)%/%5)
96
+ if (lb_lag == 0) { # 避免 lag=0 的情况
97
+ lb_lag <- 1 # 至少设置为1
98
+ }
99
+
100
+ lb_test <- Box.test(ts_stationary,
101
+ lag = lb_lag,
102
+ type = "Ljung-Box")
103
+
104
+ if(lb_test$p.value > 0.05) {
105
+ stop("序列为白噪声,无需进一步分析")
106
+ } else {
107
+ message("通过白噪声检验,p-value = ", round(lb_test$p.value,4))
108
+ }
109
+ #差分为0
110
+ if (d_order == 0) {
111
+ lb_test <- Box.test(ts_stationary, lag = min(10, length(ts_stationary) %/% 5), type = "Ljung-Box")
112
+ } else {
113
+ lb_test <- Box.test(ts_stationary, lag = min(2 * d_order, length(ts_stationary) %/% 5), type = "Ljung-Box")
114
+ }
115
+
116
+ if (lb_test$p.value > 0.05) {
117
+ stop("序列为白噪声,无需进一步分析")
118
+ } else {
119
+ message("通过白噪声检验,p-value = ", round(lb_test$p.value, 4))
120
+ }
121
+
122
+
123
+ # ---------------------------- 5. 季节性检验与处理 ----------------------------
124
+ # 方法1:季节单位根检验(确定是否需要季节差分���
125
+ # 确保 ts_stationary 有足够的长度和周期
126
+ if (length(ts_stationary) < 365 * 2) { # 至少需要两个周期的数据
127
+ message("数据长度不足,可能无法进行可靠的季节性检验(年周期)。")
128
+ ts_obj <- ts(ts_stationary, frequency = 7) # 尝试使用周频率
129
+ seasonal_diff_order <- nsdiffs(ts_obj, test = "ch")
130
+ } else {
131
+ ts_obj <- ts(ts_stationary, frequency = 365)
132
+ seasonal_diff_order <- nsdiffs(ts_obj, test = "ch")
133
+ }
134
+
135
+
136
+ if(seasonal_diff_order > 0) {
137
+ ts_seasonal <- diff(ts_obj, lag = frequency(ts_obj), differences = seasonal_diff_order)
138
+ message("执行", seasonal_diff_order, "阶季节差分")
139
+ } else {
140
+ ts_seasonal <- ts_obj
141
+ message("无需季节差分")
142
+ }
143
+
144
+ # 方法2:STL分解处理多重季节性
145
+ # 确保数据长度足以进行多重季节性分解
146
+ if (length(ts_stationary) < 365 * 2) {
147
+ message("数据长度不足,可能无法进行可靠的STL多季节性分解(年周期)。跳过此步骤。")
148
+ stl_plot <- NULL # 设置为NULL避免后续错误
149
+ } else {
150
+ msts_obj <- msts(ts_stationary, seasonal.periods = c(7, 30, 365))
151
+ stl_decomp <- mstl(msts_obj)
152
+
153
+ # 可视化分解结果
154
+ stl_plot <- autoplot(stl_decomp) +
155
+ ggtitle("STL多季节性分解(周+月+年)") +
156
+ theme_bw() +
157
+ theme(text = element_text(family = "SimHei"))
158
+ # print(stl_plot) # 在 Spaces 中,最后统一打印或保存
159
+ }
160
+
161
+ # 提取季节调整后序列
162
+ if (!is.null(stl_plot)) {
163
+ ts_season_adj <- stl_decomp[, "Trend"] + stl_decomp[, "Remainder"]
164
+ } else {
165
+ ts_season_adj <- ts_stationary # 如果跳过STL,则使用原始平稳化数据
166
+ }
167
+
168
+
169
+ # 方法3:Hegyi检验(显式检验周/年季节性)
170
+ # 周季节性检验(周期7天)
171
+ if (length(ts_data) < 7 * 2) {
172
+ message("数据长度不足,无法进行周季节性Hegyi检验。")
173
+ hegy_weekly <- NULL
174
+ } else {
175
+ ts_weekly <- ts(ts_data, frequency = 7)
176
+ hegy_weekly <- hegy.test(ts_weekly, deterministic = c(1,0,0)) # 含常数项,无趋势项
177
+ summary(hegy_weekly) # 输出检验结果(p<0.05表示存在季节性)
178
+ }
179
+
180
+ # 月季节性检验(周期30天)
181
+ if (length(ts_data) < 30 * 2) {
182
+ message("数据长度不足,无法进行月季节性Hegyi检验。")
183
+ hegy_month <- NULL
184
+ } else {
185
+ ts_month <- ts(ts_data, frequency = 30)
186
+ hegy_month <- hegy.test(ts_month, deterministic = c(1, 0, 0))
187
+ summary(hegy_month)
188
+ }
189
+
190
+ # 年季节性检验(周期365天)
191
+ if (length(ts_data) < 365 * 2) {
192
+ message("数据长度不足,无法进行年季节性Hegyi检验。")
193
+ hegy_annual <- NULL
194
+ } else {
195
+ ts_annual <- ts(ts_data, frequency = 365)
196
+ hegy_annual <- hegy.test(ts_annual, deterministic = c(1, 0, 0))
197
+ summary(hegy_annual)
198
+ }
199
+
200
+
201
+ # ---------------------------- 6. 窗口大小优化 ----------------------------
202
+ ts_values <- as.numeric(df$Value)
203
+
204
+ # 评估函数
205
+ evaluate_window <- function(window_size) {
206
+ n <- length(ts_values)
207
+ if (window_size >= n) return(list(mae = Inf, rmse = Inf))
208
+
209
+ # 确保训练数据至少有足够的点进行 auto.arima 训练
210
+ # auto.arima 至少需要一些点才能运行,例如 10-20 点
211
+ if (window_size < 20) { # 设置一个合理的最小窗口大小
212
+ return(list(mae = Inf, rmse = Inf))
213
+ }
214
+
215
+ errors <- numeric(n - window_size)
216
+ for (i in 1:(n - window_size)) {
217
+ train <- ts_values[i:(i + window_size - 1)]
218
+ test <- ts_values[i + window_size]
219
+
220
+ # 确保训练数据有足够长度进行 ARIMA 建模
221
+ if (length(train) < 2) { # auto.arima 通常需要更多数据
222
+ errors[i] <- NA # 标记为NA或跳过
223
+ next
224
+ }
225
+
226
+ model <- tryCatch({
227
+ forecast::auto.arima(
228
+ train,
229
+ d = 0, # 这里固定了 d=0,因为前面已经处理了平稳性
230
+ max.p = 3, max.q = 3,
231
+ stepwise = TRUE
232
+ )
233
+ }, error = function(e) {
234
+ message("auto.arima error: ", e$message, " for window_size ", window_size, " at iteration ", i)
235
+ return(NULL) # 返回NULL表示模型训练失败
236
+ })
237
+
238
+ if (is.null(model)) {
239
+ errors[i] <- NA
240
+ next
241
+ }
242
+
243
+ fc <- forecast::forecast(model, h = 1)
244
+ errors[i] <- test - fc$mean[1]
245
+ }
246
+
247
+ # 移除NA值后计算
248
+ errors <- errors[!is.na(errors)]
249
+ if (length(errors) == 0) {
250
+ return(list(mae = Inf, rmse = Inf))
251
+ }
252
+ return(list(mae = mean(abs(errors)), rmse = sqrt(mean(errors^2))))
253
+ }
254
+
255
+ # 并行计算优化
256
+ num_cores <- detectCores(logical = FALSE)
257
+ if (num_cores > 1) {
258
+ cl <- makeCluster(num_cores)
259
+ registerDoParallel(cl)
260
+ } else {
261
+ message("检测到单核CPU,将不使用并行计算。")
262
+ registerDoSEQ() # 注册顺序执行,以防万一
263
+ }
264
+
265
+
266
+ window_sizes <- seq(70, 210, by = 7)
267
+ # 过滤掉过大的窗口大小,避免 window_size >= n 导致循环无法进行
268
+ window_sizes <- window_sizes[window_sizes < length(ts_values) - 1]
269
+
270
+ if (length(window_sizes) == 0) {
271
+ stop("可用的窗口大小范围为空,无法进行窗口优化。")
272
+ }
273
+
274
+ results <- foreach(ws = window_sizes, .combine = rbind) %dopar% {
275
+ res <- evaluate_window(ws)
276
+ c(window_size = ws, mae = res$mae, rmse = res$rmse)
277
+ }
278
+
279
+ if (exists("cl") && class(cl) == "cluster") { # 检查集群是否已创建再停止
280
+ stopCluster(cl)
281
+ }
282
+
283
+ # 可视化窗口大小与误差关系
284
+ results_df <- as.data.frame(results)
285
+ if (nrow(results_df) == 0) {
286
+ message("没有有效的窗口优化结果,跳过窗口优化图表。")
287
+ window_plot <- NULL
288
+ best_mae_window <- 100 # 设置一个默认值
289
+ best_rmse_window <- 100 # 设置一个默认值
290
+ } else {
291
+ window_plot <- ggplot(results_df, aes(x = window_size)) +
292
+ geom_line(aes(y = mae, color = "MAE"), size = 1) +
293
+ geom_line(aes(y = rmse, color = "RMSE"), size = 1) +
294
+ geom_point(aes(y = mae, color = "MAE"), size = 2) +
295
+ geom_point(aes(y = rmse, color = "RMSE"), size = 2) +
296
+ labs(title = "窗口大小对预测误差的影响",
297
+ x = "训练窗口天数", y = "误差值",
298
+ color = "指标") +
299
+ theme_minimal() +
300
+ theme(text = element_text(family = "SimHei", size = 12),
301
+ legend.position = "top")
302
+
303
+ # print(window_plot)
304
+
305
+ # 输出最优窗口
306
+ best_mae_window <- window_sizes[which.min(results_df$mae)]
307
+ best_rmse_window <- window_sizes[which.min(results_df$rmse)]
308
+ cat("最优窗口(MAE):", best_mae_window, "天\n")
309
+ cat("最优窗口(RMSE):", best_rmse_window, "天\n")
310
+ }
311
+
312
+
313
+ # ---------------------------- 7. 动态窗口划分 ----------------------------
314
+ dynamic_split <- function(data, current_date, window_size = best_mae_window) {
315
+ data %>%
316
+ mutate(Date = lubridate::ymd(Date)) %>%
317
+ filter(Date >= current_date - days(window_size - 1),
318
+ Date <= current_date) %>%
319
+ arrange(Date) %>%
320
+ list(
321
+ train = .,
322
+ test_1w = filter(data, Date > current_date, Date <= current_date + weeks(1)),
323
+ test_4w = filter(data, Date > current_date, Date <= current_date + weeks(4))
324
+ )
325
+ }
326
+
327
+ df$Date <- lubridate::ymd(df$Date) # 确保 df$Date 是日期类型
328
+
329
+ start_date <- min(df$Date) + days(best_mae_window)
330
+ end_date <- max(df$Date) - weeks(4)
331
+
332
+ # 确保 start_date 不在 end_date 之后
333
+ if (start_date > end_date) {
334
+ stop("数据不足以进行动态窗口划分,请检查数据长度和窗口大小。")
335
+ }
336
+ current_dates <- seq(start_date, end_date, by = "week")
337
+
338
+ if (length(current_dates) == 0) {
339
+ stop("无法生成 current_dates 序列,请检查日期范围和数据长度。")
340
+ }
341
+
342
+ ############################################################################
343
+ # ---------------------------- 8. 模型定义 ----------------------------
344
+ # 8.1 SARIMA模型函数 - 修复:添加h参数控制预测长度
345
+ sarima_model <- function(train_data, h = 28) {
346
+ # 确保 train_data$Value 有足够的长度
347
+ if (length(train_data$Value) < 2) {
348
+ message("SARIMA 训练数据不足,返回NA预测。")
349
+ return(list(mean = rep(NA, h)))
350
+ }
351
+ ts_data <- ts(train_data$Value, frequency = 7) # 假设周季节性
352
+ model <- tryCatch({
353
+ auto.arima(ts_data, seasonal = TRUE)
354
+ }, error = function(e) {
355
+ message("SARIMA 模型训练失败: ", e$message)
356
+ return(NULL)
357
+ })
358
+
359
+ if (is.null(model)) {
360
+ return(list(mean = rep(NA, h)))
361
+ }
362
+ fc <- forecast(model, h = h)
363
+ # 确保返回的预测值长度正确
364
+ if (length(fc$mean) < h) {
365
+ fc$mean <- c(fc$mean, rep(NA, h - length(fc$mean)))
366
+ }
367
+ return(fc)
368
+ }
369
+
370
+ # 8.2 Prophet模型函数(修改后)
371
+ prophet_model <- function(train_data, test_dates) {
372
+ df_prophet <- train_data %>% rename(ds = Date, y = Value)
373
+
374
+ # 确保 Prophet 训练数据有足够的行数
375
+ if (nrow(df_prophet) < 2) {
376
+ message("Prophet 训练数据不足,返回NA预测。")
377
+ return(tibble(Date = test_dates, Value = rep(NA, length(test_dates))))
378
+ }
379
+
380
+ # 使用全量数据作为训练集,预测最后四周的测试集
381
+ model <- tryCatch({
382
+ prophet(df_prophet,
383
+ yearly.seasonality = TRUE,
384
+ weekly.seasonality = TRUE)
385
+ }, error = function(e) {
386
+ message("Prophet 模型训练失败: ", e$message)
387
+ return(NULL)
388
+ })
389
+
390
+ if (is.null(model)) {
391
+ return(tibble(Date = test_dates, Value = rep(NA, length(test_dates))))
392
+ }
393
+
394
+ future <- make_future_dataframe(model, periods = length(test_dates), freq = "day")
395
+ fc <- predict(model, future)
396
+
397
+ tibble(
398
+ Date = test_dates,
399
+ Value = tail(fc$yhat, length(test_dates)) # 确保长度一致
400
+ )
401
+ }
402
+
403
+ # 8.3 加权平均组合模型(修改后)
404
+ weighted_average_model <- function(train_data, test_dates) {
405
+ # 验证集:从全量数据中提取最后四周
406
+ # 确保 train_data 有足够的历史数据来创建验证集
407
+ validation_start_date <- max(train_data$Date) - weeks(4) + days(1) # 从倒数四周的开始日期
408
+ validation_data <- train_data %>%
409
+ arrange(Date) %>%
410
+ filter(Date >= validation_start_date)
411
+
412
+ if (nrow(validation_data) < 28) {
413
+ message("验证集不足四周(少于28天),无法计算权重。将使用默认权重或跳过。")
414
+ sarima_weight <- 0.5
415
+ prophet_weight <- 0.5
416
+ } else {
417
+ # 使用全量数据训练SARIMA和Prophet
418
+ sarima_fc_val <- sarima_model(train_data, h = nrow(validation_data))
419
+ sarima_values <- as.numeric(sarima_fc_val$mean)
420
+
421
+ prophet_fc_val <- prophet_model(train_data, validation_data$Date)
422
+
423
+ # 确保预测值长度与实际值一致
424
+ min_len <- min(length(validation_data$Value), length(sarima_values), length(prophet_fc_val$Value))
425
+ if (min_len < 1) {
426
+ sarima_weight <- 0.5
427
+ prophet_weight <- 0.5
428
+ message("验证集或预测值长度不足,使用默认权重。")
429
+ } else {
430
+ sarima_mae <- mean(abs(validation_data$Value[1:min_len] - sarima_values[1:min_len]), na.rm = TRUE)
431
+ prophet_mae <- mean(abs(validation_data$Value[1:min_len] - prophet_fc_val$Value[1:min_len]), na.rm = TRUE)
432
+
433
+ # 避免除以零或NaN
434
+ if (is.na(sarima_mae) || is.na(prophet_mae) || (sarima_mae == 0 && prophet_mae == 0)) {
435
+ sarima_weight <- 0.5
436
+ prophet_weight <- 0.5
437
+ } else {
438
+ total_mae <- sarima_mae + prophet_mae
439
+ sarima_weight <- 1 - (sarima_mae / total_mae)
440
+ prophet_weight <- 1 - (prophet_mae / total_mae)
441
+
442
+ total_weight <- sarima_weight + prophet_weight
443
+ sarima_weight <- sarima_weight / total_weight
444
+ prophet_weight <- prophet_weight / total_weight
445
+ }
446
+ }
447
+ }
448
+ cat("权重计算 - SARIMA:", round(sarima_weight, 2),
449
+ "Prophet:", round(prophet_weight, 2), "\n")
450
+
451
+ # 预测最后四周
452
+ full_sarima_fc <- sarima_model(train_data, h = length(test_dates))
453
+ full_sarima <- as.numeric(full_sarima_fc$mean)
454
+ full_prophet <- prophet_model(train_data, test_dates)$Value
455
+
456
+ # 确保预测值长度一致
457
+ min_len_pred <- min(length(full_sarima), length(full_prophet), length(test_dates))
458
+ if (min_len_pred < 1) {
459
+ message("最终预测长度不足,返回NA。")
460
+ result <- tibble(Date = test_dates, Value = rep(NA, length(test_dates)))
461
+ } else {
462
+ weighted_avg <- sarima_weight * full_sarima[1:min_len_pred] + prophet_weight * full_prophet[1:min_len_pred]
463
+ result <- tibble(Date = test_dates[1:min_len_pred], Value = weighted_avg)
464
+ }
465
+
466
+ attr(result, "sarima_weight") <- sarima_weight
467
+ attr(result, "prophet_weight") <- prophet_weight
468
+ return(result)
469
+ }
470
+
471
+ # ---------------------------- 9. 模型性能评估 ----------------------------
472
+ calculate_metrics <- function(actual, predicted) {
473
+ # 移除NA值,并确保长度一致
474
+ common_indices <- intersect(which(!is.na(actual)), which(!is.na(predicted)))
475
+ if (length(common_indices) == 0) {
476
+ return(data.frame(MAE = NA, RMSE = NA, MAPE = NA, sMAPE = NA))
477
+ }
478
+ actual <- actual[common_indices]
479
+ predicted <- predicted[common_indices]
480
+
481
+ mae <- mean(abs(actual - predicted))
482
+ rmse <- sqrt(mean((actual - predicted)^2))
483
+ # 避免除以零或NaN
484
+ mape <- ifelse(any(actual == 0), NA, mean(abs((actual - predicted) / actual)) * 100)
485
+ smape <- 200 * mean(abs(actual - predicted) / (abs(actual) + abs(predicted)))
486
+
487
+ data.frame(MAE = mae, RMSE = rmse, MAPE = mape, sMAPE = smape)
488
+ }
489
+
490
+ all_metrics <- list()
491
+ weight_history <- tibble() # 存储权重历史
492
+
493
+ # 限制循环次数以加快测试或处理大数据量
494
+ # 例如,只处理最后几个 `current_dates`
495
+ # current_dates_to_process <- tail(current_dates, 5) # 只处理最后5个周期
496
+ current_dates_to_process <- current_dates
497
+
498
+ for(i in seq_along(current_dates_to_process)) {
499
+ date <- current_dates_to_process[i]
500
+ message("Processing date: ", date)
501
+
502
+ # 动态窗口划分(用于 SARIMA 训练,Prophet 使用 full_train_data)
503
+ window_data <- dynamic_split(df, date, window_size = best_mae_window)
504
+
505
+ # 使用全量数据作为训练集
506
+ full_train_data <- df %>% filter(Date <= date)
507
+
508
+ # 保留最后四周作为测试集
509
+ test_start_date <- date + days(1)
510
+ test_end_date <- date + weeks(4)
511
+ test_dates <- seq(test_start_date, test_end_date, by = "day")
512
+
513
+ if (length(test_dates) == 0) {
514
+ message("测试日期序列为空,跳过此迭代。")
515
+ next
516
+ }
517
+ # 检查实际值数据是否存在且足够
518
+ actual_values_full_range <- df %>%
519
+ filter(Date >= test_start_date, Date <= test_end_date) %>%
520
+ pull(Value)
521
+
522
+ if (length(actual_values_full_range) == 0) {
523
+ message("当前日期 ", date, " 之后的实际值不足,跳过此迭代。")
524
+ next
525
+ }
526
+
527
+ # 各模型预测
528
+ sarima_fc_result <- sarima_model(window_data$train, h = length(test_dates))
529
+ sarima_pred <- as.numeric(sarima_fc_result$mean)
530
+
531
+ prophet_pred_df <- prophet_model(full_train_data, test_dates)
532
+ prophet_pred <- prophet_pred_df$Value
533
+
534
+ weighted_pred_df <- weighted_average_model(full_train_data, test_dates)
535
+ weighted_pred <- weighted_pred_df$Value
536
+
537
+
538
+ # 提取权重
539
+ sarima_weight <- attr(weighted_pred_df, "sarima_weight")
540
+ prophet_weight <- attr(weighted_pred_df, "prophet_weight")
541
+
542
+ # 存储权重信息
543
+ weight_history <- bind_rows(weight_history,
544
+ tibble(Date = date,
545
+ SARIMA_Weight = sarima_weight,
546
+ Prophet_Weight = prophet_weight))
547
+
548
+ # 计算评��指标
549
+ # 确保预测值和实际值长度一致
550
+ min_len_metrics <- min(length(actual_values_full_range), length(sarima_pred),
551
+ length(prophet_pred), length(weighted_pred))
552
+ if (min_len_metrics == 0) {
553
+ message("预测或实际值长度为0,无法计算指标。")
554
+ next
555
+ }
556
+
557
+ actual_values <- actual_values_full_range[1:min_len_metrics]
558
+ sarima_pred_cut <- sarima_pred[1:min_len_metrics]
559
+ prophet_pred_cut <- prophet_pred[1:min_len_metrics]
560
+ weighted_pred_cut <- weighted_pred[1:min_len_metrics]
561
+
562
+
563
+ sarima_metrics <- calculate_metrics(actual_values, sarima_pred_cut)
564
+ prophet_metrics <- calculate_metrics(actual_values, prophet_pred_cut)
565
+ weighted_metrics <- calculate_metrics(actual_values, weighted_pred_cut)
566
+
567
+ all_metrics[[i]] <- list(
568
+ date = date,
569
+ sarima = sarima_metrics,
570
+ prophet = prophet_metrics,
571
+ weighted = weighted_metrics
572
+ )
573
+ }
574
+
575
+ # 过滤掉空的列表元素
576
+ all_metrics <- all_metrics[!sapply(all_metrics, is.null)]
577
+
578
+ # ---------------------------- 10. 模型对比可视化 ----------------------------
579
+ # 10.1 提取评估结果
580
+ if (length(all_metrics) == 0) {
581
+ stop("没有计算出任何模型评估指标,无法生成图表。请检查数据和循环设置。")
582
+ }
583
+ metrics_df <- bind_rows(lapply(all_metrics, function(x) {
584
+ bind_rows(
585
+ x$sarima %>% mutate(Model = "SARIMA", Date = x$date),
586
+ x$prophet %>% mutate(Model = "Prophet", Date = x$date),
587
+ x$weighted %>% mutate(Model = "加权平均模型", Date = x$date)
588
+ )
589
+ }))
590
+
591
+ # 10.2 模型权重变化可视化
592
+ plot_model_weights <- function(weight_history) {
593
+ # 确保日期是日期格式
594
+ weight_history$Date <- as.Date(weight_history$Date)
595
+
596
+ # 绘制权重变化图
597
+ ggplot(weight_history, aes(x = Date)) +
598
+ geom_line(aes(y = SARIMA_Weight, color = "SARIMA Weight"), size = 1) +
599
+ geom_line(aes(y = Prophet_Weight, color = "Prophet Weight"), size = 1) +
600
+ labs(title = "模型权重变化",
601
+ x = "日期",
602
+ y = "权重",
603
+ color = "模型") +
604
+ theme_minimal() +
605
+ theme(text = element_text(family = "SimHei", size = 12)) +
606
+ scale_color_manual(values = c("SARIMA Weight" = "#E41A1C", "Prophet Weight" = "#377EB8"))
607
+ }
608
+
609
+ # 调用函数绘制图形
610
+ p_weights <- plot_model_weights(weight_history)
611
+
612
+
613
+ # 10.3 各模型误差指标对比(分面图)
614
+ metrics_long <- metrics_df %>%
615
+ pivot_longer(cols = c(MAE, RMSE, MAPE, sMAPE),
616
+ names_to = "Metric",
617
+ values_to = "Value")
618
+
619
+ error_plot <- ggplot(metrics_long, aes(x = Date, y = Value, color = Model)) +
620
+ geom_line(size = 0.8) +
621
+ facet_wrap(~Metric, scales = "free_y", ncol = 2) +
622
+ labs(title = "各模型预测误差指标对比",
623
+ y = "误差值", x = "预测起始日期") +
624
+ theme_bw() +
625
+ theme(text = element_text(family = "SimHei"),
626
+ legend.position = "bottom") +
627
+ scale_color_brewer(palette = "Set1")
628
+
629
+ # print(error_plot)
630
+
631
+ # 10.4 平均性能对比雷达图
632
+ avg_metrics <- metrics_df %>%
633
+ group_by(Model) %>%
634
+ summarise(
635
+ MAE = mean(MAE, na.rm = TRUE),
636
+ RMSE = mean(RMSE, na.rm = TRUE),
637
+ MAPE = mean(MAPE, na.rm = TRUE),
638
+ sMAPE = mean(sMAPE, na.rm = TRUE)
639
+ ) %>%
640
+ pivot_longer(cols = -Model, names_to = "Metric", values_to = "Value")
641
+
642
+ radar_plot <- ggplot(avg_metrics, aes(x = Metric, y = Value, group = Model, color = Model)) +
643
+ geom_polygon(aes(fill = Model), alpha = 0.2, size = 1) +
644
+ coord_polar() +
645
+ labs(title = "各模型平均性能对比雷达图") +
646
+ theme_minimal() +
647
+ theme(text = element_text(family = "SimHei"),
648
+ axis.text.x = element_text(size = 10),
649
+ legend.position = "right")
650
+
651
+ # print(radar_plot)
652
+
653
+ # 10.5 最终预测对比图(最后一个窗口)
654
+ # 确保 current_dates_to_process 不为空
655
+ if (length(current_dates_to_process) == 0) {
656
+ warning("没有足够的 current_dates 来生成最终预测对比图。")
657
+ forecast_plot <- NULL
658
+ } else {
659
+ last_date <- tail(current_dates_to_process, 1) # 使用处理过的日期序列
660
+ window_data <- dynamic_split(df, last_date)
661
+ test_dates <- seq(last_date + days(1), last_date + weeks(4), by = "day")
662
+
663
+ sarima_fc <- sarima_model(window_data$train, h = length(test_dates))$mean
664
+ prophet_fc <- prophet_model(window_data$train, test_dates)
665
+ weighted_fc <- weighted_average_model(window_data$train, test_dates)
666
+
667
+ # 过滤掉NA值,确保长度一致
668
+ min_len_final_comp <- min(length(window_data$test_4w$Value),
669
+ length(sarima_fc),
670
+ length(prophet_fc$Value),
671
+ length(weighted_fc$Value))
672
+
673
+ if (min_len_final_comp == 0) {
674
+ warning("最终预测对比图数据长度不足,跳过生成。")
675
+ forecast_plot <- NULL
676
+ } else {
677
+ comparison_df <- bind_rows(
678
+ window_data$test_4w[1:min_len_final_comp,] %>% mutate(Type = "实际值"),
679
+ tibble(Date = test_dates[1:min_len_final_comp], Value = sarima_fc[1:min_len_final_comp], Type = "SARIMA预测"),
680
+ prophet_fc[1:min_len_final_comp,] %>% mutate(Type = "Prophet预测"),
681
+ weighted_fc[1:min_len_final_comp,] %>% mutate(Type = "加权平均预测")
682
+ )
683
+
684
+ forecast_plot <- ggplot(comparison_df, aes(x = Date, y = Value, color = Type)) +
685
+ geom_line(size = 1.2) +
686
+ geom_point(size = 2) +
687
+ labs(title = "三种模型未来4周预测对比",
688
+ subtitle = paste("预测起始日期:", last_date),
689
+ x = "日期", y = "值") +
690
+ theme_minimal() +
691
+ theme(text = element_text(family = "SimHei", size = 12),
692
+ legend.position = "top") +
693
+ scale_color_manual(values = c("实际值" = "black",
694
+ "SARIMA预测" = "red",
695
+ "Prophet预测" = "blue",
696
+ "加权平均预测" = "green"))
697
+
698
+ # print(forecast_plot)
699
+ }
700
+ }
701
+
702
+
703
+ # 10.6 误差分布箱线图
704
+ error_dist <- metrics_df %>%
705
+ select(Model, MAE, RMSE, MAPE, sMAPE) %>%
706
+ pivot_longer(cols = -Model, names_to = "Metric", values_to = "Value")
707
+
708
+ box_plot <- ggplot(error_dist, aes(x = Model, y = Value, fill = Model)) +
709
+ geom_boxplot(alpha = 0.7) +
710
+ facet_wrap(~Metric, scales = "free_y") +
711
+ labs(title = "各模型误差分布箱线图") +
712
+ theme_bw() +
713
+ theme(text = element_text(family = "SimHei"),
714
+ axis.text.x = element_text(angle = 45, hjust = 1)) +
715
+ scale_fill_brewer(palette = "Pastel1")
716
+ # print(box_plot)
717
+
718
+
719
+ # 10.7 组合所有可视化结果
720
+ # 检查每个图表对象是否为NULL,只有非NULL的才会被组合
721
+ plots_to_combine <- list()
722
+ if (!is.null(p_weights)) plots_to_combine$p_weights <- p_weights
723
+ if (!is.null(error_plot)) plots_to_combine$error_plot <- error_plot
724
+ if (!is.null(forecast_plot)) plots_to_combine$forecast_plot <- forecast_plot
725
+ if (!is.null(radar_plot)) plots_to_combine$radar_plot <- radar_plot
726
+ if (!is.null(box_plot)) plots_to_combine$box_plot <- box_plot
727
+ if (!is.null(stl_plot)) plots_to_combine$stl_plot <- stl_plot # 添加 STL 分解图
728
+
729
+ # 使用 patchwork 动态组合图表
730
+ if (length(plots_to_combine) > 0) {
731
+ # 根据可用图表的数量和类型,选择合适的布局
732
+ # 这是一个通用的组合,你可以根据实际生成的图表调整布局
733
+ combined_plots <- wrap_plots(plots_to_combine) +
734
+ plot_annotation(title = "时间序列预测模型综合比较",
735
+ theme = theme(plot.title = element_text(hjust = 0.5, size = 16, family = "SimHei")))
736
+ print(combined_plots)
737
+ # 保存综合图表
738
+ ggsave("forecast_comparison.png", combined_plots, width = 16, height = 20, dpi = 300)
739
+ } else {
740
+ message("没有足够的图表可以组合。")
741
+ }
742
+
743
+
744
+ # 输出平均性能
745
+ cat("\n各模型平均性能对比:\n")
746
+ avg_perf <- metrics_df %>%
747
+ group_by(Model) %>%
748
+ summarise(
749
+ MAE = mean(MAE, na.rm = TRUE),
750
+ RMSE = mean(RMSE, na.rm = TRUE),
751
+ MAPE = mean(MAPE, na.rm = TRUE),
752
+ sMAPE = mean(sMAPE, na.rm = TRUE)
753
+ )
754
+ print(avg_perf)
755
+
756
+
757
+ #---------------------------第11部分代码---------------------------#
758
+ # 11.1 获取最后一个预测窗口数据
759
+ # 确保 current_dates_to_process 不为空
760
+ if (length(current_dates_to_process) == 0) {
761
+ warning("没有足够的 current_dates 来进行最后的预测可视化。")
762
+ } else {
763
+ last_date <- tail(current_dates_to_process, 1)
764
+ window_data <- dynamic_split(df, last_date)
765
+ test_dates <- seq(last_date + days(1), last_date + weeks(4), by = "day")
766
+ actual_data <- window_data$test_4w
767
+
768
+ # 11.2 生成各模型预测
769
+ sarima_fc <- sarima_model(window_data$train, h = 28)$mean
770
+ prophet_fc <- prophet_model(window_data$train, test_dates)
771
+ weighted_fc <- weighted_average_model(window_data$train, test_dates)
772
+
773
+ # 11.3 创建结果数据框
774
+ # 确保所有预测结果长度一致
775
+ min_len_results <- min(length(actual_data$Value), length(sarima_fc), length(prophet_fc$Value), length(weighted_fc$Value))
776
+
777
+ if (min_len_results == 0) {
778
+ warning("最终结果数据框数据长度不足,无法创建。")
779
+ results_df <- NULL
780
+ } else {
781
+ results_df <- bind_rows(
782
+ actual_data[1:min_len_results,] %>% mutate(Model = "实际值"),
783
+ tibble(Date = as.Date(test_dates[1:min_len_results]), Value = sarima_fc[1:min_len_results], Model = "SARIMA预测"),
784
+ prophet_fc[1:min_len_results,] %>% mutate(Model = "Prophet预测"),
785
+ weighted_fc[1:min_len_results,] %>% mutate(Model = "加权平均预测")
786
+ )
787
+
788
+ # 确保所有数据框中的 Date 列都是 Date 类型
789
+ results_df$Date <- as.Date(results_df$Date)
790
+ prophet_fc$Date <- as.Date(prophet_fc$Date)
791
+ weighted_fc$Date <- as.Date(weighted_fc$Date)
792
+
793
+ # ————————————————————————————提取一周预测数据————————————————————————————#
794
+ first_week_df <- results_df %>%
795
+ filter(Date <= last_date + weeks(1))
796
+ # 再次确保 first_week_df 中的 Date 列是 Date 类型
797
+ first_week_df$Date <- as.Date(first_week_df$Date)
798
+
799
+ # 11.5 可视化:第一周预测对比
800
+ first_week_plot <- ggplot(first_week_df, aes(x = Date, y = Value, color = Model, linetype = Model)) +
801
+ geom_line(size = 1.2) +
802
+ geom_point(data = filter(first_week_df, Model == "实际值"), size = 2) +
803
+ labs(
804
+ title = "第一周预测结果对比",
805
+ subtitle = paste("预测起始日期:", format(last_date, "%Y-%m-%d")),
806
+ x = "日期", y = "值"
807
+ ) +
808
+ theme_minimal() +
809
+ theme(
810
+ text = element_text(family = "SimHei", size = 12),
811
+ legend.position = "top",
812
+ axis.text.x = element_text(angle = 45, hjust = 1)
813
+ ) +
814
+ scale_color_manual(
815
+ values = c(
816
+ "实际值" = "black",
817
+ "SARIMA预测" = "#E41A1C",
818
+ "Prophet预测" = "#377EB8",
819
+ "加权平均预测" = "#4DAF4A"
820
+ )
821
+ ) +
822
+ scale_linetype_manual(
823
+ values = c(
824
+ "实际值" = "solid",
825
+ "SARIMA预测" = "dashed",
826
+ "Prophet预测" = "dotted",
827
+ "加权平均预测" = "longdash"
828
+ )
829
+ ) +
830
+ scale_x_date(
831
+ date_labels = "%m-%d",
832
+ date_breaks = "1 day"
833
+ )
834
+
835
+ print(first_week_plot)
836
+
837
+ #---------------------------对比图---------------------------#
838
+
839
+ # 11.6 计算第一周的误差指标
840
+ # 计算每个模型的 MAE、MAPE 和 RMSE
841
+ # 提取实际值(第一周)
842
+ actual_values_1w <- first_week_df %>%
843
+ filter(Model == "实际值") %>%
844
+ pull(Value)
845
+
846
+ # 提取各模型预测值(第一周)
847
+ sarima_predictions_1w <- first_week_df %>%
848
+ filter(Model == "SARIMA预测") %>%
849
+ pull(Value)
850
+ prophet_predictions_1w <- first_week_df %>%
851
+ filter(Model == "Prophet预测") %>%
852
+ pull(Value)
853
+ weighted_predictions_1w <- first_week_df %>%
854
+ filter(Model == "加权平均预测") %>%
855
+ pull(Value)
856
+
857
+ # 检查数据长度是否一致
858
+ min_len_error_1w <- min(length(actual_values_1w), length(sarima_predictions_1w),
859
+ length(prophet_predictions_1w), length(weighted_predictions_1w))
860
+
861
+ if (min_len_error_1w == 0) {
862
+ warning("第一周误差计算数据长度不足。")
863
+ error_df_long_1w <- data.frame() # 创建空数据框以避免后续错误
864
+ } else {
865
+ # 截取到最小长度
866
+ actual_values_1w <- actual_values_1w[1:min_len_error_1w]
867
+ sarima_predictions_1w <- sarima_predictions_1w[1:min_len_error_1w]
868
+ prophet_predictions_1w <- prophet_predictions_1w[1:min_len_error_1w]
869
+ weighted_predictions_1w <- weighted_predictions_1w[1:min_len_error_1w]
870
+
871
+ # 计算误差指标
872
+ sarima_error_1w <- calculate_error_metrics(actual_values_1w, sarima_predictions_1w)
873
+ prophet_error_1w <- calculate_error_metrics(actual_values_1w, prophet_predictions_1w)
874
+ weighted_error_1w <- calculate_error_metrics(actual_values_1w, weighted_predictions_1w)
875
+
876
+ # 创建误差指标数据框
877
+ error_df_1w <- data.frame(
878
+ Model = c("SARIMA预测", "Prophet预测", "加权平均预测"),
879
+ MAE = c(sarima_error_1w$MAE, prophet_error_1w$MAE, weighted_error_1w$MAE),
880
+ MAPE = c(sarima_error_1w$MAPE, prophet_error_1w$MAPE, weighted_error_1w$MAPE),
881
+ RMSE = c(sarima_error_1w$RMSE, prophet_error_1w$RMSE, weighted_error_1w$RMSE)
882
+ )
883
+
884
+ # 将误差指标数据框转换为长格式
885
+ error_df_long_1w <- error_df_1w %>%
886
+ pivot_longer(cols = c(MAE, MAPE, RMSE),
887
+ names_to = "Metric",
888
+ values_to = "Value")
889
+
890
+ # 11.7 可视化:第一周误差结果对比
891
+ # 创建误差指标对比图
892
+ error_plot_1w <- ggplot(error_df_long_1w, aes(x = Model, y = Value, fill = Model)) +
893
+ geom_bar(stat = "identity", position = position_dodge()) +
894
+ geom_text(aes(label = ifelse(Metric == "MAPE", paste0(round(Value, 2), "%"), round(Value, 2))),
895
+ position = position_dodge(width = 0.9), vjust = -0.5) +
896
+ labs(
897
+ title = "第一周预测误差结果对比",
898
+ x = "模型", y = "误差值"
899
+ ) +
900
+ facet_wrap(~Metric, scales = "free_y") +
901
+ theme_minimal() +
902
+ theme(
903
+ text = element_text(family = "SimHei", size = 12),
904
+ legend.position = "none",
905
+ strip.text = element_text(face = "bold")
906
+ )
907
+
908
+ print(error_plot_1w)
909
+ }
910
+
911
+ # # ————————————————————————————提取四周预测数据————————————————————————————#
912
+ # 时间序列对比图
913
+ # 确保 Date 列是 Date 类型
914
+ results_df$Date <- as.Date(results_df$Date)
915
+ # 确保 last_date 是 Date 类型
916
+ last_date <- as.Date(last_date)
917
+
918
+ four_week_plot <- ggplot(results_df, aes(x = Date, y = Value, color = Model, linetype = Model)) +
919
+ geom_line(size = 1.2) +
920
+ geom_point(data = filter(results_df, Model == "实际值"), size = 2) +
921
+ labs(
922
+ title = "最后四周预测结果对比",
923
+ subtitle = paste("预测起始日期:", format(last_date, "%Y-%m-%d")), # 格式化日期
924
+ x = "日期", y = "值"
925
+ ) +
926
+ theme_minimal() +
927
+ theme(
928
+ text = element_text(family = "SimHei", size = 12),
929
+ legend.position = "top",
930
+ axis.text.x = element_text(angle = 45, hjust = 1)
931
+ ) +
932
+ scale_color_manual(
933
+ values = c(
934
+ "实际值" = "black",
935
+ "SARIMA预测" = "#E41A1C",
936
+ "Prophet预测" = "#377EB8",
937
+ "加权平均预测" = "#4DAF4A"
938
+ )
939
+ ) +
940
+ scale_linetype_manual(
941
+ values = c(
942
+ "实际值" = "solid",
943
+ "SARIMA预测" = "dashed",
944
+ "Prophet预测" = "dotted",
945
+ "加权平均预测" = "longdash"
946
+ )
947
+ ) +
948
+ scale_x_date(
949
+ date_labels = "%m-%d",
950
+ date_breaks = "3 days"
951
+ )
952
+
953
+ print(four_week_plot)
954
+
955
+
956
+ # 11.8 提取四周预测数据
957
+ four_weeks_df <- results_df
958
+
959
+ # 11.9 计算四周的误差指标
960
+ # 提取实际值(四周)
961
+ actual_values_4w <- four_weeks_df %>%
962
+ filter(Model == "实际值") %>%
963
+ pull(Value)
964
+
965
+ # 提取各模型预测值(四周)
966
+ sarima_predictions_4w <- four_weeks_df %>%
967
+ filter(Model == "SARIMA预测") %>%
968
+ pull(Value)
969
+ prophet_predictions_4w <- four_weeks_df %>%
970
+ filter(Model == "Prophet预测") %>%
971
+ pull(Value)
972
+ weighted_predictions_4w <- four_weeks_df %>%
973
+ filter(Model == "加权平均预测") %>%
974
+ pull(Value)
975
+
976
+ # 根据实际值数量调整预测值数量
977
+ n_actual <- length(actual_values_4w)
978
+ min_len_error_4w <- min(n_actual, length(sarima_predictions_4w),
979
+ length(prophet_predictions_4w), length(weighted_predictions_4w))
980
+
981
+ if (min_len_error_4w == 0) {
982
+ warning("四周误差计算数据长度不足。")
983
+ error_df_long_4w <- data.frame()
984
+ } else {
985
+ sarima_predictions_4w <- sarima_predictions_4w[1:min_len_error_4w]
986
+ prophet_predictions_4w <- prophet_predictions_4w[1:min_len_error_4w]
987
+ weighted_predictions_4w <- weighted_predictions_4w[1:min_len_error_4w]
988
+ actual_values_4w <- actual_values_4w[1:min_len_error_4w] # 确保 actual 也被截取
989
+
990
+ # 计算误差指标
991
+ sarima_error_4w <- calculate_error_metrics(actual_values_4w, sarima_predictions_4w)
992
+ prophet_error_4w <- calculate_error_metrics(actual_values_4w, prophet_predictions_4w)
993
+ weighted_error_4w <- calculate_error_metrics(actual_values_4w, weighted_predictions_4w)
994
+
995
+ # 创建误差指标数据框
996
+ error_df_4w <- data.frame(
997
+ Model = c("SARIMA预测", "Prophet预测", "加权平均预测"),
998
+ MAE = c(sarima_error_4w$MAE, prophet_error_4w$MAE, weighted_error_4w$MAE),
999
+ MAPE = c(sarima_error_4w$MAPE, prophet_error_4w$MAPE, weighted_error_4w$MAPE),
1000
+ RMSE = c(sarima_error_4w$RMSE, prophet_error_4w$RMSE, weighted_error_4w$RMSE)
1001
+ )
1002
+
1003
+ # 将误差指标数据框转换为长格式
1004
+ error_df_long_4w <- error_df_4w %>%
1005
+ pivot_longer(cols = c(MAE, MAPE, RMSE),
1006
+ names_to = "Metric",
1007
+ values_to = "Value")
1008
+
1009
+ # 11.10 可视化:四周误差结果对比
1010
+ # 创建误差指标对比图
1011
+ error_plot_4w <- ggplot(error_df_long_4w, aes(x = Model, y = Value, fill = Model)) +
1012
+ geom_bar(stat = "identity", position = position_dodge()) +
1013
+ geom_text(aes(label = ifelse(Metric == "MAPE", paste0(round(Value, 2), "%"), round(Value, 2))),
1014
+ position = position_dodge(width = 0.9), vjust = -0.5) +
1015
+ labs(
1016
+ title = "四周预测误差结果对比",
1017
+ x = "模型", y = "误差值"
1018
+ ) +
1019
+ facet_wrap(~Metric, scales = "free_y") +
1020
+ theme_minimal() +
1021
+ theme(
1022
+ text = element_text(family = "SimHei", size = 12),
1023
+ legend.position = "none",
1024
+ strip.text = element_text(face = "bold")
1025
+ )
1026
+
1027
+ print(error_plot_4w)
1028
+ }
1029
+ }