Machine Learning per il marketing con Python
Karolis Urbonas
Head of Analytics & Science, Amazon
# Esplora la distribuzione mensile delle osservazioni
online.groupby(['InvoiceMonth']).size()
InvoiceMonth
2010-12 4893
2011-01 3580
2011-02 3648
2011-03 4764
2011-04 4148
2011-05 5018
2011-06 4669
2011-07 4610
2011-08 4744
2011-09 7189
2011-10 8808
2011-11 9513
dtype: int64
# Escludi la variabile target online_X = online[online['InvoiceMonth']!='2011-11']# Definisci la data di snapshot NOW = dt.datetime(2011,11,1)# Crea le feature features = online_X.groupby('CustomerID').agg({ 'InvoiceDate': lambda x: (NOW - x.max()).days, 'InvoiceNo': pd.Series.nunique, 'TotalSum': np.sum, 'Quantity': ['mean', 'sum'] }).reset_index()features.columns = ['CustomerID', 'recency', 'frequency', 'monetary', 'quantity_avg', 'quantity_total']
print(features.head())
# Crea tabella pivot con transazioni mensili per cliente
cust_month_tx = pd.pivot_table(data=online, index=['CustomerID'],
values='InvoiceNo',
columns=['InvoiceMonth'],
aggfunc=pd.Series.nunique, fill_value=0)
print(cust_month_tx.head())

# Salva i nomi di colonna per ID e target custid = ['CustomerID'] target = ['2011-11']# Estrai la variabile target Y = cust_month_tx[target]# Estrai i nomi delle feature cols = [col for col in features.columns if col not in custid]# Salva le feature X = features[cols]
# Dividi casualmente il 25% dei dati per il test from sklearn.model_selection import train_test_split train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.25, random_state=99)# Stampa le shape dei dataset print(train_X.shape, train_Y.shape, test_X.shape, test_Y.shape)
(2529, 5) (2529, 1) (843, 5) (843, 1)
Machine Learning per il marketing con Python