Exemplo n.º 1
0
Arquivo: hw3.py Projeto: aydbusra/hw3
def estimate_holt(df,
                  seriesname,
                  alpha=0.2,
                  slope=0.1,
                  trend="add",
                  estimationlength=2):
    numbers = np.asarray(df[seriesname], dtype='float')
    model = Holt(numbers)
    fit = model.fit(alpha, slope, trend)
    estimate = fit.forecast(estimationlength)
    return estimate

    # Perform Dickey-Fuller test:
    print("Results of Dickey-Fuller Test:")
    array = np.asarray(timeseries, dtype='float')
    np.nan_to_num(array, copy=False)
    dftest = adfuller(array, autolag='AIC')
    dfoutput = pd.Series(dftest[0:4],
                         index=[
                             'Test Statistic', 'p-value', '#Lags Used',
                             'Number of Observations Used'
                         ])
    for key, value in dftest[4].items():
        dfoutput['Critical Value (%s)' % key] = value
    print(dfoutput)
def estimate_Holt(array, alpha, slope, sizeestimate):
    model = Holt(array)
    fit = model.fit(smoothing_level=alpha, smoothing_slope=slope)
    forecast = fit.forecast(sizeestimate)
    for index in range(len(forecast)):
        forecast[index] = round(forecast[index], 4)
    return forecast
def estimate_holt(df, seriesname, alpha=0.2, slope=0.1, trend="add"):
    numbers = np.asarray(df[seriesname], dtype='float')
    model = Holt(numbers)
    fit = model.fit(alpha, slope, trend)
    estimate = fit.forecast(2)[-1]
    print("Dollar estimation:", estimate)
    return estimate
Exemplo n.º 4
0
def evaluate_holt_model(X):
    """
    Evaluate a Holt Model
    :param X: list or series containing all historical data
    :return: mse (error metric) and the fitted model
    """
    # Prepare training dataset
    train_size = int(len(X) * 0.75)
    train, test = X[0:train_size], X[train_size:]
    history = [x for x in train]

    # Make predictions
    predictions = list()
    for t in range(len(test)):
        # Fit model
        model = Holt(history)
        model_fit = model.fit()

        # Forecast
        yhat = model_fit.forecast()[0]

        # Store prediction and move forward one time step
        predictions.append(yhat)
        history.append(test[t])

    # calculate out of sample error
    mse = mean_squared_error(test, predictions)
    return mse, model_fit
Exemplo n.º 5
0
def estimate_Holt(dataframe, name, alpha, slope, sizeestimate):
    array = np.asarray(dataframe[name])
    model = Holt(array)
    fit = model.fit(smoothing_level = alpha,smoothing_slope = slope)
    forecast = fit.forecast(sizeestimate)
    for index in range ( len(forecast) ):
        forecast[index] = round(forecast[index], 4)
    return forecast
def estimate_Holt(dataframe, name, alpha, slope, sizeestimate):
    # Holt requires an array to work with, so we convert the column into an array
    array = np.asarray(dataframe[name])
    model = Holt(array)
    fit = model.fit(smoothing_level = alpha,smoothing_slope = slope)
    forecast = fit.forecast(sizeestimate)
    for index in range ( len(forecast) ):
        forecast[index] = round(forecast[index], 4)
    return forecast
Exemplo n.º 7
0
    def DEF_damping_f(self, df, alpha, beta):
        try:
            double_exp = Holt(np.array(df['Actual']), exponential=True, damped=True)
            fit_double_exp = double_exp.fit(smoothing_level=alpha, smoothing_slope=beta,optimized=False)
            forecast = fit_double_exp.forecast()[0]

            Cluster, Warehouse, WF, YF = generate_attrib(df)
            self.df_forecast.append({'Cluster':Cluster, 'Warehouse':Warehouse, 'Year':YF, "Week": WF, "Forecast":forecast})
            return print(f'DEBUG:Forecast:{Cluster}:{Warehouse}:{YF}:{WF}:{forecast}')
        except:
            return print("ERROR:FORECAST-DEF_DAMPING")
Exemplo n.º 8
0
def run_holts(train, validate, target_variable,exponential,  smoothing_level = .1, smoothing_slope = .1):
    # Create model object
    model = Holt(train[target_variable], exponential = exponential)

    # Fit model 
    model = model.fit(smoothing_level = smoothing_level, smoothing_slope=smoothing_slope, optimized = False)

    # Create predictions
    y_pred = model.predict(start=validate.index[0], end=validate.index[-1])

    return model, y_pred
Exemplo n.º 9
0
    def create_Holt_Winters(self, series, param):
        assert type(param) == str
        self.args = param

        # self.print_params(param)

        model = Holt(series,
                     exponential=self.get_bool('exponential'),
                     damped=self.get_bool('damped'))
        return model.fit(smoothing_level=self.get_float('smoothing_level'),
                         smoothing_slope=self.get_float('smoothing_slope'),
                         optimized=self.get_bool('optimized'),
                         damping_slope=self.get_float('damping_slope'))
Exemplo n.º 10
0
    def predict(self, test_X, test_Y):
        predictions = numpy.empty(0)
        for t in range(0, test_Y.shape[0]):
            array = numpy.hstack((self.train_Y, test_Y[:t]))
            model = Holt(array,
                         exponential=self.exponential,
                         damped=self.damped)
            fit = model.fit(smoothing_level=self.smoothing_level,
                            smoothing_slope=self.smoothing_slope,
                            damping_slope=self.damping_slope,
                            optimized=self.optimized)
            predictions = numpy.append(predictions, fit.forecast(1)[0])

        return predictions
Exemplo n.º 11
0
def holts(train, validate, yhat_df):
    '''
    This function sets default parameters for Holt's model. 
    yhat_items makes predictions based on model.
    '''
    for col in train.columns:
        model = Holt(train[col], exponential=False, damped=True)
        model = model.fit(smoothing_level=.1,
                          smoothing_slope=.1,
                          optimized=True)
        yhat_items = model.predict(start=validate.index[0],
                                   end=validate.index[-1])
        yhat_df[col] = round(yhat_items, 2)
    return yhat_df
Exemplo n.º 12
0
class TS_Holt(object):
    def __init__(self, folder_debug=None, filename_weights=None):
        self.name = 'TS_Holt'
        self.model = []
        self.folder_debug = folder_debug

        self.exponential = False
        self.damped = True
        self.optimized = False
        self.damping_slope = 0.98
        self.smoothing_slope = 0.2
        self.smoothing_level = 0.8
        self.train_X = []
        self.train_Y = []
        return
# ----------------------------------------------------------------------------------------------------------------

    def train(self, array_X, array_Y):
        self.train_X = array_X
        self.train_Y = array_Y
        self.model = Holt(array_Y,
                          exponential=self.exponential,
                          damped=self.damped)
        self.fit = self.model.fit(smoothing_level=self.smoothing_level,
                                  smoothing_slope=self.smoothing_slope,
                                  damping_slope=self.damping_slope,
                                  optimized=self.optimized)
        res = self.fit.fittedvalues
        return res
#----------------------------------------------------------------------------------------------------------------------

    def predict_n_steps_ahead(self, n_steps):
        res = self.fit.forecast(n_steps)[0]
        return res
# ----------------------------------------------------------------------------------------------------------------------

    def predict(self, test_X, test_Y):
        predictions = numpy.empty(0)
        for t in range(0, test_Y.shape[0]):
            array = numpy.hstack((self.train_Y, test_Y[:t]))
            model = Holt(array,
                         exponential=self.exponential,
                         damped=self.damped)
            fit = model.fit(smoothing_level=self.smoothing_level,
                            smoothing_slope=self.smoothing_slope,
                            damping_slope=self.damping_slope,
                            optimized=self.optimized)
            predictions = numpy.append(predictions, fit.forecast(1)[0])

        return predictions
def holt(train, validate, target_var, eval_df):

    model_type = "Holt's Linear Trend"

    model = Holt(train[target_var], exponential=False)
    model = model.fit(smoothing_level=.1, smoothing_slope=.1, optimized=False)

    temps = model.predict(start=validate.index[0], end=validate.index[-1])

    yhat = pd.DataFrame({target_var: '1'}, index=validate.index)
    yhat[target_var] = round(temps, 4)

    rmse = plot_and_eval(train, validate, yhat, target_var, model_type)

    eval_df = append(model_type, target_var, rmse, eval_df)

    return eval_df
Exemplo n.º 14
0
def estimate_holt(array, alpha, slope, a):
    numbers = array
    model = Holt(numbers)
    fit = model.fit(alpha, slope)
    estimate = fit.forecast(a)[-1]
    return estimate
Exemplo n.º 15
0
Arquivo: 1b .py Projeto: ctelkok/HW3
def estimate_holt(df, seriesname, alpha=0.2, slope=0.1):
    numbers = np.asarray(df[seriesname])
    model = Holt(numbers)
    fit = model.fit(alpha, slope)
    estimate = fit.forecast(1)[-1]
    return estimate
Exemplo n.º 16
0
plt.plot(train['Thousands of Passengers'], label='Train')
plt.plot(test['Thousands of Passengers'], label='Test')
plt.plot(y_hat['SES'], label='Simple Exp Smoothing')
# 트렌드와 패턴이 반영안된 걸 확인할 수 있음
# %%
# mse가 너무커서 루트를 씌워줌
rmse_ses = np.sqrt(mean_squared_error(test['Thousands of Passengers'],y_hat['SES'])
)
# %%
from statsmodels.tsa.api import Holt

# %%
holt_model = Holt(train['Thousands of Passengers'])

# %%
holt_result = holt_model.fit()

# %%
y_hat['Holt'] = holt_result.forecast(len(test))

# %%
plt.plot(train['Thousands of Passengers'], label='Train')
plt.plot(test['Thousands of Passengers'], label='Test')
plt.plot(y_hat['Holt'], label='Simple Exp Smoothing')
# 트렌드는 반영된 것을 확인할 수 있음
# %%
rmse_holt = np.sqrt(mean_squared_error(test['Thousands of Passengers'],y_hat['Holt'])
)
#ses보다 줄어들었음을 확인
# %%
# Holt_winters
def estimate_holt(df, alpha=0.2, slope=0.1):
    model = Holt(df)
    fit = model.fit(alpha, slope)
    estimate = fit.forecast(1)[-1]
    return estimate
Exemplo n.º 18
0
 def damped_double_exponential_smoothing(self, y, bias, alpha, beta):
     smoother = Holt(y - bias, damped_trend=True)
     fit_model = smoother.fit(smoothing_level=alpha, smoothing_trend=beta)
     fitted = fit_model.fittedvalues
     self.model_params = (fit_model, bias, len(y))
     return fitted
Exemplo n.º 19
0
def estimate_holt(data, alpha=0.2, slope=0.1, trend='add', fc=1):
  numbers = np.asarray(data, dtype='float')
  model = Holt(numbers)
  fit = model.fit(alpha, slope, trend)
  estimate = fit.forecast(fc)[-1]
  return estimate