【发布时间】:2021-01-02 08:51:54
【问题描述】:
我有以下数据表,我想使用 GLM(= 广义线性模型)根据数据表中的其他变量来预测 DE 价格。
set.seed(123)
dt.data <- data.table(date = seq(as.Date('2019-01-01'), by = '1 day', length.out = 731),
'DE' = rnorm(731, 30, 1), 'windDE' = rnorm(731, 10, 1),
'consumptionDE' = rnorm(731, 50, 1), 'nuclearDE' = rnorm(731, 8, 1),
'solarDE' = rnorm(731, 1, 1), check.names = FALSE)
dt.forecastData <- dt.data
dt.forecastData <- na.omit(dt.forecastData)
fromTestDate <- "2019-12-31"
fromDateTest <- base::toString(fromTestDate)
## Create train and test date-vectors depending on fromDateTest: ##
v.train <- which(dt.forecastData$date <= fromDateTest)
v.test <- which(dt.forecastData$date == as.Date(fromDateTest)+1)
## Create data tables for train and test data with specific date range (fromTestDate): ##
dt.train <- dt.forecastData[v.train]
v.trainDate <- dt.train$date
dt.test <- dt.forecastData[v.test]
v.testDate <- dt.test$date
## Delete column "date" of train and test data for model fitting: ##
dt.train <- dt.train[, c("date") := NULL]
dt.test <- dt.test[, c("date") := NULL]
## MODEL FITTING: ##
## Generalized Linear Model: ##
xgbModel <- stats::glm(DE ~ .-1, data = dt.train,
family = quasi(link = "identity", variance = "constant"))
## Train and Test Data PREDICTION with xgbModel: ##
dt.train$prediction <- stats::predict.glm(xgbModel, dt.train)
dt.test$prediction <- stats::predict.glm(xgbModel, dt.test)
## Add date columns to dt.train and dt.test: ##
dt.train <- data.table(date = v.trainDate, dt.train)
dt.test <- data.table(date = v.testDate, dt.test)
在这段代码中,我使用2019-01-01 到2019-12-31 的数据训练模型,并使用2020-01-01 的前一天预测对其进行测试。
现在我想创建一个for-loop,以便我总共运行我的模型365,如下:
运行 1:
a) 使用 01-01-2019 到 31-12-2019 训练我的模型
b) 预测01-01-2020(测试数据)
c) 使用01-01-2020 的实际数据点来评估预测
运行 2:
a) 使用 01-01-2019 到 01-01-2020 来训练我的模型
b) 预测02-01-2020
c) 使用02-01-2020 的实际数据点来评估预测
等
最后,我想绘制例如单个预测性能的累积总和或单个预测性能的直方图和一些汇总统计数据(均值、中位数、标准差等)
不幸的是,我不知道如何从循环开始,以及在哪里可以保存每次运行的预测? 我希望有人可以帮助我!
【问题讨论】:
标签: r for-loop prediction forecasting glm