开始使用免费开始使用

梯度提升树:预测

当您运行完模型后,下一步就是用它进行预测。与 base R 使用 predict() 函数进行预测不同,sparklyr 使用 ml_predict() 函数。ml_predict() 接受两个参数:一个模型,以及一些用于测试的数据。

ml_predict(a_model, testing_data)

一个常见用法是将预测的响应与真实响应进行比较,并在 R 中作图展示。准备这类数据的代码范式如下。请注意,目前添加预测列需要在本地完成,因此必须先收集结果。

predicted_vs_actual <- testing_data %>%
  select(actual) %>%
  collect() %>%
  mutate(predicted)

本练习是课程的一部分

R 中使用 sparklyr 的 Spark 入门

查看课程

练习说明

已经为您创建了名为 spark_conn 的 Spark 连接。存储在 Spark 中的训练集和测试集对应的 tibble 已分别预定义为 track_data_to_model_tbltrack_data_to_predict_tbl。梯度提升树模型已预定义为 gradient_boosted_trees_model

  • 定义变量 predicted,用于保存模型在测试数据上的预测结果。
    • 调用 ml_predict(),将模型和测试数据作为参数。该函数会为测试数据集生成预测,并将其作为名为 prediction 的新列添加。
    • 使用 pull() 提取该列,并赋值给 predicted
  • 定义变量 responses,以便准备比较预测响应与真实响应的数据:
    • 选择响应列 year
    • 收集结果。
    • 使用 mutate()predicted 中的预测加入。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Training, testing sets & model are pre-defined
track_data_to_model_tbl
track_data_to_predict_tbl
gradient_boosted_trees_model

# Predict the responses for the testing data
predicted <- ___(
      ___,
      ___) %>% pull(prediction)

# Prepare the data for comparing predicted responses with actual responses
responses <- track_data_to_predict_tbl %>%
  # Select the response column
  ___ %>%
  # Collect the results
  ___ %>%
  # Add in the predictions
  mutate(___)
编辑并运行代码