Prophet

更新时间:
复制 MD 格式

Prophet is a time series forecasting algorithm developed by Facebook. It decomposes a series into trend, seasonality, and holiday components to generate a forecast and uncertainty bounds. Prophet is practical for business forecasting scenarios such as demand planning, revenue forecasting, and traffic prediction.

Prophet runs on MaxCompute computing resources only.

When to use Prophet

Prophet works best when your data meets most of the following conditions:

  • At least two full seasonal cycles of historical data (for example, two years of daily observations)

  • Clear seasonal patterns—daily, weekly, or yearly

  • Known one-off events that affect the series (product launches, holidays, promotions)

  • A growth trend approaching a natural ceiling or floor (for example, market saturation)

If your data has none of these characteristics, a simpler model may perform just as well.

How it works

  1. Load time series data into an MTable column using the MTable Assembler component.

  2. Pass the MTable column to the Prophet component and configure forecasting parameters.

  3. Prophet decomposes the series into trend, seasonality, and holiday components, then generates a forecast.

  4. The output contains a point forecast (yhat) in the prediction column and uncertainty bounds (yhat_lower, yhat_upper) in the prediction details column.

Configure the component in the PAI console

Input ports

Input portData typeRequiredRecommended upstream component
Input DataN/AYesRead Table, Read CSV File, Feature engineering, Data preprocessing

Field setting

ParameterDescription
valueColThe MTable column that contains the time series. The data type is STRING and the data format is MTable. Use the MTable Assembler component to construct this column. The Datetime column (ds) serves as the time axis. Example: {"data":{"ds":["2019-05-07 00:00:00.0","2019-05-08 00:00:00.0"],"val":[8588.0,8521.0]},"schema":"ds TIMESTAMP,val DOUBLE"}
reservedColsColumns from the input data to carry through to the output.

Parameter setting

Parameters fall into four groups: trend control, seasonality control, holiday control, and output control. Understanding which group a parameter belongs to makes tuning more straightforward.

Trend control

ParameterDefaultDescription
growthLINEARThe type of growth trend. LINEAR fits a piecewise linear trend. Logistic fits a saturating growth curve—use this when the series has a natural ceiling or floor (set cap and floor accordingly). Flat assumes no trend.
capThe upper saturation limit. Required when growth is Logistic. Can be a constant or a series that changes over time. Has no effect when growth is LINEAR or Flat.
floorThe lower saturation limit. Required when growth is Logistic and the series has a minimum bound. Has no effect when growth is LINEAR or Flat.
changepointsAn explicit list of change point dates, separated by commas. Example: 2021-05-02,2021-05-07. Leave blank to let Prophet detect change points automatically.
n_change_point25The maximum number of automatically detected change points.
change_point_range0.8The proportion of the historical data in which change points can occur. The default (0.8) restricts detection to the first 80% of the series, preventing spurious change points near the end of the data.
changepoint_prior_scale0.05Controls trend flexibility. If the trend is overfit (following noise too closely), decrease this value toward 0.001. If the trend is underfit (missing real shifts), increase it toward 0.5.

Seasonality control

ParameterDefaultDescription
seasonality_modeADDITIVEHow seasonality interacts with the trend. Use ADDITIVE when seasonal swings stay roughly constant in magnitude. Use MULTIPLICATIVE when seasonal swings grow or shrink proportionally with the trend level.
daily_seasonalityautoWhether to fit a daily seasonal component. auto enables daily seasonality only when the data has sub-daily observations.
weekly_seasonalityautoWhether to fit a weekly seasonal component.
yearly_seasonalityautoWhether to fit a yearly seasonal component.
seasonality_prior_scale10.0Controls how strongly seasonality fits the data. Decrease to smooth out seasonal fluctuations; increase to allow larger seasonal swings. Works analogously to changepoint_prior_scale but for the seasonality component.

Holiday control

ParameterDefaultDescription
holidaysCustom holiday dates, formatted as name:date1,date2 name2:date3,date4. Separate multiple holidays with spaces. Example: playoff:2021-05-03,2021-01-03 superbowl:2021-02-07,2021-11-02.
holidays_prior_scale10.0Controls how strongly the model fits holiday effects. Works analogously to seasonality_prior_scale but for the holiday component. Decrease if holiday spikes are being overfit.

Output and inference control

ParameterDefaultDescription
predictionColThe name of the output column that contains the point forecast (yhat).
predictionDetailColThe name of the output column that contains forecast details as an MTable. Fields include yhat_lower and yhat_upper (uncertainty bounds), trend, and seasonal component values. Use the MTable Expander component to flatten this column into a regular table.
predictNum12The number of future periods to forecast. Valid values: (0, inf).
include_historyWhether to include fitted values for historical dates in the output.
interval_width0.8The width of the uncertainty interval. The default 0.8 corresponds to an 80% uncertainty interval around the forecast.
mcmc_samples100The number of Markov Chain Monte Carlo (MCMC) samples for Bayesian inference. Set to 0 to use maximum a posteriori (MAP) estimation instead of full Bayesian inference—this is faster but does not produce uncertainty intervals.
uncertaintySamples1000The number of samples used to compute uncertainty bounds. Set to 0 to skip uncertainty estimation and speed up prediction.
stanInitThe initial value for the Stan optimizer. Leave blank to use the default.
numThreadsThe number of threads the component uses.

Execution tuning

ParameterDescription
Number of WorkersThe number of CPU cores. Must be a positive integer in the range [1, 9999]. Set together with Memory per worker, unit MB.
Memory per worker, unit MBThe memory allocated to each worker node. Valid values: 1024–65536 MB.

Configure the component by using code

Copy the following code into the PyAlink Script component to replicate Prophet component behavior programmatically.

The code performs three steps:

  1. Aggregate raw time series rows into a single MTable column per group using GroupByBatchOp.

  2. Run Prophet forecasting on each MTable using ProphetBatchOp.

  3. Flatten the MTable prediction output into a regular table using FlattenMTableBatchOp.

import time, datetime
import numpy as np
import pandas as pd

# Download the required Prophet plugin environment
downloader = AlinkGlobalConfiguration.getPluginDownloader()
downloader.downloadPlugin('tf115_python_env_linux')

# Sample input: each row is one timestamped observation
data = pd.DataFrame([
    [1, datetime.datetime.fromtimestamp(1),  10.0],
    [1, datetime.datetime.fromtimestamp(2),  11.0],
    [1, datetime.datetime.fromtimestamp(3),  12.0],
    [1, datetime.datetime.fromtimestamp(4),  13.0],
    [1, datetime.datetime.fromtimestamp(5),  14.0],
    [1, datetime.datetime.fromtimestamp(6),  15.0],
    [1, datetime.datetime.fromtimestamp(7),  16.0],
    [1, datetime.datetime.fromtimestamp(8),  17.0],
    [1, datetime.datetime.fromtimestamp(9),  18.0],
    [1, datetime.datetime.fromtimestamp(10), 19.0]
])

# Step 1: Convert rows into an MTable column grouped by series ID
source = dataframeToOperator(data, schemaStr='id int, ts timestamp, val double', op_type='batch')

source.link(
    GroupByBatchOp()
        .setGroupByPredicate("id")
        .setSelectClause("id, mtable_agg(ts, val) as data")
    # Step 2: Run Prophet and forecast 4 future periods
).link(
    ProphetBatchOp()
        .setValueCol("data")
        .setPredictNum(4)
        .setPredictionCol("pred")
    # Step 3: Flatten the MTable prediction output into rows
).link(
    FlattenMTableBatchOp()
        .setSelectedCol("pred_detail")
        .setSchemaStr("ds timestamp, yhat double")
).print()

What's next