Package: nbeats-forecast
nbeats_forecastNeural Beats implementation librarynbeats_forecast is an end to end library for univariate time series forecasting using N-BEATS (https://arxiv.org/pdf/1905.10437v3.pdf- Published as conference paper in ICLR).
This library uses nbeats-pytorch (https://github.com/philipperemy/n-beats) as base and simplifies the task of forecasting using N-BEATS by providing a interface similar to scikit-learn and keras.Required: Python >=3.6Installation$pipinstallnbeats_forecastImportfromnbeats_forecastimportNBeatsInputnumpy array of size nx1OutputForecasted values as numpy array of size mx1Mandatory Parameters for the model:dataperiod_to_forecastBasic model with only mandatory parameters can be used to get forecasted values as shown below:importpandasaspd
fromnbeats_forecastimportNBeatsdata=pd.read_csv('data.csv')data=data.values#univariate time series data of shape nx1 (numpy array)model=NBeats(data=data,period_to_forecast=12)model.fit()forecast=model.predict()Other optional parameters for the object of the model  (as described in the paper) can be tweaked for better performance. If these parameters are not passed, default values as mentioned in the table below are considered.Optional parametersParameterTypeDefault ValueDescriptionbackcast_lengthinteger3* period_to_forecastExplained in the paperpathstring'  'path to save intermediate training checkpointcheckpoint_file_namestring'nbeats-training-checkpoint.th'name for checkpoint file ending in format  .thmodestring'cpu'Any of the torch.device modesbatch_sizeintegerlen(data)/15size of batchthetas_dimslist of integers[7, 8]Explained in the papernb_blocks_per_stackinteger3Explained in the papershare_weights_in_stackbooleanFalseExplained in the papertrain_percentfloat(below 1)0.8Percentage of data to be used for trainingsave_checkpointbooleanFalsesave intermediate checkpoint fileshidden_layer_unitsinteger128hissen layer unitsstacklist of integers[1,1]adding stacks in the model as per the paper passed in list as integer. Mapping is as follows -- 1: GENERIC_BLOCK,  2: TREND_BLOCK , 3: SEASONALITY_BLOCKMethodsfit(epoch,optimiser,plot,verbose):This method is used to train the model for number of gradient steps passed in the object of the model.Parameter - epoch : integerepoch is 100 * gradient steps. 25 epoch means 2500 weight updation steps.
If optimizer is not passed, default value is 25.Parameter - optimiseroptimizer from torch.optim can be passed as a parameter by including model.parameters as the variable.Example:model.fit(epoch=5,optimiser=torch.optim.AdamW(model.parameters, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.01, amsgrad=False))If optimizer is not passed, default optimizer used is Adam.Parameter- plot : booleanDefault value - FalseIf True, plots during training are shown.Parameter- verbose : booleanDefault value - TrueIf True, training details are printed.predict(predict_data):Parameter - predict_data (optional) : numpy array of size backcast_length x 1If predict_data is not passed, forecasted values returned will be continued from the last value of data passed in fit() during training.UPDATE:Added functionality:Predicting for other dataPassing predict_data:To get predictions for the some other data from trained model, pass the predict_data as a numpy array of shape backcast_length x 1 (default value for backcast length is 3* preiod_to_forecast).Example:You have trained a model for temperature forecast with hourly temperature data, period_to_forecast=4 and backcast_length=16 for Timestamp "13-12-2019 08:00:00" to "31-12-2019 08:00:00".Now you want to predict temperature from Timestamp "14-01-2020 17:00:00" using the trained model. You need to pass past data as predict_data with window equal to backcast_length(16 here). Here you need to pass values from "14-01-2020 01:00:00" to "14-01-2020 16:00:00"(16 values here) as numpy array of shape backcast_length x 1 (Here 16 x 1).Returns forecasted values.save(file):Saves the current step model after training. File needs to be passed a string. Format of the model to be saved is .thExample: model.save('model.th')load(file,optimizer):Parameter - fileLoad the saved model with format .thParameter - optimiseroptimizer from torch.optim can be passed as a parameter by including model.parameters as the variable.Example: model.load('model.th')EXAMPLES BELOWModel with a different optimiser and different stack is shown here.Predicting for other dataContinue training via the saved file or retrain with new data(load saved model and retrain)Load saved model and predict with dataExample 1Model with a different optimiser and different stack is shown here.Here  2: TREND_BLOCK and 3: SEASONALITY_BLOCK stacks are used.importpandasaspd
fromnbeats_forecastimportNBeats
fromtorchimportoptimdata=pd.read_csv('data.csv')data=data.values#univariate time series data of shape nx1(numpy array)model=NBeats(data=data,period_to_forecast=12,stack=[2,3],nb_blocks_per_stack=3,thetas_dims=[2,8])model.fit(epoch=5,optimiser=optim.AdamW(model.parameters,lr=0.001,betas=(0.9,0.999),eps=1e-08,weight_decay=0.01,amsgrad=False))forecast=model.predict()Example 2Predicting for other data with backcast_length=12.importpandasaspd
fromnbeats_forecastimportNBeats
fromtorchimportoptimdata=pd.read_csv('new_data.csv')data=data.values#univariate time series data of shape nx1(numpy array)model=NBeats(data=data,period_to_forecast=12,stack=[2,3],nb_blocks_per_stack=3,thetas_dims=[2,8])model.fit()list1=[36.7,38.5,39.4,36.75,38,39,38,37.45,38,39,39.5,40]pred=np.asarray(list1)forecast=model.predict(predict_data=pred)Example 3Continue training via the saved file or retrain with new dataimportpandasaspd
fromnbeats_forecastimportNBeats
fromtorchimportoptimnew_datdata=pd.read_csv('new_data.csv')data=data.values#univariate time series data of shape nx1(numpy array)model=NBeats(data=data,period_to_forecast=12,stack=[2,3],nb_blocks_per_stack=3,thetas_dims=[2,8])# use same model definition as saved modelmodel.load('nbeats.th',optimiser=optim.AdamW(model.parameters,lr=0.001,betas=(0.9,0.999),eps=1e-08,weight_decay=0.01,amsgrad=False)))model.fit()forecast=model.predict()Example 4Load saved model and predict with datafromnbeats_forecastimportNBeats
importnumpyasnp# use same model definition as saved modelmodel=NBeats(period_to_forecast=4,stack=[2,3],nb_blocks_per_stack=3,thetas_dims=[2,8])model.load(file='nbeats.th')list1=[36.7,38.5,39.4,36.75,38,39,38,37.45,38,39,39.5,40]pred=np.asarray(list1)forecast=model.predict(pred)