Skip to content

Instantly share code, notes, and snippets.

params_mean = pm.summary(trace_trunc, var_names = ["r", "alpha", "a", "b"])["mean"]
params_mean
@meraldo-aliz
meraldo-aliz / bayes.py
Last active September 14, 2023 04:51
lifetimes
from pymc3.math import log, exp, where
import pymc3 as pm
import numpy as np
# We use the "calibration" portion of the dataset to train the model
N = rfm_cal_holdout.shape[0] # number of customers
x = rfm_cal_holdout['frequency_cal'].values # repeat purchase frequency
t_x = rfm_cal_holdout['recency_cal'].values # recency
T = rfm_cal_holdout['T_cal'].values # time since first purchase (T)
@meraldo-aliz
meraldo-aliz / rmse.py
Created March 2, 2022 05:46
lifetimes
from sklearn.metrics import mean_squared_error
RMSE = mean_squared_error(y_true = rfm_cal_holdout["n_transactions_holdout_real"],
y_pred = rfm_cal_holdout["n_transactions_holdout_pred"],
squared = False)
RMSE # = 1.3536793286521
# the real number of transactions in the observation period, which equals frequency_holdout + 1
rfm_cal_holdout["n_transactions_holdout_real"] = rfm_cal_holdout["frequency_holdout"] + 1
# the predicted number of transactions in the next 26 weeks (length of the observation period)
rfm_cal_holdout["n_transactions_holdout_pred"] = bgf.predict(t=26,
frequency=rfm_cal_holdout['frequency_cal'],
recency=rfm_cal_holdout['recency_cal'],
T=rfm_cal_holdout['T_cal'])
# comparison of the real and predicted transactions
@meraldo-aliz
meraldo-aliz / high_value.py
Last active March 2, 2022 05:11
lifetimes
VALUE_10_PRED_THRESHOLD = 10
# filtering for high-value customers
rfm_cal_holdout.loc[rfm_cal_holdout["value_10_pred"]>VALUE_10_PRED_THRESHOLD, ["value_10_pred"]]
import seaborn as sns
fig, ax = plt.subplots(figsize = (12, 7))
ax = sns.histplot(rfm_cal_holdout["value_10_pred"],
kde=False,
binwidth = 2)
ax.set_title(f'Customer value histogram')
ax.set_xlabel(r'Customer value estimate for 10 periods ($)')
ax.set_ylabel(r'Number of customers in each bin')
ax.set_xlim(-2,20)
rfm_cal_holdout["value_10_pred"].describe()
# the predicted number of transactions in the next 10 weeks
rfm_cal_holdout["n_transactions_10_pred"] = bgf.predict(t=10,
frequency=rfm_cal_holdout['frequency_cal'],
recency=rfm_cal_holdout['recency_cal'],
T=rfm_cal_holdout['T_cal'])
# the probability of being alive
rfm_cal_holdout["alive_prob"] = bgf.conditional_probability_alive(frequency=rfm_cal_holdout['frequency_cal'],
from lifetimes.plotting import plot_probability_alive_matrix
_ = plot_probability_alive_matrix(bgf)
from lifetimes.plotting import plot_frequency_recency_matrix
_ = plot_frequency_recency_matrix(bgf)