首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于R的多项先知预测

基于R的多项先知预测
EN

Stack Overflow用户
提问于 2018-08-29 06:06:36
回答 1查看 3.4K关注 0票数 5

我是非常新的时间序列预测使用先知在R,我能够预测一个产品的价值使用先知。有任何方法,如果我可以使用循环生成预测使用先知为多种产品?下面的代码对于单个产品是非常好的,但是我试图为多个产品生成预测。

代码语言:javascript
复制
 library(prophet)
 df <- read.csv("Prophet.csv")
 df$Date<-as.Date(as.character(df$Date), format =  "%d-%m-%Y")
 colnames(df) <- c("ds", "y")
 m <- prophet(df)
 future <- make_future_dataframe(m, periods = 40)
 tail(future)
 forecast <- predict(m, future)
 write.csv(forecast[c('ds','yhat')],"Output_Prophet.csv")
 tail(forecast[c('ds', 'yhat', 'yhat_lower', 'yhat_upper')])

样本数据集:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-29 06:53:15

这可以通过使用来自lists包的mappurrr函数来实现。

让我们构建一些数据:

代码语言:javascript
复制
library(tidyverse) # contains also the purrr package
set.seed(123)
tb1 <- tibble(
  ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
  y = sample(365)
)
tb2 <- tibble(
  ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
  y = sample(365)
)

ts_list <- list(tb1, tb2) # two separate time series
# using this construct you could add more of course

构建与预测

代码语言:javascript
复制
library(prophet)

m_list <- map(ts_list, prophet) # prophet call

future_list <- map(m_list, make_future_dataframe, periods = 40) # makes future obs

forecast_list <- map2(m_list, future_list, predict) # map2 because we have two inputs

# we can access everything we need like with any list object
head(forecast_list[[1]]$yhat) # forecasts for time series 1
[1] 179.5214 198.2375 182.7478 173.5096 163.1173 214.7773
head(forecast_list[[2]]$yhat) # forecast for time series 2
[1] 172.5096 155.8796 184.4423 133.0349 169.7688 135.2990

更新(只是输入部分、构建部分和预测部分--它是相同的):

我创建了一个基于OP请求的新示例,基本上,您需要将所有内容再次放入list对象中:

代码语言:javascript
复制
# suppose you have a data frame like this:
set.seed(123)
tb1 <- tibble(
  ds = seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day"),
  productA = sample(365),
  productB = sample(365)
)
head(tb1)
# A tibble: 6 x 3
  ds         productA productB
  <date>        <int>    <int>
1 2018-01-01      105      287
2 2018-01-02      287       71
3 2018-01-03      149        7
4 2018-01-04      320      148
5 2018-01-05      340      175
6 2018-01-06       17      152

# with some dplyr and base R you can trasform each time series in a data frame within a list
ts_list <- tb1 %>% 
  gather("type", "y", -ds) %>% 
  split(.$type)
# this just removes the type column that we don't need anymore
ts_list <- lapply(ts_list, function(x) { x["type"] <- NULL; x })

# now you can continue just like above..
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52070501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档