File size: 13,792 Bytes
6f4f21f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
from data_utils.data_generation import UpliftSimulation
from data_utils.exploratory_data_analysis import ExploratoryAnalysis
from data_utils.feature_importance import FeatureImportance
from models_utils.ml_models import ModelTraining
from eval_utils.evaluation import ModelEvaluator

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import streamlit as st

X_names = [
            'AgeIndex', 'IncomeIndex', 'PurchaseFrequencyIndex',
            'AccountLifetimeIndex', 'AverageTransactionValueIndex', 'PreferredPaymentMethodIndex', 'RegionIndex',
            'EmailDiscountCTRIndex', 'WebDiscountCTRIndex', 'SocialMediaEngagementIndex',
            'DirectMailDiscountResponseIndex', 'InAppDiscountEngagementIndex', 'FlashSaleParticipationIndex',
            'SeasonalPromoInterestIndex', 'LoyaltyProgramEngagementIndex', 'ReferralBonusUsageIndex',
            'DiscountCodeRedemptionIndex', 'VIPSaleAccessIndex', 'EarlyAccessOptInIndex',
            'ProductReviewAfterDiscountIndex', 'UpsellConversionIndex', 'CrossSellInterestIndex',
            'BundlePurchaseIndex', 'SubscriptionUpgradeIndex', 'CustomerFeedbackIndex',
            'BrowserTypeIndex', 'DeviceCategoryIndex', 'OperatingSystemIndex',
            'SessionStartTimeIndex', 'LanguagePreferenceIndex', 'NewsletterSubscriptionIndex',
            'AccountVerificationStatusIndex', 'AdBlockerPresenceIndex'
        ]

# Title
st.title("Uplift Modeling in Retail Demo")

tabs = st.sidebar.radio("Navigation", ["Data generation", "Exploratory analysis", "Model training", "Economic effects"])

if tabs == "Data generation":

    st.header("Data Generation")

    # Description
    st.write("""
    This app creates a simulated dataset for a special kind of analysis called uplift modeling, which helps understand the effect of different actions (like promotions) on customer behavior. We use some default settings to make things easy:
    - We're looking at whether customers make a purchase or not.
    - We compare different types of promotions (like no discount, 5% off, etc.).
    - The dataset includes 15 different pieces of information (features) about each customer.
    """)

    # Interactive number of samples selection
    n = st.number_input('Number of Samples (n)', min_value=1000, value=10000, step=1000,
                        help="Total number of samples to generate in the dataset.")

    # Default values for other variables
    y_name = 'conversion'
    treatment_group_keys = ['control', 'discount_05', 'discount_10', 'discount_15']
    n_classification_features = 15
    n_classification_informative = 7
    n_classification_repeated = 0
    n_uplift_increase_dict = {'discount_05': 4, 'discount_10': 3, 'discount_15': 3}
    n_uplift_decrease_dict = {'discount_05': 0, 'discount_10': 0, 'discount_15': 0}
    positive_class_proportion = 0.05
    random_seed = 8097

    # Button to generate dataset
    if st.button('Generate Dataset'):
        uplift_sim = UpliftSimulation(n=n, y_name=y_name, treatment_group_keys=treatment_group_keys,
                                    n_classification_features=n_classification_features,
                                    n_classification_informative=n_classification_informative,
                                    n_classification_repeated=n_classification_repeated,
                                    n_uplift_increase_dict=n_uplift_increase_dict,
                                    n_uplift_decrease_dict=n_uplift_decrease_dict,
                                    positive_class_proportion=positive_class_proportion,
                                    random_seed=random_seed)
        uplift_sim.simulate_dataset()
        uplift_sim.apply_discounts_and_clean()
        uplift_sim.postprocess_tables()
        uplift_sim.add_monetary_effect()
        st.session_state.uplift_sim = uplift_sim # Store in session state

        st.write("Dataset Generated Successfully!")

        st.subheader("User profiles")
        st.write('Features that represent a customer such as age, income, purchase frequency, etc')
        st.dataframe(uplift_sim.dataframes[0].head(3))

        st.subheader("Treatments data")
        st.write('Information about the different treatments (discounts) that were applied to the customers as discounts in different channels (web, email, mobile), early access, etc')
        st.dataframe(uplift_sim.dataframes[1].head(3))

        st.subheader("Other data")
        st.write('Other data that can be used in the analysis')
        st.dataframe(uplift_sim.dataframes[2].head(3))

if tabs == "Exploratory analysis":

    st.header("Exploratory Analysis")

    if 'uplift_sim' in st.session_state:

        st.subheader('Summary statistics')
        uplift_sim = st.session_state.uplift_sim
        eda = ExploratoryAnalysis(uplift_sim.df)

        st.write('We begin by computing the total sum of conversions, sales (discounted price) and platform benefit. We can see that the total conversions and the total sales grows as the discount value is bigger. However, the platform benefit decreases.')
        
        sum_conversions, mean_conversions = eda.compute_summaries()
        st.write(sum_conversions)
        st.write(mean_conversions)

        st.write('We can also visualize the tradeoff between conversions and platform benefit by plotting the mean benefit per user on the y-axis and the mean conversion rate on the x-axis, for each treatment group.')
        mean_benefit_vs_conversion = eda.compute_mean_benefit_vs_conversion()

        fig, ax = plt.subplots()
        mean_benefit_vs_conversion.plot.scatter(x='conversion', y='benefit', c='DarkBlue', s=50, ax=ax)
        st.pyplot(fig)

        st.write('''
                 We further compute the Average Treatment Effect (ATE) for both the mean conversion rate and the mean benefit per user:
                 - Conversion ATE = Mean Conversion rate in the discounted group minus Mean Conversion rate in the control group
                 - Benefit ATE = Mean Benefit per user in the discounted group minus Mean Benefit per user in the control group
                 This helps illustrate how the discount value affects Conversion ATE and Benefit ATE.
                 ''')
        mean_conversions_ate = eda.compute_ate()

        fig, ax = plt.subplots()
        mean_conversions_ate.plot.scatter(x='conversion', y='benefit', c='DarkBlue', s=50, ax=ax)
        st.pyplot(fig)

        st.subheader('Feature importance')

        # Allow users to select a treatment group
        treatment_group = st.selectbox(
            'Select a treatment group',
            options=['discount_05', 'discount_10', 'discount_15'],
            index=0  # default to 'discount_05'
        )

        feature_importance = FeatureImportance(uplift_sim.df, X_names, y_name = 'conversion', treatment_group = treatment_group)
        fi = feature_importance.compute_feature_importance()
        fig, ax = plt.subplots()
        di_df_sorted = fi.sort_values(by='score', ascending=False)
        di_df_sorted[['feature', 'score']].plot.barh(x='feature', y='score', ax=ax)
        st.pyplot(fig)

        st.write("""
                    - AccountLifetimeIndex: Longer-standing accounts are key predictors of customer response to promotions \n
                    - CustomerFeedbackIndex: Customer feedback significantly influences the success of marketing strategies \n
                    - UpsellConversionIndex: The success rate of upselling is an important factor \n
                    - PurchaseFrequencyIndex: More frequent purchases indicate higher engagement and response to marketing efforts \n
                    - ReferralBonusUsedIndex and LoyaltyProgramEngagementIndex: Engagement with these programs is highly indicative of responsiveness to promotions
                 """)

    else:
        st.error("Please generate the dataset first.")

if tabs == "Model training":

    st.header("Model Training")

    if 'uplift_sim' in st.session_state:

        uplift_sim = st.session_state.uplift_sim

        model_trainer = ModelTraining(uplift_sim.df, 'conversion', X_names)

        model_type = st.radio("Choose the model type", ('Conversion Model', 'Benefit Model'))

        params = {
            'n_estimators': st.slider('Number of Estimators', 10, 100, 50),
            'max_depth': st.slider('Max Depth', 1, 10, 4),
            'colsample_bytree': st.slider('Colsample by Tree', 0.1, 1.0, 0.2),
            'subsample': st.slider('Subsample', 0.1, 1.0, 0.2),
        }
        control_name = 'control' # st.text_input('Control Group Name', 'control')
        test_size = st.slider('Test Size', 0.1, 0.9, 0.5)
        random_state = 20143 # st.slider('Random State', 0, 10000, 20143)

        if st.button('Train Model'):

            model_trainer.split_data(test_size=test_size, random_state=random_state)

            if model_type == 'Conversion Model':
                y_name = 'conversion' # st.selectbox('Select target variable for conversion', options=uplift_sim.target_options)
                model_trainer.y_name = y_name
                tau = model_trainer.fit_predict_classifier(params, control_name)
            elif model_type == 'BATE Model':
                y_name = 'benefit' # st.selectbox('Select target variable for benefit', options=uplift_sim.benefit_options)
                model_trainer.y_name = y_name
                tau = model_trainer.fit_predict_regressor(params, control_name)

            st.session_state.model_trainer = model_trainer

            feature_importances = model_trainer.compute_feature_importance()

            st.subheader('Feature Importances')
            fig, ax = plt.subplots()

            for k, v in feature_importances.items():
                st.write(f"Feature importance for {k}")
                v.plot(kind='barh', ax=ax)
                ax.set_xlabel("Importance")
                ax.set_ylabel("Feature")
                ax.set_title(f"Feature Importance for {model_type}")
                st.pyplot(fig)

    else:
        st.error("Please generate and preprocess the dataset first.")

if tabs == "Economic effects":

    st.header("Economic Effects Analysis")

    if 'uplift_sim' in st.session_state and 'model_trainer' in st.session_state:
        df_test = st.session_state.model_trainer.df_test
        model_type = st.radio("Choose the model type for analysis", ('Conversion Model', 'Benefit Model'))

        # Determine which model to use based on user selection
        if model_type == 'Conversion Model':
            model = st.session_state.model_trainer.conversion_learner_t
        elif model_type == 'Benefit Model':
            model = st.session_state.model_trainer.benefit_learner_t
        else:
            st.error("Invalid model type selected.")
            st.stop()

        if model == None:
            st.error("Please train the model first.")
            st.stop()

        evaluator = ModelEvaluator(model,
                                   df_test,
                                   X_names # df_test.columns.drop(['conversion', 'benefit', 'treatment_group_key'])
                                   )
        discounts = ['discount_05', 'discount_10', 'discount_15']
        qini_conversions = {}
        qini_benefits = {}

        for discount in discounts:
            qini_conv, qini_ben = evaluator.eval_performance(discount)
            qini_conversions[discount] = qini_conv
            qini_benefits[discount] = qini_ben
        
        # Plotting CATE Conversion
        st.subheader("CATE Conversion vs Targeted Population")
        fig, ax_conversion = plt.subplots()
        for discount, color in zip(discounts, ['b', 'g', 'y']):
            qini_conversions[discount].plot(ax=ax_conversion, x='index', y='S', color=color)
            qini_conversions[discount].plot(ax=ax_conversion, x='index', y='Random', color='r', ls='--')
        
        ax_conversion.legend([f'{d} model' for d in discounts] + [f'{d} random' for d in discounts], prop={'size': 10})
        ax_conversion.set_xlabel('Fraction of Targeted Users')
        ax_conversion.set_ylabel('CATE Conversion')
        ax_conversion.set_title('CATE Conversion vs Targeted Population')
        st.pyplot(fig)

        # Plotting CATE Benefit
        st.subheader("CATE Benefit vs Targeted Population")
        fig, ax_benefit = plt.subplots()
        for discount, color in zip(discounts, ['b', 'g', 'y']):
            qini_benefits[discount].plot(ax=ax_benefit, x='index', y='S', color=color)
            qini_benefits[discount].plot(ax=ax_benefit, x='index', y='Random', color='r', ls='--')

        ax_benefit.legend([f'{d} model' for d in discounts] + [f'{d} random' for d in discounts], prop={'size': 10})
        ax_benefit.set_xlabel('Fraction of Targeted Users')
        ax_benefit.set_ylabel('CATE Benefit')
        ax_benefit.set_title('CATE Benefit vs Targeted Population')
        st.pyplot(fig)

        # Plotting CATE Benefit vs CATE Conversion
        st.subheader("CATE Benefit vs CATE Conversion")
        fig, ax_comp = plt.subplots()
        colors = ['b', 'g', 'y']
        for i, discount in enumerate(discounts):
            qini_conc_test = pd.concat([qini_conversions[discount][['S']], qini_benefits[discount][['S']]], axis=1)
            qini_conc_test.columns = ['cate_conversion', 'cate_benefit']
            qini_conc_test.plot(ax=ax_comp, x='cate_conversion', y='cate_benefit', color=colors[i], label=f'{discount} model')

        ax_comp.legend(prop={'size': 10})
        ax_comp.set_xlabel('CATE Conversion')
        ax_comp.set_ylabel('CATE Benefit')
        ax_comp.set_title('CATE Benefit vs CATE Conversion')
        st.pyplot(fig)
        
    else:
        st.error("Please ensure the model is trained and the dataset is prepared.")