本文整理汇总了Python中fbprophet.Prophet方法的典型用法代码示例。如果您正苦于以下问题:Python fbprophet.Prophet方法的具体用法?Python fbprophet.Prophet怎么用?Python fbprophet.Prophet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fbprophet
的用法示例。
在下文中一共展示了fbprophet.Prophet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_check_single_cutoff_forecast_func_calls
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_check_single_cutoff_forecast_func_calls(self):
m = Prophet()
m.fit(self.__df)
mock_predict = pd.DataFrame({'ds':pd.date_range(start='2012-09-17', periods=3),
'yhat':np.arange(16, 19),
'yhat_lower':np.arange(15, 18),
'yhat_upper': np.arange(17, 20),
'y': np.arange(16.5, 19.5),
'cutoff': [datetime.date(2012, 9, 15)]*3})
# cross validation with 3 and 7 forecasts
for args, forecasts in ((['4 days', '10 days', '115 days'], 3),
(['4 days', '4 days', '115 days'], 7)):
with patch('fbprophet.diagnostics.single_cutoff_forecast') as mock_func:
mock_func.return_value = mock_predict
df_cv = diagnostics.cross_validation(m, *args)
# check single forecast function called expected number of times
self.assertEqual(diagnostics.single_cutoff_forecast.call_count,
forecasts)
示例2: test_cross_validation_extra_regressors
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_cross_validation_extra_regressors(self):
df = self.__df.copy()
df['extra'] = range(df.shape[0])
df['is_conditional_week'] = np.arange(df.shape[0]) // 7 % 2
m = Prophet()
m.add_seasonality(name='monthly', period=30.5, fourier_order=5)
m.add_seasonality(name='conditional_weekly', period=7, fourier_order=3,
prior_scale=2., condition_name='is_conditional_week')
m.add_regressor('extra')
m.fit(df)
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='4 days', initial='135 days')
self.assertEqual(len(np.unique(df_cv['cutoff'])), 2)
period = pd.Timedelta('4 days')
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())
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)
示例3: main
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def main(args):
data = pd.read_csv(DATA_FILE, parse_dates=True, index_col='timestamp')
# Re-group data to fit for Prophet data format
data['ds'] = data.index
data = data.reindex(columns=['ds', 'v0', 'v1', 'result'])
data = data.rename(columns={"v0": 'y'})
model = Prophet()
model.fit(data.ix[data.index[0:500]])
future = model.make_future_dataframe(120, 'H')
forecast = model.predict(future)
model.plot(forecast)
model.plot_components(forecast)
plt.show()
示例4: test_cross_validation_logistic_or_flat_growth
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_cross_validation_logistic_or_flat_growth(self):
params = (x for x in ['logistic', 'flat'])
for growth in params:
with self.subTest(i=growth):
df = self.__df.copy()
if growth == "logistic":
df['cap'] = 40
m = Prophet(growth=growth).fit(df)
df_cv = diagnostics.cross_validation(
m, horizon='1 days', period='1 days', initial='140 days')
self.assertEqual(len(np.unique(df_cv['cutoff'])), 2)
self.assertTrue((df_cv['cutoff'] < df_cv['ds']).all())
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)
示例5: test_cross_validation_custom_cutoffs
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_cross_validation_custom_cutoffs(self):
m = Prophet()
m.fit(self.__df)
# When specify a list of cutoffs
# the cutoff dates in df_cv are those specified
df_cv1 = diagnostics.cross_validation(
m,
horizon='32 days',
period='10 days',
cutoffs=[pd.Timestamp('2012-07-31'), pd.Timestamp('2012-08-31')])
self.assertEqual(len(df_cv1['cutoff'].unique()), 2)
示例6: test_cross_validation_uncertainty_disabled
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_cross_validation_uncertainty_disabled(self):
df = self.__df.copy()
for uncertainty in [0, False]:
m = Prophet(uncertainty_samples=uncertainty)
m.fit(df, algorithm='Newton')
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='4 days', initial='115 days')
expected_cols = ['ds', 'yhat', 'y', 'cutoff']
self.assertTrue(all(col in expected_cols for col in df_cv.columns.tolist()))
df_p = diagnostics.performance_metrics(df_cv)
self.assertTrue('coverage' not in df_p.columns)
示例7: test_fit
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [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, control={'adapt_engaged': False})
示例8: anomaly_fbprophet
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def anomaly_fbprophet(lista_datos,num_fut,desv_mse=0,train=True,name='model-name'):
lista_puntos = np.arange(0, len(lista_datos),1)
df, df_train, df_test = create_train_test(lista_puntos, lista_datos)
m = Prophet()
df_temp = pd.DataFrame(df_train['valores'])
df_temp.rename(columns={"valores": "y"},inplace=True)
df_temp['ds']= pd.date_range(datetime.today(), periods=len(df_temp['y'])).strftime("%Y/%m/%d").tolist()
m.fit(df_temp)
future = m.make_future_dataframe(len(df_test['valores']))
future.tail()
forecast = m.predict(future)
engine = engine_output_creation('fbprophet')
engine.alerts_creation(forecast[-len(df_test['valores']):]['yhat'],df_test)
############## ANOMALY FINISHED,
print ("Anomaly finished. Start forecasting")
############## FORECAST START
df_temp = pd.DataFrame(df['valores'])
df_temp.rename(columns={"valores": "y"},inplace=True)
df_temp['ds']= pd.date_range(datetime.today(), periods=len(df_temp['y'])).strftime("%Y/%m/%d").tolist()
m_future = Prophet()
m_future.fit(df_temp)
future = m_future.make_future_dataframe(num_fut)
future.tail()
forecast = m_future.predict(future)
engine.forecast_creation( forecast[-num_fut:]['yhat'], len(lista_datos),num_fut)
engine.metrics_generation( df_test['valores'].values, forecast[-len(df_test['valores']):]['yhat'])
engine.debug_creation(forecast[-len(df['valores']):]['yhat'].tolist(),df_test)
return (engine.engine_output)
示例9: fit
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def fit(self, df: pd.DataFrame) -> None:
"""
Fit Prophet model on normal (inlier) data.
Parameters
----------
df
Dataframe with columns `ds` with timestamps and `y` with target values.
"""
if self.cap:
df['cap'] = self.cap
self.model.fit(df)
示例10: _upload_graph
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def _upload_graph(self, model, forecast):
import boto3
import matplotlib as mlp
# Need to plot graph for Prophet
mlp.use("agg")
from matplotlib import pyplot as plt
fig1 = model.plot(forecast)
fig2 = model.plot_components(forecast)
predict_fig_data = io.BytesIO()
component_fig_data = io.BytesIO()
fig1.savefig(predict_fig_data, format="png")
fig2.savefig(component_fig_data, format="png")
predict_fig_data.seek(0)
component_fig_data.seek(0)
# Upload figures to S3
# boto3 assuming environment variables "AWS_ACCESS_KEY_ID" and "AWS_SECRET_ACCESS_KEY":
# http://boto3.readthedocs.io/en/latest/guide/configuration.html#environment-variables
s3 = boto3.resource("s3")
predicted_fig_file = "predicted.png"
component_fig_file = "component.png"
# ACL should be chosen with your purpose
s3.Object(os.environ["S3_BUCKET"], predicted_fig_file).put(
ACL="public-read", Body=predict_fig_data, ContentType="image/png"
)
s3.Object(os.environ["S3_BUCKET"], component_fig_file).put(
ACL="public-read", Body=component_fig_data, ContentType="image/png"
)
示例11: load_context
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def load_context(self, context):
from fbprophet import Prophet
return
示例12: _run_prophet
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def _run_prophet(self, data: ProphetDataEntry, params: dict) -> np.array:
"""
Construct and run a :class:`Prophet` model on the given
:class:`ProphetDataEntry` and return the resulting array of samples.
"""
prophet = self.init_model(Prophet(**params))
# Register dynamic features as regressors to the model
for i in range(len(data.feat_dynamic_real)):
prophet.add_regressor(feat_name(i))
prophet.fit(data.prophet_training_data)
future_df = prophet.make_future_dataframe(
periods=self.prediction_length,
freq=self.freq,
include_history=False,
)
# Add dynamic features in the prediction range
for i, feature in enumerate(data.feat_dynamic_real):
future_df[feat_name(i)] = feature[data.train_length :]
prophet_result = prophet.predictive_samples(future_df)
return prophet_result["yhat"].T
示例13: test_simple_serialize
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [as 别名]
def test_simple_serialize(self):
m = Prophet()
days = 30
N = DATA.shape[0]
df = DATA.head(N - days)
m.fit(df)
future = m.make_future_dataframe(2, include_history=False)
fcst = m.predict(future)
model_str = model_to_json(m)
# Make sure json doesn't get too large in the future
self.assertTrue(len(model_str) < 200000)
z = json.loads(model_str)
self.assertEqual(z['__fbprophet_version'], '0.6.1.dev0')
m2 = model_from_json(model_str)
# Check that m and m2 are equal
self.assertEqual(m.__dict__.keys(), m2.__dict__.keys())
for k, v in m.__dict__.items():
if k in ['stan_fit', 'stan_backend']:
continue
if k == 'params':
self.assertEqual(v.keys(), m2.params.keys())
for kk, vv in v.items():
self.assertTrue(np.array_equal(vv, m2.params[kk]))
elif k in PD_SERIES and v is not None:
self.assertTrue(v.equals(m2.__dict__[k]))
elif k in PD_DATAFRAME and v is not None:
pd.testing.assert_frame_equal(v, m2.__dict__[k])
elif k == 'changepoints_t':
self.assertTrue(np.array_equal(v, m.__dict__[k]))
else:
self.assertEqual(v, m2.__dict__[k])
self.assertTrue(m2.stan_fit is None)
self.assertTrue(m2.stan_backend is None)
# Check that m2 makes the same forecast
future2 = m2.make_future_dataframe(2, include_history=False)
fcst2 = m2.predict(future2)
self.assertTrue(np.array_equal(fcst['yhat'].values, fcst2['yhat'].values))
示例14: test_cross_validation
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [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')
methods = [None, 'processes', 'threads', CustomParallelBackend()]
try:
from dask.distributed import Client
client = Client(processes=False) # noqa
methods.append("dask")
except ImportError:
pass
for parallel in methods:
df_cv = diagnostics.cross_validation(
m, horizon='4 days', period='10 days', initial='115 days',
parallel=parallel)
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')
# invalid alias
with self.assertRaises(ValueError, match="'parallel' should be one"):
diagnostics.cross_validation(m, horizon="4 days", parallel="bad")
# no map method
with self.assertRaises(ValueError, match="'parallel' should be one"):
diagnostics.cross_validation(m, horizon="4 days", parallel=object())
示例15: test_performance_metrics
# 需要导入模块: import fbprophet [as 别名]
# 或者: from fbprophet import Prophet [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=-1)
self.assertEqual(
set(df_none.columns),
{'horizon', 'coverage', 'mae', 'mape', 'mdape', 'mse', 'rmse'},
)
self.assertEqual(df_none.shape[0], 16)
# Aggregation level 0
df_0 = diagnostics.performance_metrics(df_cv, rolling_window=0)
self.assertEqual(len(df_0), 4)
self.assertEqual(len(df_0['horizon'].unique()), 4)
# Aggregation level 0.2
df_horizon = diagnostics.performance_metrics(df_cv, rolling_window=0.2)
self.assertEqual(len(df_horizon), 4)
self.assertEqual(len(df_horizon['horizon'].unique()), 4)
# 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.assertAlmostEqual(df_all[metric].values[0], df_none[metric].mean())
self.assertAlmostEqual(df_all['mdape'].values[0], df_none['mdape'].median())
# Custom list of metrics
df_horizon = diagnostics.performance_metrics(
df_cv, metrics=['coverage', 'mse'],
)
self.assertEqual(
set(df_horizon.columns),
{'coverage', 'mse', 'horizon'},
)
# Skip MAPE
df_cv.loc[0, 'y'] = 0.
df_horizon = diagnostics.performance_metrics(
df_cv, metrics=['coverage', 'mape'],
)
self.assertEqual(
set(df_horizon.columns),
{'coverage', 'horizon'},
)
df_horizon = diagnostics.performance_metrics(
df_cv, metrics=['mape'],
)
self.assertIsNone(df_horizon)
# List of metrics containing non-valid metrics
with self.assertRaises(ValueError):
diagnostics.performance_metrics(
df_cv, metrics=['mse', 'error_metric'],
)