本文整理汇总了Python中fbprophet.Prophet.predict方法的典型用法代码示例。如果您正苦于以下问题:Python Prophet.predict方法的具体用法?Python Prophet.predict怎么用?Python Prophet.predict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fbprophet.Prophet
的用法示例。
在下文中一共展示了Prophet.predict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_logistic_floor
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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())
示例2: test_fit_changepoint_not_in_history
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例3: test_fit_predict_no_changepoints
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例4: test_fit_predict_no_seasons
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例5: test_fit_predict
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例6: test_fit_predict_duplicates
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例7: build_forecast
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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
示例8: test_fit_predict_constant_history
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [as 别名]
def test_fit_predict_constant_history(self):
N = DATA.shape[0]
train = DATA.head(N // 2).copy()
train['y'] = 20
future = pd.DataFrame({'ds': DATA['ds'].tail(N // 2)})
m = Prophet()
m.fit(train)
fcst = m.predict(future)
self.assertEqual(fcst['yhat'].values[-1], 20)
train['y'] = 0
future = pd.DataFrame({'ds': DATA['ds'].tail(N // 2)})
m = Prophet()
m.fit(train)
fcst = m.predict(future)
self.assertEqual(fcst['yhat'].values[-1], 0)
示例9: get_predictions
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例10: run
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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);
示例11: add_prophet_features
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [as 别名]
def add_prophet_features(df_shop):
df = df_shop[['day', 'pays_count']].rename(columns={'day': 'ds', 'pays_count': 'y'})
results = []
biweek_max = df_shop.biweek_id.max()
for m in range(biweek_max - 1, 0, -1):
train_idx = df_shop.biweek_id >= m
df_train = df[train_idx]
not_null = ~df_train.y.isnull()
if not_null.sum() < 7:
continue
p = Prophet().fit(df_train)
future = p.make_future_dataframe(14, include_history=False)
pred = p.predict(future)
results.append(pred)
df_res = pd.concat(results)
df_res.columns = ['prophet_%s' % c for c in pred.columns]
df_res = df_shop.merge(df_res, how='left', left_on='day', right_on='prophet_ds')
del df_res['prophet_t'], df_res['prophet_ds']
df_res.drop_duplicates('days_from_beginning', keep='last', inplace=1)
if len(df_res) != len(df_shop):
raise Exception("size doesn't match")
return df_res
示例12: test_subdaily_holidays
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [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)
示例13: hello
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [as 别名]
def hello():
print('Hello, world!')
df = pd.read_csv(url)
df['y'] = np.log(df['y'])
df.head()
m = Prophet()
m.fit(df);
future = m.make_future_dataframe(periods=365)
future.tail()
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
return forecast.to_json(orient='table')
示例14: train_prophet
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [as 别名]
def train_prophet(df, modelDir, confidence=0.99):
# train and cache into modelDir
m = Prophet(
yearly_seasonality=True, daily_seasonality=True, interval_width=confidence
)
with suppress_stdout_stderr():
m.fit(df)
# Predict the future.
print "PREDICTING!"
future = m.make_future_dataframe(periods=0)
forecast = m.predict(future)
# Merge in the historical data.
forecast["y"] = df.y.astype(float)
# Backup the model.
forecast.to_csv(
pJoin(modelDir, "forecasted_{}.csv".format(confidence)), index=False
)
return forecast
示例15: create_prophet_m
# 需要导入模块: from fbprophet import Prophet [as 别名]
# 或者: from fbprophet.Prophet import predict [as 别名]
def create_prophet_m(self,app_name,z1,delay=24):
import pandas as pd
import pymysql
import warnings
warnings.filterwarnings("ignore")
from datetime import datetime, timedelta
import logging
from tqdm import tqdm
from fbprophet import Prophet
from sklearn.metrics import mean_squared_error as mse
import math
### --- For realtime pred ---###
full_df = z1.bw.iloc[0:len(z1)]
full_df = full_df.reset_index()
full_df.columns = ['ds','y']
#removing outliers
q50 = full_df.y.median()
q100 = full_df.y.quantile(1)
q75 = full_df.y.quantile(.75)
#print(max(train_df.y))
if((q100-q50) >= (2*q75)):
#print('ind')
full_df.loc[full_df.y>=(2*q75),'y'] = None
#-- Realtime prediction --##
#model
model_r = Prophet(yearly_seasonality=False,changepoint_prior_scale=.2)
model_r.fit(full_df)
future_r = model_r.make_future_dataframe(periods=delay,freq='H')
forecast_r = model_r.predict(future_r)
forecast_r.index = forecast_r['ds']
#forecast
pred_r = pd.DataFrame(forecast_r['yhat'][len(z1):(len(z1)+delay)])
pred_r=pred_r.reset_index()
#--- completes realtime pred ---#
train_end_index=len(z1.bw)-delay
train_df=z1.bw.iloc[0:train_end_index]
#train_df= train_df[train_df<cutter]
test_df=z1.bw.iloc[train_end_index:len(z1)]
train_df=train_df.reset_index()
test_df=test_df.reset_index()
train_df.columns=['ds','y']
#--- removing outliers in trainset ---#
q50 = train_df.y.median()
q100 = train_df.y.quantile(1)
q75 = train_df.y.quantile(.75)
#print(max(train_df.y))
if((q100-q50) >= (2*q75)):
#print('ind')
train_df.loc[train_df.y>=(2*q75),'y'] = None
test_df.columns=['ds','y']
#print('len of testdf = ',len(test_df))
#model
model = Prophet(yearly_seasonality=False,changepoint_prior_scale=.2)
model.fit(train_df)
future = model.make_future_dataframe(periods=len(test_df),freq='H')
forecast = model.predict(future)
forecast.index = forecast['ds']
#forecast
pred = pd.DataFrame(forecast['yhat'][train_end_index:len(z1)])
pred=pred.reset_index()
pred_df=pd.merge(test_df,pred,on='ds',how='left')
pred_df.dropna(inplace=True)
df=pd.DataFrame()
if(len(pred_df)>0):
pred_df['error_test']=pred_df.y-pred_df.yhat
MSE=mse(pred_df.y,pred_df.yhat)
RMSE=math.sqrt(MSE)
pred_df['APE']=abs(pred_df.error_test*100/pred_df.y)
MAPE=pred_df.APE.mean()
#print("App name:",app_name)
#print("MSE :",MSE)
#print("RMSE :",RMSE)
#print("MAPE :",MAPE)
q98=pred_df['APE'].quantile(0.98)
mape_q98=pred_df['APE'][pred_df.APE<pred_df['APE'].quantile(0.98)].mean()
df = pd.DataFrame({'length':len(z1),#'predicted_t':[forcast_lag],
'test_rmse':RMSE,
'test_mape':MAPE,
#.........这里部分代码省略.........