Showing posts with label optmodel. Show all posts
Showing posts with label optmodel. Show all posts

Thursday, January 23, 2014

Optimization in SAS: Results

After spending all the time writing up code, next comes the fun part and what we really get paid for in the consulting world. I'm going to walk through three pieces of the results having hit "run". The three pieces are:
  1. The Log: This contains information behind the compilation of the code, including errors and high level results.
  2. The Results Window (Tab if you are in SAS EG): Contains the default results of having written a basic PROC OPTMODEL.
  3. Graphing the results: Some bonus code at the end to make some sense 
First up, the log produced from the program. SAS uses the log in order to print out the model description and the high level results. I'll skip the boring parts of the log where it reprints the code and get right to the important part. This set of "notes" in SAS describes what was created as the optimization formulation. It will also give the stats around "presolving" the problem and the solution status. SAS "presolves" the optimization problem by removing extraneous information like variables and non-binding constraints.

NOTE: The problem has 3000 variables (0 free, 0 fixed).
NOTE: The problem has 3000 binary and 0 integer variables.
NOTE: The problem has 4004 linear constraints (4004 LE, 0 EQ, 0 GE, 0 range).
NOTE: The problem has 12000 linear constraint coefficients.
NOTE: The problem has 0 nonlinear constraints (0 LE, 0 EQ, 0 GE, 0 range).
NOTE: The OPTMODEL presolver removed 0 variables, 3003 linear constraints, and 0 nonlinear constraints.
NOTE: The OPTMODEL presolved problem has 3000 variables, 1001 linear constraints, and 0 nonlinear constraints.
NOTE: The OPTMODEL presolver removed 8000 linear constraint coefficients, leaving 4000.
NOTE: The OPTMILP presolver value AUTOMATIC is applied.
NOTE: The OPTMILP presolver removed 0 variables and 0 constraints.
NOTE: The OPTMILP presolver removed 0 constraint coefficients.
NOTE: The OPTMILP presolver modified 0 constraint coefficients.
NOTE: The presolved problem has 3000 variables, 1001 constraints, and 4000 constraint coefficients.
NOTE: The MIXED INTEGER LINEAR solver is called.
          Node  Active    Sols    BestInteger      BestBound      Gap    Time
             0       1       2  41528.0754238  41528.0754238    0.00%       1
             0       0       2  41528.0754238              .    0.00%       1
NOTE: Optimal.
NOTE: Objective = 41528.0754.

Hooray, the model not only solved, but it found an optimal solution. Next part is to check the results of the program. This is where SAS will put all printouts from the procedures used in the program. There are three sections to this problem in the results section. The first one is the test print we had to verify that our data was read in to the model correctly.


The next part shows the model summary. You'll noticed that this looks like the output in the log, but forced into a table format. I don't particularly use this table very often other than to verify the size of the table. It can be helpful to note the size of the table in reference to the run-time for the problem.

problem summary

The last piece shows the solution summary. This gives you some of the relevant information you need to evaluate your model.

Solution Summary


The last step for me is taking a stab at visualizing the results produced by the optimization model. Since this optimization problem is relatively simple, I want to color code who was mailed and who wasn't for each of the products. Since my objective function is the product of Profit and the Likelihood To Apply, I use each as an axis inside of the chart. Below is the simple macro I use to build the chart for each product. First I use SQL to generate a dynamic header for the chart with the total expected profit for that product. I then use SGPLOT to draw the scatter plot. 

proc format;
    value mail
        1="Mail"
        0="No Mail"
    ;
run;

%macro graph_results(product);
goptions device=svg;
ods graphics on / antialiasmax=10000;
proc sql noprint;
    select sum(e_profit*lta) format=dollar12. 
        into :profit 
        from results 
        where mail=1
        and product = "&product"
    ;
quit;

proc sgplot data=results;
    title1 "Optimization Results for &product.";
    title2 "Total Expected Profit = &profit.";
    where product = "&product";
    format mail mail.;
    scatter x=e_profit y=lta / 
        group=mail 
        markerattrs=(size=5 symbol=circlefilled)
        transparency=0.7
        name="scatter"
    ;
    keylegend "scatter" / across=1 position=topleft noborder location=inside ;
    xaxis label="Expected Profit" values=(0 to 100 by 20) display=(noticks);
    yaxis label="Likelihood to Apply" values=(0 to 1 by .1) display=(noticks);
run;
title;
ods graphics off;
goptions reset=all;
%mend;

%graph_results(TRAVEL);




Note that it isn't the greatest picture, but it gives you an idea of the solution. I hope to give the same visualization a shot in Tableau to demonstrate that without coding up a chart, you can still get a nice visualization.

Sunday, December 8, 2013

Optimization in SAS: Proc OPTMODEL

Now that the data has been prepped, it's time to build the optimization model. Let's take a step back an formulate the problem first. Every constraint based optimization problem is divided into three parts: the objective function, the decision variables, and the constraints. 

Remember that the problem is to identify the best promotion available for each person. The decision variable is binary, whether a person will receive a specific promotion or not. In this example, a specific promotion is identified by a combination of credit card type and APR.

The objective we will maximize over will be our idea of profit. Profit will be made up of two pieces of information that are typically modeled:

  • Expected profit is defined as the profit (over a period of time) that can be earned from the customer if they open up a specific credit card. 
  • Likelihood that a customer will apply for a particular credit card if they receive a promotion from us.

The resulting objective function becomes the sum of all expected profit against the likelihood they apply for that account, if we choose to mail them a promotion for that account.

For this first example, we will keep our list of constraints short and simple. Here's the list of constraints we will implement in this first iteration:

  1. Limit the number of promotions that each customer can receive per campaign.
  2. Each credit card that is mailed to a customer needs to have only one price.
  3. Limit the number of total promotions mailed per card type and price point. 
Now that we have the formulation out of the way, let's code! I will walk you through my recommendations behind using OPTMODEL. I've found this style is the easiest to explain to colleagues and follow. 

The first step in using OPTMODEL is to define the list of "iterators" for which the optimization model will use. An iterator is a list of items that can be used to iterate through when defining constraints or reading in data. Although not necessary, it certainly helps keep your code short and easy to review. For this problem, we will define three iterators:

  1. Customers: the list of customers to analyze inside of this campaign
  2. Products: the list of credit card types to be promoted
  3. Prices: the list of various price points for each of the credit card types
proc optmodel;
    set <str> customers;
    set <str> products;
    set <str> prices;

The next step will be defining all of the data that will be used inside of the optimization model. Here are the variables we will reading in:
  1. Expected_profit: defined as the expected profit earned on a credit card at that price for a particular customer
  2. Likelihood_to_apply: defined as the likelihood that a customer will apply for a particular credit card at a that price
  3. Product_volume: defined as the number of promotions that can be sent for each credit card
  4. Price_volume: defined as the number of promotions that can be sent for each price 
  5. NUM_PRODUCTS_PER_CUSTOMER: a constant that defines the number of credit card promotions that can be sent to a person.
    number expected_profit {customers, products, prices};
    number likelihood_to_apply {customers, products, prices};
    number product_volume {products};
    number price_volume {prices};

    number NUM_PRODUCTS_PER_CUSTOMER = 1;

The next step is to populate those variables with actual data. Given the data we produced back my last post, we will use the "read data" phrase to get data into our optimization model. Since we have four datasets, we will use four different "read data" phrases. A "read data" phrase can be constructed as follows:

    read data datasetname into iterator=[columnname] product_volume=col("columnname");

We will start with the product_data dataset. Since this dataset is unique at the product level, we can use it to set values for the products iterator we defined above. Note that the only variable that is defined at the product level is product_volume.

    read data product_data into products=[product] product_volume=col("volume");

The next dataset is read in will be data related to the prices. Note that the only variable that is defined at the price level is price_volume.

    read data price_data into prices=[price] price_volume=col("volume");

Note we don't have any customer data used in the model, but we will still need a way to identify each customer. 

    read data customer_data into customers=[customer_id];

Last but not least, we need to read in the two model scores. Since this dataset is unique at the combination of customer, product and price we put all three indices in the brackets. Note that since all three iterators were defined, we don't need to list which one is mapped to which but order the variables as they were defined.

    read data model_scores into [customer_id product price] likelihood_to_apply expected_profit;

As with any model, I like to verify that the data is correct and read in properly. The following print statement will print out the two variables for the first customer (with ID='1').

    print {c in customers,p in products,q in prices: c='1'} likelihood_to_apply
          {c in customers,p in products,q in prices: c='1'} expected_profit
    ;

Now that the data has been read it, let's define the model. First up, our decision variable. Note we need to make a decision on whether to mail each person which product at what price. 

    var mail {customers, products, prices} binary;

Next is to define the objective function, profit. I will define profit as the sum of expected profit times to likelihood to apply times whether they get a promotion for all customers, credit cards, and prices.

    max profit = sum{c in customers, p in products, q in prices} 
        likelihood_to_apply[c,p,q]*expected_profit[c,p,q]*mail[c,p,q];

Next I will define each of the constraints mentioned above. The first constraint limits the number of promotions a customer can receive. The second one limits the number of pricing points per credit card. The third and fourth constraints limit the number of promotions that can be mailed per credit card and price respectively.

    constraint PRODUCT_PER_CUST{c in customers}:
        sum{p in products, q in prices} mail[c,p,q] <= NUM_PRODUCTS_PER_CUSTOMER;

    constraint PRICE_PER_PROD{c in customers,p in products}:
        sum{q in prices} mail[c,p,q] <= 1;

    constraint CONS_price_volume{q in prices}:
        sum{c in customers,p in products} mail[c,p,q] <= price_volume[q];

    constraint CONS_product_volume{p in products}:
        sum{c in customers,q in prices} mail[c,p,q] <= product_volume[p];

Now the easy part, solve the problem. There are multiple options involved with the solver inside of SAS but I will start out simply and identify the solver for Integer Programming problems.

    solve with milp;

Given the nature of solvers, I will clean up the solution to eliminate any potential rounding errors.

    for {c in customers, p in products, q in prices} mail[c,p,q] = round(mail[c,p,q],1E-4);

I will also create a dataset with the results of the optimization problem. This "create data" statement will create a dataset with three ID columns: customer_id, product, and price. I will then append in three data columns: lta, e_profit and mail.

    create data results from
        [customer_id product price] = {c in customers, p in products, q in prices}
        lta = likelihood_to_apply[c,p,q]
        e_profit = expected_profit[c,p,q]
        mail = mail[c,p,q]
    ;
quit;

Well that was pretty long, but it will provide as the basis for future enhancements and explorations into the problem. You can find the full listing of code here. My next post will explore the log and the results of this program.

Monday, December 2, 2013

SAS and Optimization

Like most people, I would prefer to use other optimization software out there than SAS. However, it is possible to decrease friction in your analytics workflow by keeping everything inside of SAS. Typical modeling processes involve using SAS's procedures to train and score predictive models. These scores can then be used as the input into a optimization model to help with the decision process.

SAS has a great product, SAS Marketing Optimization, for doing optimization in the marketing industry. Through work in that product, I have found that it lacks flexibility to incorporate various strategies that are commonly found in campaign planning. This series of blog posts will introduce the SAS procedure OPTMODEL. This procedure allows you to define an optimization problem and the solver in which to solve it.