ar model python

Solutions on MaxInterview for ar model python by the best coders in the world

showing results for - "ar model python"
Lily
21 Aug 2016
1# create and evaluate an updated autoregressive model
2from pandas import read_csv
3from matplotlib import pyplot
4from statsmodels.tsa.ar_model import AutoReg
5from sklearn.metrics import mean_squared_error
6from math import sqrt
7# load dataset
8series = read_csv('daily-minimum-temperatures.csv', header=0, index_col=0, parse_dates=True, squeeze=True)
9# split dataset
10X = series.values
11train, test = X[1:len(X)-7], X[len(X)-7:]
12# train autoregression
13window = 29
14model = AutoReg(train, lags=29)
15model_fit = model.fit()
16coef = model_fit.params
17# walk forward over time steps in test
18history = train[len(train)-window:]
19history = [history[i] for i in range(len(history))]
20predictions = list()
21for t in range(len(test)):
22	length = len(history)
23	lag = [history[i] for i in range(length-window,length)]
24	yhat = coef[0]
25	for d in range(window):
26		yhat += coef[d+1] * lag[window-d-1]
27	obs = test[t]
28	predictions.append(yhat)
29	history.append(obs)
30	print('predicted=%f, expected=%f' % (yhat, obs))
31rmse = sqrt(mean_squared_error(test, predictions))
32print('Test RMSE: %.3f' % rmse)
33# plot
34pyplot.plot(test)
35pyplot.plot(predictions, color='red')
36pyplot.show()
37
Mae
20 Jul 2017
1# create and evaluate a static autoregressive model
2from pandas import read_csv
3from matplotlib import pyplot
4from statsmodels.tsa.ar_model import AutoReg
5from sklearn.metrics import mean_squared_error
6from math import sqrt
7# load dataset
8series = read_csv('daily-minimum-temperatures.csv', header=0, index_col=0, parse_dates=True, squeeze=True)
9# split dataset
10X = series.values
11train, test = X[1:len(X)-7], X[len(X)-7:]
12# train autoregression
13model = AutoReg(train, lags=29)
14model_fit = model.fit()
15print('Coefficients: %s' % model_fit.params)
16# make predictions
17predictions = model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)
18for i in range(len(predictions)):
19	print('predicted=%f, expected=%f' % (predictions[i], test[i]))
20rmse = sqrt(mean_squared_error(test, predictions))
21print('Test RMSE: %.3f' % rmse)
22# plot results
23pyplot.plot(test)
24pyplot.plot(predictions, color='red')
25pyplot.show()
26