How to install modeltime.gluonts on iMac-Pro

安装modeltime.gluonts需要python环境,以及相应的python packages。目前在Mac M1 arm-64 系统上仍然存在问题,因为MXnet包还没有支持Mac M1 arm-64系统。我在iMac-Pro上安装成功了。以下是安装步骤。

library(reticulate)

干净的python环境

本机的sessionInfo如下:

sessionInfo()

检查以下之前是否已经在R中设置过python环境,如果有的话,最好删掉,重新设置。

# check the following

# 不要设置代理
# usethis::edit_r_environ()

# 不要设置python的路径
# usethis::edit_r_profile()

# 确保没有关于python的设置
# usethis::edit_r_makevars()

检查python环境

如果没有在R中设置过python是最好的,如果设置了最好删掉,重新做一遍。

# 如果没有安装miniconda的话,先安装。
# reticulate::install_miniconda()

# 如果之前安装的不确定对不对,删掉重新安装
# reticulate::miniconda_uninstall()

# Which Environments are Available?
reticulate::conda_list()
reticulate::virtualenv_list()

# 删除不需要的 Environments
# reticulate::conda_remove(envname = "my_gluonts_env")

# check it again
# reticulate::conda_list()

# Which Environment am I Using?
reticulate::py_discover_config()

安装 modeltime.gluonts 📦

# loading package
library(modeltime.gluonts)

首次安装的话,会出现下面的错误信息:

── Python Dependency Check modeltime.gluonts ─────────────────────────────────────────────────────────────
x GluonTS Python Dependencies Not Found
ℹ Available Options: 
1. [Option 1 - Use a Pre-Configured Environment]: Use `install_gluonts()` to install GluonTS Python
Dependencies into a conda environment named r-gluonts.
2. [Option 2 - Use a Custom Environment]: Before running `library(modeltime.gluonts)`, use
`Sys.setenv(GLUONTS_PYTHON = 'path/to/python')` to set the path of your python executable that is located
in an environment that has 'gluonts', 'mxnet', 'numpy', 'pandas', and 'pathlib' available as
dependencies.
Refer to 'Managing GluonTS Environments'
<https://business-science.github.io/modeltime.gluonts/articles/managing-envs.html> for more details.

── End Python Dependency Check ───────────────────────────────────────────────────────────────────────────

install function

my_install_fn <- function(fresh_install = FALSE, include_pytorch = FALSE) {
  if (fresh_install) {
    cli::cli_alert_info("Removing conda env `r-gluonts` to setup for fresh install...")
    reticulate::conda_remove("r-gluonts")
  }

  python_version <- "3.8"

  message("\n")
  cli::cli_alert_info("Installing gluonts dependencies...")
  message("\n")

  default_pkgs <- c(
    "mxnet~=1.7", "gluonts==0.8.0", "numpy",
    "pandas==1.0.5", "pathlib==1.0.1", "ujson==4.0.2", "brotlipy"
  )

  reticulate::py_install(
    packages = default_pkgs, envname = "r-gluonts",
    method = "conda", conda = "auto", python_version = python_version,
    pip = TRUE
  )

  if (include_pytorch) {
    message("\n")
    cli::cli_alert_info("Installing torch dependencies...")
    message("\n")
    torch_pkgs <- c("torch~=1.6", "pytorch-lightning~=1.1")

    reticulate::py_install(
      packages = torch_pkgs, envname = "r-gluonts",
      method = "conda", conda = "auto", python_version = "3.8",
      pip = TRUE
    )
  }
  env_exists <- !is.null(detect_default_gluonts_env())

  gluonts_failure <- FALSE
  message("\n")

  if (env_exists) {
    cli::cli_alert_success("The {.field r-gluonts} conda environment has been created.")
  } else {
    cli::cli_alert_danger("The {.field r-gluonts} conda environment could not be created.")
    gluonts_failure <- TRUE
  }

  if (env_exists) {
    cli::cli_alert_info("Please restart your R Session and run {.code library(modeltime.gluonts)} to activate the {.field r-gluonts} environment.")
  } else {
    cli::cli_alert_info("For installation failure reports, please copy the python error message(s). Search your error(s) using Google. If none are found, create new issues here: https://github.com/business-science/modeltime.gluonts/issues")
  }
}
# apply function
# my_install_fn(fresh_install = TRUE, include_pytorch = TRUE)

成功安装之后,需要重启R-session

# 检测是否成功,没有任何错误提示
library(modeltime.gluonts)

检查当前的环境

确保当前的环境是 r-gluonts.

# Which Environments are Available?
reticulate::conda_list()
reticulate::virtualenv_list()

# Which Environment am I Using?
reticulate::py_discover_config()

测试新包的函数

# package needed
library(tidyverse)
library(zetaEDA)
library(tidymodels)
library(timetk)
# data prepare
ts_data_tbl <- zeta.forecast::eg_diamond_ts %>%
  tsbox::ts_tbl() %>%
  add_column(id = "diamond", .before = 1) %>%
  mutate(id = as.factor(id))

# check
ts_data_tbl %>%
  head() %>%
  print_kbl(cap = "ts_data_tbl")

build training and testing data

splits <- ts_data_tbl %>%
  time_series_split(
    date_var = time,
    assess = 3,
    cumulative = TRUE
  )

# visualize
splits %>%
  tk_time_series_cv_plan() %>%
  plot_time_series_cv_plan(time, value)

N-Beats model set up,

nbeats_model_spec <- nbeats(
  id = "id",
  # monthly frequency
  freq = "M",
  prediction_length = 3,
  lookback_length = 4 * 3,
  epochs = 5,
  num_batches_per_epoch = 15,
  batch_size = 4
) %>%
  set_engine("gluonts_nbeats_ensemble")

N-Beats model fitting,

nbeats_model_fit <- nbeats_model_spec %>%
  fit(value ~ time + id, training(splits))

# check
nbeats_model_fit

ETS model fitting

ets_model_fit <- exp_smoothing() %>%
  set_engine("ets") %>%
  fit(value ~ time, training(splits))

Check Model Performance,

calibration_tbl <- modeltime_table(
  nbeats_model_fit,
  ets_model_fit
) %>%
  modeltime_calibrate(testing(splits))

# accuracy
calibration_tbl %>%
  modeltime_accuracy()

calibration_tbl %>%
  modeltime_forecast(
    new_data    = testing(splits),
    actual_data = ts_data_tbl,
    keep_data   = TRUE
  ) %>%
  filter_by_time(
    .start_date = last(time) %-time% "24 month",
    .end_date = "end"
  ) %>%
  plot_modeltime_forecast(
    .facet_ncol         = 4,
    .conf_interval_show = FALSE,
    .interactive        = TRUE
  )
Chen Xing
Chen Xing
Founder & Data Scientist

Enjoy Life & Enjoy Work!

Related