本文整理汇总了Python中fbprophet.Prophet.fit方法的典型用法代码示例。如果您正苦于以下问题:Python Prophet.fit方法的具体用法?Python Prophet.fit怎么用?Python Prophet.fit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fbprophet.Prophet
的用法示例。
在下文中一共展示了Prophet.fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_predictions
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def get_predictions(validate, train):
total_dates = train['date'].unique()
result = pd.DataFrame(columns=['id', 'unit_sales'])
problem_pairs = []
example_items = [510052, 1503899, 2081175, 1047674, 215327, 1239746, 765520, 1463867, 1010755, 1473396]
store47examples = validate.loc[(validate.store_nbr == 47) & (validate.item_nbr.isin(example_items))]
print("ONLY PREDICTING ITEMS {} IN STORE NO. 47!".format(example_items))
for name, y in store47examples.groupby(['item_nbr']):
# for name, y in validate.groupby(['item_nbr', 'store_nbr']):
item_nbr=int(name)
store_nbr = 47
df = train[(train.item_nbr==item_nbr)&(train.store_nbr==store_nbr)]
CV_SIZE = 16 #if you make it bigger, fill missing dates in cv with 0 if any
TRAIN_SIZE = 365
total_dates = train['date'].unique()
df = fill_missing_date(df, total_dates)
df = df.sort_values(by=['date'])
X = df[-TRAIN_SIZE:]
X = X[['date','unit_sales']]
X.columns = ['ds', 'y']
m = Prophet(yearly_seasonality=True)
try:
m.fit(X)
except ValueError:
print("problem for this item store pair")
problem_pairs.append((item_nbr, store_nbr))
continue
future = m.make_future_dataframe(periods=CV_SIZE)
pred = m.predict(future)
data = pred[['ds','yhat']].tail(CV_SIZE)
data = pred[['ds','yhat']].merge(y, left_on='ds', right_on='date')
data['unit_sales'] = data['yhat'].fillna(0).clip(0, 999999)
result = result.append(data[['id', 'unit_sales']])
return (result, problem_pairs)
示例2: run
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def run():
journal = ledger.read_journal("./secret/ledger.dat")
last_post = None
amount = 0
for post in journal.query(""):
if last_post == None or post.date == last_post.date:
if str(post.amount.commodity) != "£":
continue
amount = amount + post.amount
else:
print post.date, ",", amount
amount = 0
last_post = post
df = pd.read_csv('./testing.csv')
df['y'] = np.multiply(100, df['y'])
m = Prophet()
m.fit(df);
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
m.plot(forecast);
m.plot_components(forecast);
示例3: test_performance_metrics
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_performance_metrics(self):
m = Prophet()
m.fit(self.__df)
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='10 days', initial='90 days')
# Aggregation level none
df_none = diagnostics.performance_metrics(df_cv, rolling_window=0)
self.assertEqual(
set(df_none.columns),
{'horizon', 'coverage', 'mae', 'mape', 'mse', 'rmse'},
)
self.assertEqual(df_none.shape[0], 16)
# Aggregation level 0.2
df_horizon = diagnostics.performance_metrics(df_cv, rolling_window=0.2)
self.assertEqual(len(df_horizon['horizon'].unique()), 4)
self.assertEqual(df_horizon.shape[0], 14)
# Aggregation level all
df_all = diagnostics.performance_metrics(df_cv, rolling_window=1)
self.assertEqual(df_all.shape[0], 1)
for metric in ['mse', 'mape', 'mae', 'coverage']:
self.assertEqual(df_all[metric].values[0], df_none[metric].mean())
# Custom list of metrics
df_horizon = diagnostics.performance_metrics(
df_cv, metrics=['coverage', 'mse'],
)
self.assertEqual(
set(df_horizon.columns),
{'coverage', 'mse', 'horizon'},
)
示例4: test_cross_validation
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_cross_validation(self):
m = Prophet()
m.fit(self.__df)
# Calculate the number of cutoff points(k)
horizon = pd.Timedelta('4 days')
period = pd.Timedelta('10 days')
initial = pd.Timedelta('115 days')
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='10 days', initial='115 days')
self.assertEqual(len(np.unique(df_cv['cutoff'])), 3)
self.assertEqual(max(df_cv['ds'] - df_cv['cutoff']), horizon)
self.assertTrue(min(df_cv['cutoff']) >= min(self.__df['ds']) + initial)
dc = df_cv['cutoff'].diff()
dc = dc[dc > pd.Timedelta(0)].min()
self.assertTrue(dc >= period)
self.assertTrue((df_cv['cutoff'] < df_cv['ds']).all())
# Each y in df_cv and self.__df with same ds should be equal
df_merged = pd.merge(df_cv, self.__df, 'left', on='ds')
self.assertAlmostEqual(
np.sum((df_merged['y_x'] - df_merged['y_y']) ** 2), 0.0)
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='10 days', initial='135 days')
self.assertEqual(len(np.unique(df_cv['cutoff'])), 1)
with self.assertRaises(ValueError):
diagnostics.cross_validation(
m, horizon='10 days', period='10 days', initial='140 days')
示例5: test_fit_changepoint_not_in_history
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_changepoint_not_in_history(self):
train = DATA[(DATA['ds'] < '2013-01-01') | (DATA['ds'] > '2014-01-01')]
train[(train['ds'] > '2014-01-01')] += 20
future = pd.DataFrame({'ds': DATA['ds']})
forecaster = Prophet(changepoints=['2013-06-06'])
forecaster.fit(train)
forecaster.predict(future)
示例6: test_logistic_floor
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_logistic_floor(self):
m = Prophet(growth='logistic')
N = DATA.shape[0]
history = DATA.head(N // 2).copy()
history['floor'] = 10.
history['cap'] = 80.
future = DATA.tail(N // 2).copy()
future['cap'] = 80.
future['floor'] = 10.
m.fit(history, algorithm='Newton')
self.assertTrue(m.logistic_floor)
self.assertTrue('floor' in m.history)
self.assertAlmostEqual(m.history['y_scaled'][0], 1.)
fcst1 = m.predict(future)
m2 = Prophet(growth='logistic')
history2 = history.copy()
history2['y'] += 10.
history2['floor'] += 10.
history2['cap'] += 10.
future['cap'] += 10.
future['floor'] += 10.
m2.fit(history2, algorithm='Newton')
self.assertAlmostEqual(m2.history['y_scaled'][0], 1.)
fcst2 = m2.predict(future)
fcst2['yhat'] -= 10.
# Check for approximate shift invariance
self.assertTrue((np.abs(fcst1['yhat'] - fcst2['yhat']) < 1).all())
示例7: prophetForecast
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def prophetForecast(rawData, startDate, modelDir, partitions):
"""Forecasting with fbprophet"""
from fbprophet import Prophet
from fbprophet.diagnostics import cross_validation
partitions = int(partitions)
# initiate model
prophet = Prophet()
# put dates in df
dates = pd.date_range(start=startDate, periods=len(rawData), freq="H")
input_df = pd.DataFrame(rawData, columns=["y", "temp"])
input_df["ds"] = dates.to_pydatetime()
input_df.to_csv(pJoin(modelDir, "prophetin.csv"))
# give prophet the input data
with suppress_stdout_stderr():
prophet.fit(input_df)
# determine partition length for the cross-validation
total_hours = len(input_df.ds)
hp = total_hours // partitions # horizon and period
init = total_hours % partitions # total_hours - hp * (partitions - 1)
# train prophet w/ those partitions
# take a moment to appreciate this stupid way to pass the durations
out_df = cross_validation(
prophet,
initial="%d hours" % init,
horizon="%d hours" % hp,
period="%d hours" % hp,
)
out_df.to_csv(pJoin(modelDir, "prophetout.csv"))
return (list(out_df.yhat), list(out_df.yhat_lower), list(out_df.yhat_upper))
示例8: test_fit
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit(self):
train = pd.DataFrame({
'ds': np.array(['2012-05-18', '2012-05-20']),
'y': np.array([38.23, 21.25])
})
forecaster = Prophet(mcmc_samples=1)
forecaster.fit(train)
示例9: test_fit_predict
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_predict(self):
N = DATA.shape[0]
train = DATA.head(N // 2)
future = DATA.tail(N // 2)
forecaster = Prophet()
forecaster.fit(train)
forecaster.predict(future)
示例10: test_fit_predict_no_changepoints
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_predict_no_changepoints(self):
N = DATA.shape[0]
train = DATA.head(N // 2)
future = DATA.tail(N // 2)
forecaster = Prophet(n_changepoints=0)
forecaster.fit(train)
forecaster.predict(future)
示例11: test_fit_predict_no_seasons
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_predict_no_seasons(self):
N = DATA.shape[0]
train = DATA.head(N // 2)
future = DATA.tail(N // 2)
forecaster = Prophet(weekly_seasonality=False, yearly_seasonality=False)
forecaster.fit(train)
forecaster.predict(future)
示例12: test_fit_with_holidays
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_with_holidays(self):
holidays = pd.DataFrame({
'ds': pd.to_datetime(['2012-06-06', '2013-06-06']),
'holiday': ['seans-bday'] * 2,
'lower_window': [0] * 2,
'upper_window': [1] * 2,
})
model = Prophet(holidays=holidays, uncertainty_samples=0)
model.fit(DATA).predict()
示例13: test_subdaily_holidays
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_subdaily_holidays(self):
holidays = pd.DataFrame({
'ds': pd.to_datetime(['2017-01-02']),
'holiday': ['special_day'],
})
m = Prophet(holidays=holidays)
m.fit(DATA2)
fcst = m.predict()
self.assertEqual(sum(fcst['special_day'] == 0), 575)
示例14: test_fit_predict_duplicates
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def test_fit_predict_duplicates(self):
N = DATA.shape[0]
train1 = DATA.head(N // 2).copy()
train2 = DATA.head(N // 2).copy()
train2['y'] += 10
train = train1.append(train2)
future = pd.DataFrame({'ds': DATA['ds'].tail(N // 2)})
forecaster = Prophet()
forecaster.fit(train)
forecaster.predict(future)
示例15: build_forecast
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import fit [as 别名]
def build_forecast(
data,
forecast_range,
truncate_range=0
):
"""build a forecast for publishing
Args:
data (:obj:`pandas.data_frame`): data to build prediction
forecast_range (int): how much time into the future to forecast
truncate_range (int, optional): truncate output to CREST_RANGE
Returns:
pandas.DataFrame: collection of data + forecast info
['date', 'avgPrice', 'yhat', 'yhat_low', 'yhat_high', 'prediction']
"""
data['date'] = pd.to_datetime(data['date'])
filter_date = data['date'].max()
## Build DataFrame ##
predict_df = pd.DataFrame()
predict_df['ds'] = data['date']
predict_df['y'] = data['avgPrice']
## Run prediction ##
# https://facebookincubator.github.io/prophet/docs/quick_start.html#python-api
model = Prophet()
model.fit(predict_df)
future = model.make_future_dataframe(periods=forecast_range)
tst = model.predict(future)
predict_df = pd.merge(
predict_df, model.predict(future),
on='ds',
how='right'
)
## Build report for endpoint ##
report = pd.DataFrame()
report['date'] = pd.to_datetime(predict_df['ds'], format='%Y-%m-%d')
report['avgPrice'] = predict_df['y']
report['yhat'] = predict_df['yhat']
report['yhat_low'] = predict_df['yhat_lower']
report['yhat_high'] = predict_df['yhat_upper']
report['prediction'] = False
report.loc[report.date > filter_date, 'prediction'] = True
if truncate_range > 0:
cut_date = filter_date - timedelta(days=truncate_range)
report = report.loc[report.date > cut_date]
return report