pythonrneural-networkforecast

Do Python have a model which is similar to nnetar in R's package forecast?


R's package 'forecast' has a function nnetar, which uses feed-forward neural networks with a single hidden layer to predict in time series.

Now I am using Python to do the similar analysis. I want to use neural network which does not need to be as complex as deep learning. Maybe 2 layers and a couple of nodes are good enough for my case.

So, does Python have a model of simple neural networks which can be used in time series lik nnetar? If not, how to deal with this problem?


Solution

  • There is arnet.py (pip install arnet) as a port of nnetar.R. It uses sklearn's MLPRegressor under the hood. Here is a reproducible example flow:

    import pandas as pd
    from arnet import ARNet
    
    # Sample data
    y = pd.read_csv("https://raw.githubusercontent.com/mustafaaydn/mustafaaydn.github.io/main/data/sunspots.csv",
                    index_col="Year").squeeze()
    
    # Fit-predict
    model = ARNet()
    model.fit(y)
    forecasts = model.predict(n_steps=20)
    
    # Plot
    ARNet.plot(lines=[y, model.fitted_values_, forecasts],
               labels=["y-train", "in-sample preds", "out-sample preds"],
               figure_kwargs={"xaxis_title": "Year", "yaxis_title": "# of spots",
                              "title": "Forecasting dark spots on the Sun"})
    

    which yields example_plot

    >>> model
    ARNet(base_model=MLPRegressor(hidden_layer_sizes=5, max_iter=2000), p=9)
    

    It has chosen the past lags to look at (p) as well as the number of hidden neurons automatically, following nnetar.R.

    This is actually a bit more generic than nnetar.R -- one can use any sklearn-compatible estimator, so, for example, if you use LinearRegression as the base model, you'll get the good old linear AR(p) estimator (actually SARX(p, P) because there is support for seasonality and exogenous regressors). Here is an example for using this as an AR(p) model.

    Further information: examples, API.

    Disclaimer: author here.