Kats Documentation

repository·main·Indexed 27 days ago

https://github.com/facebookresearch/kats

A lightweight, generalizable toolkit for time series analysis. Kats provides tools for forecasting (including Prophet, SARIMA, Holt-Winters, and VAR), anomaly and change point detection (such as CUSUM and OutlierDetector), feature extraction via TsFeatures, and multivariate analysis. It utilizes a central TimeSeriesData object to represent univariate and multivariate time series and follows an sklearn-like fit/predict API for its models.

Tokens
7.5K
Snippets
18
Records
33
Agent score
92%

What's inside Kats

  1. Explore available forecasting models in kats.models

    main

    The kats.models package provides a wide variety of time series forecasting models. You can use specific model implementations depending on your data characteristics (e.g., seasonality, trend, or multivariate requirements). Available model modules include:

    • Univariate Models:
      • kats.models.arima: Autoregressive Integrated Moving Average models.
      • kats.models.sarima: Seasonal ARIMA models.
      • kats.models.holtwinters: Exponential smoothing models.
      • kats.models.theta: Theta decomposition models.
      • kats.models.prophet: Facebook Prophet implementation.
      • kats.models.stlf: Seasonal-Trend decomposition using LOESS and Fourier terms.
      • kats.models.harmonic_regression: Models using harmonic components.
      • kats.models.quadratic_model: Models with quadratic trends.
      • kats.models.linear_model: Linear regression-based models.
    • Multivariate & Vector Models:
      • kats.models.var: Vector Autoregression.
      • kats.models.bayesian_var: Bayesian Vector Autoregression.
      • kats.models.nowcasting: Models for nowcasting.
    • Advanced & Ensemble Models:
      • kats.models.ensemble: Combines multiple models.
      • kats.models.metalearner: Uses meta-learning to select/combine models.
      • kats.models.lstm: Long Short-Term Memory neural networks.
      • kats.models.reconciliation: For reconciling hierarchical forecasts.
  2. Install Kats via pip

    main

    You can install the full version of Kats using pip. It is recommended to upgrade pip first.

    To install a minimal version that omits many dependencies (specifically those in test_requirements.txt), set the MINIMAL_KATS=1 environment variable during installation. Note that a minimal installation will disable many functionalities and trigger warnings when importing kats.

    pip install --upgrade pip
    pip install kats
    
    # For a minimal installation:
    MINIMAL_KATS=1 pip install kats
  3. Perform Hyperparameter Tuning with Grid Search

    main

    Kats allows efficient hyperparameter tuning using a search method factory. This requires ax-platform (e.g., pip install ax-platform).

    Workflow:

    1. Define a parameters_grid_search as a list of dictionaries specifying name, type (e.g., 'choice'), values, and value_type.
    2. Create a search method using tpt.SearchMethodFactory.create_search_method with SearchMethodEnum.GRID_SEARCH.
    3. Define an evaluation_function(params) that fits a model on training data and returns an error metric (like MAE) on test data.
    4. Call generate_evaluate_new_parameter_values(evaluation_function).
    5. Retrieve results via list_parameter_value_scores().
  4. Load pretrained Global Model Ensembles

    main

    Kats provides pretrained daily GMEnsemble objects trained on the M4 dataset. You can download these files and load them directly for forecasting.

    Available models:

    • RNN-GME: Recurrent Neural Network ensemble.
    • S2S-GME: Sequence to Sequence ensemble.

    To use a pretrained model, download the .p file and use load_gmensemble_from_file.

  5. Train and use a single `GMModel`

    main

    A GMModel can be initialized with a GMParam instance. It is trained using a list or dictionary of TimeSeriesData objects.

    Workflow:

    1. Initialize: gm = GMModel(gmparam)
    2. Train: gm.train(train_TSs) returns training information.
    3. Predict: gm.predict(test_TSs, steps=N) returns a dictionary where keys are time series identifiers and values are pd.DataFrame objects containing forecasts for specified quantiles.
    4. Save/Load: Use gm.save_model(path) and load_gmmodel_from_file(path).
    5. JSON Serialization: Use global_model_to_json(gm) to get a JSON string and load_global_model_from_json(json_str) to reconstruct the model.
    from kats.models.globalmodel.model import GMModel, load_gmmodel_from_file
    from kats.models.globalmodel.serialize import global_model_to_json, load_global_model_from_json
    
    # Initialize and train
    gm = GMModel(gmparam)
    training_info = gm.train(train_TSs)
    
    # Predict
    fcsts = gm.predict(test_TSs, steps=3)
    
    # Save and Load
    gm.save_model("gm_example_1.p")
    gm2 = load_gmmodel_from_file("gm_example_1.p")
    
    # JSON workflow
    gm_str = global_model_to_json(gm)
    gm3 = load_global_model_from_json(gm_str)
  6. Initialize TimeSeriesData from a Pandas DataFrame

    main

    To use Kats models, you must first convert your data into a TimeSeriesData object. If your DataFrame has a column named time, it will be used automatically. If not, you must rename your time column to time or specify it during processing.

    import pandas as pd
    from kats.consts import TimeSeriesData
    
    # Ensure the time column is named 'time'
    df = pd.read_csv("your_data.csv")
    df.columns = ["time", "value"]
    
    # Convert to Kats TimeSeriesData
    ts = TimeSeriesData(df)
    from kats.consts import TimeSeriesData
    
    # Note: If the column holding the time values is not called time, you will want to specify the name of this column.
    air_passengers_df.columns = ["time", "value"]
    air_passengers_ts = TimeSeriesData(air_passengers_df)
  7. Forecast time series using ProphetModel

    main

    Kats provides a ProphetModel wrapper to perform forecasting. The workflow involves:

    1. Loading data into a pandas DataFrame.
    2. Converting the DataFrame to a TimeSeriesData object.
    3. Defining model parameters using ProphetParams.
    4. Initializing the ProphetModel with the data and parameters.
    5. Calling .fit() to train the model.
    6. Calling .predict() to generate future values.
    import pandas as pd
    from kats.consts import TimeSeriesData
    from kats.models.prophet import ProphetModel, ProphetParams
    
    # Load data
    air_passengers_df = pd.read_csv(
        "../kats/data/air_passengers.csv",
        header=0,
        names=["time", "passengers"],
    )
    
    # Convert to TimeSeriesData object
    air_passengers_ts = TimeSeriesData(air_passengers_df)
    
    # Create model parameters (e.g., multiplicative seasonality)
    params = ProphetParams(seasonality_mode='multiplicative')
    
    # Create and fit the model
    m = ProphetModel(air_passengers_ts, params)
    m.fit()
    
    # Predict next 30 months
    fcst = m.predict(steps=30, freq="MS")
  8. Detect change points using CUSUMDetector

    main

    Use the CUSUMDetector to identify change points in a time series. The detector requires a TimeSeriesData object and is invoked via the .detector() method.

    import numpy as np
    import pandas as pd
    from kats.consts import TimeSeriesData
    from kats.detectors.cusum_detection import CUSUMDetector
    
    # Simulate time series with an increase
    np.random.seed(10)
    df_increase = pd.DataFrame(
        {
            'time': pd.date_range('2019-01-01', '2019-03-01'),
            'increase': np.concatenate([np.random.normal(1, 0.2, 30), np.random.normal(2, 0.2, 30)]),
        }
    )
    
    # Convert to TimeSeriesData object
    timeseries = TimeSeriesData(df_increase)
    
    # Run detector and find change points
    change_points = CUSUMDetector(timeseries).detector()
  9. Extract features using TsFeatures

    main

    The TsFeatures class allows you to extract meaningful statistical features from a time series. Use the .transform() method on a TimeSeriesData object to calculate these features.

    import pandas as pd
    from kats.consts import TimeSeriesData
    from kats.tsfeatures.tsfeatures import TsFeatures
    
    # Load data
    air_passengers_df = pd.read_csv(
        "../kats/data/air_passengers.csv",
        header=0,
        names=["time", "passengers"],
    )
    
    # Convert to TimeSeriesData object
    air_passengers_ts = TimeSeriesData(air_passengers_df)
    
    # Calculate the TsFeatures
    features = TsFeatures().transform(air_passengers_ts)
  10. Forecast with ProphetModel

    main

    Kats follows the sklearn model API pattern (fit and predict). To use the Prophet model, ensure fbprophet is installed (e.g., pip install kats[prophet]).

    1. Create a ProphetParams instance to configure seasonality.
    2. Initialize ProphetModel with your TimeSeriesData and parameters.
    3. Call .fit() to train the model.
    4. Call .predict(steps=N, freq="FREQ") to generate a forecast.