0

Generalized Linear Models (GLM) applied to specific customer activities

Posted by .

If you want to model your customers using generalized linear models, below is an example of an R script that will loop through the customer data trust, build a data frame, and then build a GLM.

vectNumEnggs   <<- c();
vectNumPurch   <<- c();
vectTotSpend   <<- c();
vectAvgSpend   <<- c();
vectTotItems   <<- c();

totCustomers <<- 0;

dfBuilder <- function(customer) {
    totCustomers <<- totCustomers + 1;
    
    numPurch <<- 0;
    numEng <<- 0;
    totSpend <<- 0;
    
    indivPurch <<- vector();
    
    spendings <<- vector();
    totitems  <<- 0;
    
    for(i in c(1:length(customer[['actions']]))) {
        if (customer[['actions']][[i]][['action']] == 'purchase') {
        	numPurch <<- numPurch + 1;
    		totSpend <<- totSpend + customer[['actions']][[i]][['additional-data']][['amount']]
    		spendings = c(spendings, customer[['actions']][[i]][['additional-data']][['amount']]);
    		
    		if('line-items' %in% names(customer[['actions']][[i]][['additional-data']])){
	    		for (j in c(1:length(customer[['actions']][[i]][['additional-data']][['line-items']]))) {
	    			if('quantity' %in% names(customer[['actions']][[i]][['additional-data']][['line-items']][[j]])) {
	    				totitems <<- totitems + customer[['actions']][[i]][['additional-data']][['line-items']][[j]][['quantity']];	
	    			}
	    		}
    		}
    		
    	}
    	if (customer[['actions']][[i]][['action']] == 'comment') {
    		numEng <<- numEng + 1;
    	}
    }
    
    vectNumPurch <<- c(vectNumPurch, numPurch);
    vectNumEnggs <<- c(vectNumEnggs, numEng);
    vectTotSpend <<- c(vectTotSpend, totSpend);
    vectAvgSpend <<- c(vectAvgSpend, mean(spendings));
    vectTotItems <<- c(vectTotItems, totitems);
    
}

canopy::walk.customers(dfBuilder, query.all());

print('Diagnostics...');
print(totCustomers);
print(length(vectNumEnggs));
print(length(vectNumPurch));
print(length(vectTotSpend));
print(length(vectAvgSpend));
print(length(vectTotItems));

basicModel <- glm(vectTotSpend ~ vectNumEnggs + vectNumPurch + vectAvgSpend + vectTotItems);
print(basicModel)
print(summary(basicModel))

Leave a Reply

  • (will not be published)