SAS Viya Copilot for Code Assistance in SAS Data and AI Studio
Recent Library Articles
In this post, we’ll take a look at how SAS Viya Copilot for Code Assistance can help with some of those everyday tasks: understanding code, improving it, and making changes more confidently—all without leaving the SAS Data and AI Studio environment.
Already a SAS Viya user? Then you know you’ve got a wealth of capabilities at your fingertips. We’ll explore those together, giving you access to all the insights you’ll need. Join us on December 10 at 11 a.m. ET.
Season 3 of my HIMYM - How I made Your Model with SAS Viya Series introduces how you can create Machine Learning models using STEPS in SAS Data and AI Studio. As main actors you will meet the following STEPS: Partition, Imputation, Binning, Variable Selection, Gradient Boosting, Forest, Logistic Regression and Assess.
The flow in SAS Data and AI Studio follows the analytic lifecycle.
You can download the data and the flow from my GITHUB repository.
Usage Note and Prerequisites
The flows assumes that you have the BIGORGANICS data ready in the CASUSER library. If you do not have them ready yet, select from swimlane "Load Data (Optional)"
"Load BIGORGANICS Data" (Note that this might run 1-2 minutes) or
Only if you have library TUNDATA available: Alternative: "Copy from CASLIB TUNDATA (if available)"
to create this dataset.
Note that sometimes I have the problem that I cannot run the the entire "Season 03" flow without getting errors. I need then to run it node by node.
Business Background
A retail marketing use case and the BIGORGANICS data are used as the underlying business case study. Imagine you work for a supermarket chain that sells organic products. Every customer has a loyalty card, and for each card you know a handful of things: age, a gender flag, an affluence grade, the neighborhood, the loyalty status (Tin, Silver, Gold, Platinum), the total amount spent and how long the card has existed. You also know whether the customer has ever bought organic products (TARGETBUY = 1) or not (TARGETBUY = 0).
The marketing department has a question: which customers should receive the organic-products coupon? Mailing everybody is expensive. A model that finds the likely buyers lets you contact fewer people and still reach most of the buyers.
1. Partition and Sample the Data
You can use the PARTITION step to partition and sample the data. Here a _PARTIND_ variable is used to partition data as 60% training, 30% validation and 10% test.
2. Impute Missing Values
The IMPUTATION steps allows to impute interval and categorical variables.
3. Perform Variable BINNING
The BINNING steps allows to BIN variables in multiple ways. The output of binning the AGE variable (IM_DEMAGE) is shown below.
4. Variable Selection
Step VARIABLE SELECTION reviews the candidate predictors which are available in the data or have been generated by other nodes.
It selects a subset of variables for further usage.
and displays the results graphically.
4. Predictive Modeling and Assessment
Note that the new variables generated in the IMPUTATION and BINNING steps are used for the analysis in the FOREST or GRADIENT BOOSTING node.
Note that all predictive modeling STEPS allow to derive the predicted values from the respective model. e.g variable P_TARGETBUY1
4.1 Random Forest
The random forest selects the following variables:
For model interpretability it shows the partial dependence for BIN_IM_DEMAGE
as well as the ICE Plot
the corresponding ASSESS Steps shows graphs for LIFT, ROC, Cumulative Lift and Captured Response
4.2 Gradient Boosting
you see which variables are selected by the GRADIENT BOOSTING step
And the partial dependence for BIN_IM_DEMAFFL is shown.
Model Assessment
Again the ASSESS node shows the results in tabular and graphical form.
4.3 Logistic Regression
You see the parameters from the logistic regression model.
Related Episodes of HIMYM - How I made your model using SAS Viya
You might want to take a look at HIMYM Season 0 - "The Prequel" for insights how the data have been derived from different sources and have been used to create the analytic base table.
Business Background (#0) for assembling the BIGORGANICS Dataset from different Source Tables
The PROC SQL approach (#1) to assemble BIGORGANICS analytic base table
The SAS datastep approach to assemble (#2) to assemble the BIGORGANICS analytic base table
The STEPS in SAS Data and AI Studio Approach (#3) to assemble the BIGORGANICS analytic base table
Reverse Engineering the relational example data from the original BIGORGANICS table (#4)
If you would like to see how such models can be built without coding in SAS Visual Analytics navigate to Season 1 - The NoCode/LowCode experience or a here for the full list of videos in Season 1.
Season 2 explains how you can built machine learning models with SAS Procedures.
More of my articles and links can be found in my header article Data Science and Data Preparation Article Overview by Gerhard.
... View more
Season 2 of my HIMYM - How I made Your Model with SAS Viya Series introduces how you can create Machine Learning models using SAS Procedures. As main actors you will meet the following SAS Procedures and CAS Actions: PARTITION, MDSUMMARY, VARIMPUTE, BINNING, DATASCOENCEPILOT, TREESPLIT, LOGSELECT, FOREST, GRADBOOST, SUPERLEARNER, NNET, LOGISTIC, MI, MIANALYSE, ASSESS. You can run the presented programs in SAS Data and AI Studio, SAS Enterprise Guide and also SAS Notebooks in Visual Studio Code.
Season 2 is aligned with the analytic lifecycle.
S02E01: Preparing, Sampling, Partitioning and Exploring your analysis data
S02E02: Modifying the data, Feature Engineering, Data Quality Checking
S02E03: Modeling the Data with various Machine Learning Techniques
S02E04: Assessing the Models and Scoring of the Models
Review of S02E01 (Sample, Partition, Explore)
In S02E01: Preparing, Sampling, Partitioning and Exploring your analysis data we met the supermarket chain that wants to send an organic-products coupon to the customers most likely to buy. We checked the data, found that every customer was in the table five times, removed the copies, split the data into training, validation and test data, and explored it, in particular against the target TARGETBUY.
The exploration left us with a to-do list:
Finding in Part Episode 1
What we do about it
Age (7%), affluence (5%) and gender (11%) have missing values, and "age is missing" might be informative
flag them, then impute them
PROMSPEND is extremely skewed (maximum 296,000, typical value 2,000)
transform it
Buying drops in a non-linear way with age; age and affluence both matter
build ratios, interactions and groups
DEMCLUSTER has 55 levels
let the models deal with it, or compress it
Nine inputs, many of them weak
select the ones worth modeling
This article is about feature engineering and data quality improvement that help the models. It is often the step with the biggest effect on model quality, much more than the choice of the algorithm.
You will two ways to create features:
by hand, with the knowledge we gained in Part 1,
and with the automatic feature machine of dataSciencePilot.
We also use clustering to create customer segments. At the end we select the variables for Part 3.
1. Dealing with Missing Values
1.1 Missing = YES - Keep this information
Before we fill the gaps, a thought: the fact that a value is missing can itself be a signal. A customer who does not tell you their gender or age may behave differently from one who does. If we simply replace the missing value by a typical one, that information is gone. So we first record it in flags.
data casuser.org_m;
set casuser.org_part;
m_demaffl = missing(demaffl);
m_demage = missing(demage);
m_promtime = missing(promtime); /* PROMSPEND has no missing values */
m_demgender = missing(demgender);
run;
This is an ordinary DATA step, but it runs in CAS: because the input and output are CAS tables, SAS processes the table in parallel in multiple threads. The MISSING() function returns 1 or 0. We create flags only for variables that actually have missing values (PROMSPEND has none).
You see that the M_ are 1 if the corresponding variable has a missing value and are 0 otherwise.
1.2 Impute the missing values
PROC VARIMPUTE replaces missing values.
For interval variables we use the median (CTECH=MEDIAN),
for categorical variables the most frequent value (NTECH=MODE😞
proc varimpute data=casuser.org_m;
input demaffl demage promspend promtime / ctech=median;
input demcluster demgender demreg promclass demtvreg / ntech=mode;
output out=casuser.org_imp copyvars=(_all_);
run;
The procedure creates new variables with the prefix IM_: IM_DemAge, IM_DemAffl, IM_DemGender and so on. The original variables stay untouched, which is good practice, because you can always compare. The procedure prints what it did:
Recommended Improvements
1. Learn the Imputation values on the training partition only
A word of caution. Here we calculate the medians on the whole table, to keep the program short. In a production project you should learn the imputation values on the training partition only and apply them unchanged to the validation, test and new data. Otherwise a little information flows from the evaluation data into the model. The same applies to every transformation that "learns" something from the data. Later in this article you will see how analytic stores solve this problem for the clustering and for the feature machine.
2. Learn the most appropriate imputation value from other variables
Here we are using the same imputation value for all customers. You can also derive a meaningful imputation value for each record by creating a predictive model (e.g. a decision tree) on the records with known values. Then you use this model derive an individual imputation value for the records with missing values. A similar idea (for a different purpose) is presented in my article Using the GLMSELECT procedure to calculate individual reference values in outlier detection
Median and mode imputation is simple and robust. A more rigorous alternative is multiple imputation, which we use in S02E03 to show how much the missing values influence a regression.
2. Feature Engineering
2.1 Manually Coding the new features.
Now we use what we learned about the target. All new variables are created in one CAS DATA step:
data casuser.org_mod;
length age_grp $8; /* long enough for "2: 30-49" */
set casuser.org_imp;
log_promspend = log(1 + im_promspend); /* skewed -> log */
affl_per_age = im_demaffl / max(im_demage, 1); /* ratio */
spend_x_time = im_promspend * im_promtime; /* interaction */
if im_demage < 30 then age_grp = "1: <30";
else if im_demage < 50 then age_grp = "2: 30-49";
else if im_demage < 65 then age_grp = "3: 50-64";
else age_grp = "4: 65+";
run;
Note the LENGTH age_grp $8; statement. Without it, SAS would take the length of the first assigned value ("1: <30", 6 characters) and cut "2: 30-49". A classic.
Rationale
log_promspend
PROMSPEND is extremely skewed. The logarithm compresses the long tail, which helps regressions and neural networks in particular. The 1 + keeps the logarithm defined for zero.
affl_per_age
Buyers are younger and more affluent. The ratio "affluence per year of age" describes both at once.
spend_x_time
An interaction: spending may matter more for customers with a long card history.
age_grp
Buying drops in a non-linear way with age (Part 1: 57% buy below 41, 14% above 66). Age groups let even a linear model capture steps.
In the SAS dataset you see imputed AGE values and derived variables.
2.2 Binning with PROC BINNING
PROC BINNING can also create bin variables for you. Here we cut the imputed spend into five quantile bins and print the boundaries:
proc binning data=casuser.org_mod numbin=5 method=quantile;
input im_promspend;
output out=casuser.org_binned copyvars=(_all_);
run;
The bin boundaries are 0.01, 970, 3,000 and 6,053; the result is a new variable BIN_IM_PromSpend. We write it to a separate table,
because the models in S02E03 will use LOG_PROMSPEND instead.
2.3 Defining Customer segments with clustering
The features so far use our domain knowledge. Clustering finds structure we did not think of. We group the customers by age, affluence, tenure and (log) spend, without letting the clustering see the target. Then we use the cluster as a categorical input for the models.
Defining the Clusters
proc kclus data=casuser.org_mod(where=(_partind_=0)) standardize=std
maxclusters=5 seed=12345;
input im_demage im_demaffl im_promtime log_promspend / level=interval;
savestate rstore=casuser.clus_store;
run;
Observe the following from the code.
WHERE=(_PARTIND_=0): the clusters are learned on the training rows only.
STANDARDIZE=STD: distances between customers are calculated in all four dimensions. Without standardization, the variable with the largest numbers (age, or tenure) would dominate the cluster assignments.
SAVESTATE: the clustering model is stored as an analytic store, a compact binary object that contains everything needed to apply the model later using PROC ASTORE.
You receive 5 clusters with different group size
You also see a profile of the variables per cluster (note that the standardized values are shown):
Applying the Cluster logic to all observations
PROC ASTORE can now be used to assign the "learned" cluster assignment all observations in all partitions:
proc astore;
score data=casuser.org_mod rstore=casuser.clus_store out=casuser.org_seg
copyvars=(_all_);
run;
This is the clean way to apply a "learned" transformation: learn on the training rows, store the model, apply it everywhere. It will also score new customers one day, with no re-clustering.
A short DATA step turns the cluster number into a categorical variable called segment and removes the technical columns:
data casuser.org_mod;
length segment $2;
set casuser.org_seg;
segment = cats('S', _cluster_id_);
drop _cluster_id_ _distance_ _standardized_distance_;
run;
Profiling the clusters
Did the clustering find anything useful? We never showed it the target, so a cross-table with the target is a fair test:
proc freqtab data=casuser.org_mod(where=(_partind_=0));
tables segment*targetbuy / nocol nopercent;
run;
You can assign business descriptions to each segment:
Segment
What characterizes it
Customers
Buy rate
S5
clearly high affluence
1,602
59%
S1
very low spenders
3,551
25%
S4
younger, below-average affluence
3,594
23%
S2
older
3,630
14%
S3
long loyalty tenure
945
14%
Segment S5 buys at more than twice the average rate, and the two groups S2 and S3 at little more than half of it. The clustering found customer types that matter for the target without ever seeing it.
In predictive modeling you can use the SEGMENT variable in two ways
as categorical input variable
as group variable to create individual models per SEGMENT
2.4 Automated Feature Engineering (Feature Machine)
Creating features by hand needs ideas and time. The featureMachine action of dataSciencePilot automates a standard set of them: it explores the inputs, screens them, and applies transformations such as missing-value indicators, imputation, label encoding or skewness corrections, depending on what it finds. As in S02E01, there is no procedure for it, so we use PROC CAS:
proc cas;
dataSciencePilot.featureMachine /
table = {name="org_part", where="_partind_=0"},
inputs = {"DemAffl","DemAge","PromSpend","PromTime","DemCluster",
"DemGender","DemReg","DemTVReg","PromClass"},
target = "targetbuy", event = "1",
transformationOut = {name="fm_transformations", replace=true},
featureOut = {name="fm_features", replace=true},
saveState = {name="fm_state", replace=true},
casOut = {name="fm_train", replace=true},
copyVars = {"targetbuy","_partind_"};
quit;
The action works on the raw inputs and on the training rows. It saves four things:
the list of transformations
the list of features
the new training table
and, most important, the whole recipe as an analytic store (saveState).
The list of features shows what it decided:
proc print data=casuser.fm_features noobs;
var name label;
run;
Explanation
Feature
What the machine did
miss_ind_DemAge, miss_ind_DemGender
added a missing indicator, because the missing rate is significant
cpy_nom_miss_lev_lab_DemAge
treated age as a category with its own level for "missing"
cpy_nom_miss_lev_lab_DemGender, ..._DemReg, ..._DemTVReg, ..._DemCluster
the same for the categorical variables
cpy_nom_mode_imp_lab_PromClass
mode imputation plus label encoding
cpy_int_med_imp_PromSpend
median imputation of the interval variable
Interesting: the machine arrived at some of the same ideas as we did (missing indicators), but not at others (no ratio, no log, no segments), and it treats age and affluence, which have few distinct values, as categories. That is flexible, but it can invite overfitting, as we will see in S02E04.
Because the recipe is an analytic store, we can apply it to all partitions with PROC ASTORE, again without re-learning anything:
proc astore;
score data=casuser.org_part rstore=casuser.fm_state out=casuser.org_fm
copyvars=(targetbuy _partind_);
run;
In E02S03 we will build a model on these automatic features and compare it with our hand-made ones. A fair duel.
3. Feature Selection
3.1 Define variable lists
We now have the original inputs, imputed versions, flags, ratios, groups and segments. Many are correlated; some are weak. Fewer variables mean simpler, faster and more stable models. We collect the candidates in two macro variables:
%let int_all = im_demaffl im_demage im_promspend im_promtime
log_promspend affl_per_age spend_x_time;
%let cls_all = im_demcluster im_demgender im_demreg im_promclass im_demtvreg
age_grp segment m_demaffl m_demage m_promtime m_demgender;
Note that you can (semi)automate this step by using the SELECT <variable> INTO <macrovariable> statement in PROC SQL. A code example is shown below with the output of the LOGSELECT procedures.
3.2 Using PROC VARREDUCE
PROC VARREDUCE with REDUCE SUPERVISED picks, step by step, the inputs that explain the target best:
proc varreduce data=casuser.org_mod(where=(_partind_=0));
class &cls_all;
reduce supervised targetbuy = &int_all &cls_all / maxeffects=12;
ods output SelectedEffects = work.SelectedEffects;
run;
You see that 28 candidate parameters have been investigated and the (cumulative) proportion of variance explained is shown.
It then selects 12 effects, in this order of importance:
Also note that in the code ODS OUTPUT is used to save the SelectedEffects in table WORK.SELECTEDEFFECTS. It will be used below to create the variable lists.
Four of the top five are variables we created (the ratio, the "gender is missing" flag, the age group and the "age is missing" flag), and the missing-value flags, which cost one line each, are in the list. The original PROMSPEND is not in the list (its log is, but late).
You see that the effort of feature engineering is paying off, as we are now able to provide a set of candidate predictor.
3.3 LASSO regression with PROC LOGSELECT
A second opinion comes from a logistic regression with a LASSO penalty. The LASSO shrinks the coefficients of unimportant effects to exactly zero; we choose the penalty by the performance on the validation data:
proc logselect data=casuser.org_mod;
class &cls_all;
model targetbuy(event='1') = &int_all &cls_all;
selection method=lasso(choose=validate);
partition rolevar=_partind_(train='0' validate='1');
run;
PARTITION ROLEVAR=_partind_(train='0' validate='1') tells the procedure how to use our partition column.
The LASSO selection is a little bit stricter: it keeps only 9 variables, which are shown here in the table with parameters for each level.
3.4 Create Selection-Lists for further Usage.
We are going to stores the results of the VARREDUCE procedure in macro variables and use it in the next episode, because ensemble models can use many variables, and the LASSO result is a good baseline in itself.
The selection is stored in two macro variables: &SEL_INT and &SEL_CLS.
proc sql noprint;
select variable into :sel_cls separated by " "
from work.SelectedEffects where type = "CLASS";
select variable into :sel_int separated " "
from work.SelectedEffects where type = "INTERVAL";
quit;
%put &=sel_int;
%put &=sel_cls;
In the code you use WORK.SELECTEDEFFECTS that was stored in PROC VARREDUCE.
You can use the SQL procedure to fill values and value lists into macro variables using the INTO option.
In the SAS Log you see:
SEL_INT=affl_per_age IM_DemAge
SEL_CLS=IM_DemGender m_demgender segment age_grp m_demage m_demaffl IM_DemReg m_promtime IM_DemCluster IM_DemTVReg
Summary
You now have the following tables that are used in future episodes.
Table
Content
Used for
casuser.org_mod
imputed variables, flags, hand-made features, segment, partition
models in S02E03
casuser.org_fm
the 11 automatic features, all partitions
the feature-machine model in S02E03
casuser.clus_store, casuser.fm_state
analytic stores of the learned transformations
scoring new data in Part S02E04
The data quality problems from Part 1 are handled: missing values are flagged and imputed, the skewed variable has a log version, non-linear effects can be captured by groups, ratios and segments, and we have a short list of variables.
In S02E03 we model: a decision tree, regression, gradient boosting (also with automatic hyperparameter tuning), a random forest, a neural network, a model on the feature-machine variables, and a Super Learner that combines them. We also use PROC LOGISTIC with ROC curves and multiple imputation with PROC MI and PROC MIANALYZE.
More of my articles and links can be found in my header article Data Science and Data Preparation Article Overview by Gerhard.
... View more
As someone who still happily uses Display Manager, I like that I can configure it to automatically open ODS results using an external application (PowerPoint, Word, Adobe reader, whatever).
Is there a feature like that in VS Code extension / VS Code? I'm running VS Code locally, and connecting to local SAS 9.
AI suggests I use an X statement to open a file, which sounds like a reasonable approach. But curious if a human knows a way to configure the output files to open automatically in an external application.
Particularly interested in getting ODS PowerPoint to automatically pop open, at the moment.
... View more
Animate a SAS series plot with a date loop and the GIF printer driver
In my article Data-Driven Line Colors in PROC SGPLOT with a DATA ATTRIBUTE MAP I asked what the September 1 water level at Lake Neusiedl might be if, starting on May 9, 2022, it followed the same pattern of change as in a historical year.
That gives us one chart. What if we ask the same question on May 10? Or on June 1?
This article explains how you can use the SAS animated GIF printer driver to create animated charts using the SPLOT procedure.
s the cutoff moves from May 9 to August 31, 2022, the observed line grows and the September 1 scenarios are recalculated and recolored
This animation doesn’t simply reveal more points on fixed lines. Each frame recalculates the scenarios. A later cutoff gives us a new observed starting level and a shorter stretch of each historical season to replay. September 1 stays the comparison date, but the result for that date can change enough to move a line into another color category.
The data and programs for this example can be download from my Git Respository here. There you find the programs that generate this graph (GRPH_AnimWaterLevelPlot.sas) as well as the underlying data (CreateData_DailyWaterLevel.sas).
This article explains the necessary steps for the animated GIF printer driver and the %DO LOOP. For the individual graphs itself, it uses program GRPH_DataDrivenLineColors.sas, which is explained in article Data-Driven Line Colors in PROC SGPLOT with a DATA ATTRIBUTE MAP.
Introduction and Business Background
Static charts are often sufficient for reporting. However, some analytical processes are inherently dynamic. Forecasts evolve, uncertainty changes, simulations converge, and new observations continuously reshape our understanding of possible future outcomes.
In those situations, animation can reveal patterns that are difficult to spot in a sequence of static charts.
SAS provides built-in support for animated GIF generation through the ODS Animated GIF driver. By combining ODS Graphics, PROC SGPLOT and a simple macro loop, it is possible to create highly informative animated visualisations directly in SAS.
This article demonstrates the technique using a water-level scenario model for Lake Neusiedl that recalculates future scenarios every day and assembles the resulting charts into a single animated GIF. The overall approach is based on the example presented in my webinar on animated SAS graphics
Why Animated Graphics?
Animation is particularly valuable when change itself contains information.
Examples include:
Forecast updates
Climate scenarios
Monte Carlo simulations
Demand forecasting
Process monitoring
Hydrological modelling
Risk assessment
Movement can often communicate evolving situations more effectively than a collection of static graphics.
Step 0 - Prework: Provide the program that generates an individual graph
This program can be found in "GRPH_DataDrivenLineColors.sas" explained in article Data-Driven Line Colors in PROC SGPLOT with a DATA ATTRIBUTE MAP. Open this program and use the code at steps 1-5. Do not use the code shown at steps 0, as this specifies CUTDATE for a single date only.
Either copy this program it inside the macro loop of Step 3 of the program "GRPH_AnimWaterLevelPlot.sas" which is described here in this article
or create a macro %macro DataDrivenLineGraph; and copy it between there and end it with a %mend; statement
Step 1 - Define the Animation Macro
%macro Water_Level_Anim(from,till,anim_duration=0.5);
from and till are the first and last cutoff dates, both included.
anim_duration is the time each frame stays on screen, in seconds. The macro defaults to half a second.
Step 2: Open a GIF destination and start the animated GIF driver
/***********************************************************************************
*** Step 2 - Set Init Options
**********************************************************************************/
options papersize=('28 cm', '20 cm') printerpath=gif animation=start
animduration=&anim_duration. animloop=yes noanimoverlay;
%let path = /export/viya/homes/gerhard/SAS_Files;
ods printer file="&path/WaterLevel_LinePlot.gif";
ods graphics /height=20cm width=28cm imagefmt=GIF;;
PRINTERPATH=GIF picks the GIF printer driver, and
ANIMATION=START tells it to start an animation sequence.
ANIMDURATION= controls the delay per frame.
ANIMLOOP=YES repeats playback of the finished GIF; that’s separate from the SAS loop that generates the charts.
NOANIMOVERLAY plays the frames sequentially rather than drawing one over another.
PAPERSIZE and ODS GRAPHICS request matching dimensions: 28 cm wide and 20 cm high.
ODS PRINTER FILE= opens the output file once, before the loop. With this destination, each output page becomes a frame.
Note that setting IMAGEFMT=GIF alone doesn’t create the animated sequence.
Folder with WRITE access
You need to have write access to a library at the server where your SAS Session is running. In the folder the final .GIF file will the saved.
In my example this is the folder /export/viya/homes/gerhard/SAS_Files. If you are working from a local PC it should be easy to select such a path. If you are working at a server, ask you administrator that you need a folder in the file system.
Step 3 - Loop over days and create the GRAPH
3.1 Calculate the number of FRAMES for the animation
/***********************************************************************************
*** Step 3 - Loop over Dates and create Graphs
**********************************************************************************/
data _null_;
call symput ("AnimDays","&till."d - "&from."d); *** No need to add 1 because loop starts with 0;
run;
SAS dates are day counts, so subtracting the start date from the end date gives the number of days between them. For May 9 through August 31, AnimDays is 114 . Think of it as the last offset, not the number of frames. The first date has offset 0 ; the last has offset 114 . Since %DO includes both bounds, that gives 115 daily iterations.
3.2 Loop over the DAYS and draw each individual chart
For each of those cutoffs, %DataDrivenLineGraph looks up the new observed starting level, calculates historical changes from the new matching calendar day, rebuilds the September 1 attribute map, and draws the chart. If a scenario changes color, its September 1 result has moved into a different category. The same rules apply in every frame.
Code element "&from"d + &i advances the counter inside the %DO LOOP.
%do i = 0 %to &AnimDays;
data _null_;
call symput ("Cutdate",put("&from"d + &i,date9.));
run;
%DataDrivenLineGraph; *** To define this macro use Code code from STEP 1-5 (not Step 0!!!) from program "GRPH_DataDrivenLineColors.sas";
*** Alternatively paste the code from STEP 1-5 (not Step 0!!!) from program "GRPH_DataDrivenLineColors.sas" here.;
%end; *** Do Loop;
For each of those cutoffs, %DataDrivenLineGraph looks up the new observed starting level, calculates historical changes from the new matching calendar day, rebuilds the September 1 attribute map, and draws the chart. If a scenario changes color, its September 1 result has moved into a different category. The same rules apply in every frame.
Why use a macro loop instead of a BY statement? BY -group processing is an option when the data for each frame is already prepared. Here, moving the cutoff changes the inputs to the calculation, so I rerun the calculation and the plot together
In your individual application you would paste the code inside this macro loop. The code can contain calculations and data preparation that is needed to generate the plot data for that specific point in time.
Step 4: Stop the animation and close the output
/***********************************************************************************
*** Step 4 - Set Closing Options
**********************************************************************************/
options printerpath=gif animation=stop;
ods printer close;
%mend Water_Level_Anim;
Finally you close the GIF AnimPrinter and the GIF file is written to the destination you specified.
These closing statements belong after the loop. ANIMATION=STOP ends the animated sequence, and ODS PRINTER CLOSE closes the output file. Opening and closing the destination around the entire loop gives you one GIF containing the full sequence.
You navigate there and download the GIF file and open it in your browser. You should now see the animation of the line charts.
Run the Example
title;
options mprint;
%Water_Level_Anim(09MAY2022, 31AUG2022,anim_duration=0.25);
TITLE; clears any title left over from earlier work. OPTIONS MPRINT writes the SAS statements generated by the macros to the log, which is useful for checking that the cutoff date actually changes in the generated code.
The example sets a quarter-second delay and covers 115 dates. If each call produces exactly one page in ODS PRINTER , the GIF has 115 frames.
Usage Hint
Before generating the full season, I’d check a short range first. If the cutoff repeats, look for a Cutdate assignment inside the chart macro that overrides the loop. If the GIF alternates between different chart types, check whether the quantile plot is also reaching the printer destination. And watch the axes: Part 1 sets the y-axis limits, but its WHERE clause filters the x-axis data without fixing the displayed x-axis endpoints. A shifting scale can make the scenarios look as if they changed more than they did.
The moving cutoff tells you when the scenario was calculated. The line colors tell you which September 1 outcomes crossed a threshold. That’s what makes this more useful than simply playing a series of charts.
Practical Tips
Here are some useful lessons learned when building animated graphics.
1. Freeze the axes
Always fix axis ranges: e.g.
yaxis min=0.5 max=1.5;
otherwise the graph may jump between frames.
2. Choose a sensible frame speed
For most analytical animations animduration =0.1 - 0.5 provides good results.
3. Verify GIF viewer support
Some image viewers display only the first frame. If the animation appears static, verify that the GIF viewer supports animation.
Conclusion
Creating Animated GIFs in SAS
The Animated GIF driver works by collecting a sequence of graphics and storing them as frames within a GIF file.
The workflow is straightforward:
Start animation mode.
Generate a series of graphs.
Store each graph as a frame.
Stop animation mode.
Save the GIF.
The Heart of the Actual Solution: The Macro Loop
Most examples of the SAS Animated GIF driver focus on animating existing data. This example demonstrates something more powerful: animating a complete analytical workflow. Each frame is the result of an entirely new analytical calculation. The animation loop therefore becomes the centrepiece of the solution.
%do i = 0 %to &AnimDays;
During every iteration:
A new cut-off date is selected.
Water-level scenarios are rebuilt.
Historical years are shifted.
Risk categories are recalculated.
A new graph is generated.
The GIF therefore visualizes the evolution of the analysis itself.
As the cut-off date progresses through the year, the viewer can observe how the entire range of possible future water-level developments evolves.
Some scenarios disappear.
Others become increasingly likely.
Risk classifications change.
Uncertainty narrows.
The resulting animation communicates all of this information far more effectively than a collection of static charts.
The final result shown in the webinar demonstrates how the range of possible outcomes changes throughout the season
That ability to animate analysis, rather than just data, is where the Animated GIF driver becomes truly valuable.
References and Links
The data and programs for this example can be download from my Git Respository here.
Article The water level on Lake Neusiedl in 2022 — viewpoints of a sailor and statistician at medium.com
Connected Article: Data-Driven Line Colors in PROC SGPLOT with a DATA ATTRIBUTE MAP.
More SAS Community articles from Gerhard
Youtube: Simulation Scenarios for the Water Level at Lake Neusiedl in 2020
... View more
Season 2 of my HIMYM - How I made Your Model with SAS Viya Series introduces how you can create Machine Learning models using SAS Procedures. As main actors you will meet the following SAS Procedures and CAS Actions: PARTITION, MDSUMMARY, VARIMPUTE, BINNING, DATASCOENCEPILOT, TREESPLIT, LOGSELECT, FOREST, GRADBOOST, SUPERLEARNER, NNET, LOGISTIC, MI, MIANALYSE, ASSESS. You can run the presented programs in SAS Data and AI Studio, SAS Enterprise Guide and also SAS Notebooks in Visual Studio Code.
Season 2 is aligned with the analytic lifecycle.
S02E01: Preparing, Sampling, Partioning and Exploring your analysis data
S02E02: Modifying the data, Feature Engineering, Data Quality Checking
S02E03: Modeling the Data with various Machine Learning Techniques
S02E04: Assessing the Models and Scoring of the Models
Business Background
A retail marketing use case and the BIGORGANICS data are used as the underlying business case study. Imagine you work for a supermarket chain that sells organic products. Every customer has a loyalty card, and for each card you know a handful of things: age, a gender flag, an affluence grade, the neighborhood, the loyalty status (Tin, Silver, Gold, Platinum), the total amount spent and how long the card has existed. You also know whether the customer has ever bought organic products (TARGETBUY = 1) or not (TARGETBUY = 0).
The marketing department has a question: which customers should receive the organic-products coupon? Mailing everybody is expensive. A model that finds the likely buyers lets you contact fewer people and still reach most of the buyers.
Related Episodes of HIMYM - How I made your model using SAS Viya
You might want to take a look at HIMYM Season 0 - "The Prequel" for insights how the data have been derived from different sources and have been used to create the analytic base table.
Business Background (#0) for assembling the BIGORGANICS Dataset from different Source Tables
The PROC SQL approach (#1) to assemble BIGORGANICS analytic base table
The SAS datastep approach to assemble (#2) to assemble the BIGORGANICS analytic base table
The STEPS in SAS Data and AI Studio Approach (#3) to assemble the BIGORGANICS analytic base table
Reverse Engineering the relational example data from the original BIGORGANICS table (#4)
If you would like to see how such models can be built without coding in SAS Visual Analytics navigate to Season 1 - The NoCode/LowCode experience or a here for the full list of videos in Season 1.
Pre-Requisites
CAS-Session Name and Loading the Data
CAS procedures that are featured in this series. This means you need to be able to start a CAS session. You can create a CAS session using the command:
%let SessionName = cas1;
cas &SessionName;
In case you SAS Session is already connected to a CAS session, you can retrieve the name of your session using the command.
%put &=_SESSREF_;
Note the the FEDSQL procedures, shown later in this article requires that you specify the name of the CAS Session. Make sure that you have the session name available then.
To load the BIGORGANICS data to your session, you can run program "BORG_create_BIGORGANICS.sas" which generates the data in your WORK library. You then copy them to your CASUSER library using:
data casuser.BIGORGANICS;
set work.BIGORANICS;
run;
In case you are working at a SAS Viya for Learners environment, the BIGORGANICS data can also be found in library TUNDATA. You can copy them to the CASUSER library using.
data casuser.BIGORGANICS;
set tundata.BIGORANICS;
run;
Availability of the CAS procedures
This article features CAS procedures from SAS Visual Statistics and from SAS Viya: Machine Learning and requires that you have a license for these two products. If you only have a license for SAS Visual Statistics you cannot run the examples using the FOREST, GRADBOOST, NNET and parts of the SUPERLEARNER procedure.
1. Sampling and Partition the Data
1.1 (Optional) Check Data for Duplicates
You can check, if your data contain duplicate IDs or records with identical data values.
proc fedsql sessref=cas1;
select count(*) as n_rows, count(distinct id) as n_ids
from casuser.bigorganics;
select count(*) as n_distinct_profiles from
(select distinct DemAffl, DemAge, DemCluster, DemGender, DemReg, DemTVReg,
PromClass, PromSpend, PromTime, TargetBuy
from casuser.bigorganics) a;
quit;
The first selection reports 111,115 rows and the data and 111,115 distinct IDs. This shows that you do not have duplicate IDs in your data.
The second query reviews the values of each records and checks, if there are duplicate value combinations. Note that such query on many observations and a large number of variables might cause a long runtime. Also note that the occurrence of records with identical data values do not necessarily mean that you have duplicate records here. It might happen that in the same region, you have more than one customer with the same age, gender, total spend and campaign response.
Here the query outputs that you only have 22,204 distinct combinations of values. Which means that you roughly have 5 customers with the same values (22k out of 111k). Reviewing the data however in more detail, reveals that each value combination exactly occurs five times in the data.
data work.borg_double;
set casuser.bigorganics;
Batch = substr(id,1,1);
run;
data work.borg_first_rec_batch;
set work.borg_double;
by batch;
if first.batch;
run;
proc print data=work.borg_first_rec_batch;
run;
It looks like that the BIGORGANICS data have been artificially blown up to a larger number of observations by repeating each records 5 times and appending a A-E to the ID.
(Only) If you have enough evidence that this is the case and you have checked with those how provided you the data, it can make sense to only select one of the duplicated customer records for further analysis.
proc fedsql sessref=cas1;
create table casuser.organics {options replace=true} as
select min(id) as id, DemAffl, DemAge, DemCluster, DemClusterGroup, DemGender,
DemReg, DemTVReg, PromClass, PromSpend, PromTime, TargetBuy,
max(TargetAmt) as TargetAmt, count(*) as n_copies
from casuser.bigorganics
group by DemAffl, DemAge, DemCluster, DemClusterGroup, DemGender,
DemReg, DemTVReg, PromClass, PromSpend, PromTime, TargetBuy;
quit;
The new table casuser.organics has 22,204 rows. N_COPIES is 5 for 99.9% of them (and 10 for 19 profiles). The event rate is 24.8%: one customer in four buys organic products.
A note on "big": We lose the "big" in BIGORGANICS, but we lose no information: in this case the extra rows were pure copies. In a real project with real big data, you would take the same care, only that the duplicates would hide in joins, repeated extractions or customer-level versus transaction-level data.
1.2 Partition into training, validation and test data
A model that is evaluated on the data it was trained on always looks good. To avoid overfitting you split the data into three parts:
_PartInd_
Role
Share
Rows
Purpose
0
Training
60%
13,322
fit the models
1
Validation
30%
6,661
tune and select models, prune trees, stop boosting
2
Test
10%
2,221
the final, untouched check; later also our "new customers"
Note that this assignment of codes to roles differs from some suggestions in the SAS Documentation. The authors opinion is that it is more intuitive to have a ordered list 0-2 of the data partitions train, validation and test.
You use the following code:
proc partition data=casuser.organics partind samppct=30 samppct1=30 seed=12345;
by targetbuy;
output out=casuser.org_part copyvars=(_all_);
run;
PARTIND adds a column _PartInd_ with the codes 0 (training), 1 (validation) and 2 (test).
SAMPPCT=30 SAMPPCT2=10 request 30% validation and 10% test data. The rest is assigned to code 0 = Train Data.
BY targetbuy makes the split stratified: each of the two target classes is split on its own. This is important when the event is rare, because a random split could leave you with too few events in the test data.
SEED= fixes the random sampling and makes the split reproducible.
You check that the stratification worked:
proc freqtab data=casuser.org_part;
tables _partind_*targetbuy / nocol nopercent;
run;
Every partition has the same share of buyers.
A small sample for plotting
Sometimes you want a small table, for example for graphs or for tools that run only on the compute server. PROC PARTITION can draw such a sample, too. SAMPPCT defines a 5% sample.
If you leave out PARTIND, it writes only the sampled rows. With the BY statement the sample is stratified again:
proc partition data=casuser.org_part samppct=5 seed=4711;
by targetbuy;
output out=casuser.org_sample copyvars=(_all_);
run;
2. Explore the Data
We explore the training data only (where=(_partind_=0)). If you base decisions for data preparation from exploring the validation or test data, information from those partitions would leak into your modeling choices.
And we define macro variables for the list of input variables:
/* Original input variables */
%let int_raw = DEMAFFL DEMAGE PROMSPEND PROMTIME;
%let cls_raw = DEMCLUSTER DEMGENDER DEMREG PROMCLASS DEMTVREG;
2.1 Interval variables
proc mdsummary data=casuser.org_part(where=(_partind_=0));
var &int_raw;
output out=casuser.summary_int;
run; proc print data=casuser.summary_int noobs; run;
PROC MDSUMMARY computes the usual statistics (N, number of missing values, mean, standard deviation, minimum, maximum, skewness, kurtosis and more) in parallel, also for very large tables. We learn that DEMAGE and DEMAFFL have around 5% to 7% missing values, and that PROMSPEND has none but is extremely skewed: maximum about 296,000, typical values around 2,000 (skewness above 8).
3.2 Missing values and cardinality
proc cardinality data=casuser.org_part(where=(_partind_=0)) outcard=casuser.card maxlevels=254;
var &int_raw &cls_raw targetbuy;
run;
proc print data=casuser.card noobs;
var _varname_ _more_ _nobs_ _nmiss_ _cardinality_;
run;
PROC CARDINALITY reports, for every variable, the number of distinct levels and the number of missing values. It tells us that DEMGENDER is missing for about 11% of the customers, and that DEMCLUSTER has 55 levels, which is a lot for a categorical variable.
Make sure that you specify the MAXLEVELS option is set to a sufficiently high number (maximum is 254). Otherwise the _CARDINALITY_ value might show smaller numbers and have the _MORE_ = Y indicating that are more categories. E.g. you see that PROMSPEND has more than 254 values.
3.3 Categorical variables against the target
proc freqtab data=casuser.org_part(where=(_partind_=0));
tables demgender*targetbuy demreg*targetbuy promclass*targetbuy
demtvreg*targetbuy / nocol nopercent;
run;
Note that the PROC FREQTAB needs one variable*targetbuy cross-table per variable; a parenthesised list does not work here.
The row percentages are already a first profile of the target:
Gender is a strong signal: 35% of women buy, 16% of men, and only 6% of the "U" (unknown) group.
Loyalty status matters, in an unexpected direction: Tin customers buy most often (31%), Platinum customers least (14%).
Regions barely matter: the buy rates are between 22% and 26%.
3.4 Graphs
For graphs we use the small sample from above (dataset CASUSER.ORG_SAMPLE) and ordinary PROC SGPLOT, which reads CAS tables directly:
proc sgplot data=casuser.org_sample;
histogram demage / group=targetbuy transparency=0.5;
density demage / type=kernel group=targetbuy;
run;
You receive a visual impression that younger customers are more likely to purchase during the campaign.
proc sgplot data=casuser.org_sample;
vbar promclass / response=targetbuy stat=mean;
yaxis label="Buy rate";
run;
And you see clear differences between LOYALTY STATUS
4. Profile every input against the target
So far we have described the population and in section 3.3 and 3.4 we have already taken a look per target outcome. A modeler needs to know: how do buyers differ from non-buyers? That is what a good model has to pick up, so that is what we look at now.
4.1 Buyers versus non-buyers
A GROUPBY statement in PROC MDSUMMARY repeats the statistics for each target class:
proc mdsummary data=casuser.org_part(where=(_partind_=0));
var &int_raw;
groupby targetbuy;
output out=casuser.sum_by_target;
run;
proc print data=casuser.sum_by_target noobs;
var targetbuy _column_ _nobs_ _nmiss_ _mean_ _std_ _min_ _max_;
run;
You can use PROC TABULATE to get a nicer display of the results table. Alternatively you could sort the above table by _COLUMN_ rather than TARGETBUY. This makes the results better comparable.
proc tabulate data=casuser.sum_by_target;
class _column_ targetbuy;
var _nobs_ _mean_;
table
_column_ = 'Variable',
targetbuy = 'TargetBuy' *
(_nobs_ = 'N' * sum=' ' * f=comma12.
_mean_ = 'Mean' * sum=' ' * f=comma12.1) ;
run;
You see that buyers are younger and more affluent. The tenure of the card hardly differs.
Non-buyers
Buyers
Mean age
56.1
46.6
Mean affluence grade
8.0
10.9
Mean total spend
4,768
3,448
Mean card tenure
6.7
6.1
4.2 Weight of evidence and information value
Credit scoring and marketing analytics use two classic profiling measures. Split each interval variable into bins, and compare for every bin the share of buyers with the share of non-buyers:
Weight of evidence (WOE) per bin: how strongly does the bin separate buyers from non-buyers? Zero means "no information". In PROC BINNING, a positive WOE means fewer buyers than average, a negative WOE more buyers.
Information value (IV) per variable: the sum over its bins, a single number to rank the variables. Rule of thumb: below 0.02 useless, 0.02 to 0.1 weak, 0.1 to 0.3 medium, above 0.3 strong.
PROC BINNING does the binning, knows the target through the TARGET statement, and gives missing values a bin of their own, so that you also see whether being missing says something:
proc binning data=casuser.org_part(where=(_partind_=0)) numbin=5 method=quantile woe;
input &int_raw;
target targetbuy / event="1";
ods output BinDetails=work.bin_details InfoValue=work.info_value;
run;
ODS OUTPUT saves the two result tables as data sets.
The bins tell the story: among customers younger than 41, 57% buy; among customers older than 66, only 14%. The big step at the lowest age bin is a hint that a straight-line effect of age will not capture everything. We keep that in mind for article 2.
You sort and plot them
proc sort data=work.info_value; by descending iv; run;
title "Information value of the interval inputs (training data)";
proc print data=work.info_value noobs; run;
title "Weight of evidence per bin (positive = FEWER buyers than average)";
proc sgpanel data=work.bin_details(where=(binid ne .));
panelby variable / columns=2;
vbar binid / response=woe;
rowaxis label="WOE";
run;
title;
IV
Verdict
DemAge
0.614
strong
DemAffl
0.520
strong
PromSpend
0.072
weak
PromTime
0.019
useless
4.3 CAS Action dataSciencePilot: automated exploration
Finally you also see an example, how to use a CAS Action. DATASCIENCEPILOT is a CAS action set that automates the routine parts of exploration and feature engineering. It has no procedure, so this is the one place where we call actions directly with PROC CAS:
exploreData rates every variable for missing values, cardinality, skewness and outliers.
proc cas;
loadactionset "dataSciencePilot";
/* statistics and quality ratings per variable */
dataSciencePilot.exploreData /
table = {name="org_part", where="_partind_=0"},
inputs = {"DemAffl","DemAge","PromSpend","PromTime","DemCluster",
"DemGender","DemReg","DemTVReg","PromClass"},
target = "targetbuy",
casOut = {name="dsp_explore", replace=true}; quit; proc print data=casuser.dsp_explore noobs;
var variable vartype n nmiss missrate cardinality;
run;
exploreCorrelation computes the mutual information between each input and the target.
Unlike a classical correlation it works for interval and categorical inputs, so all nine inputs end up in one ranking
proc cas;
/* mutual information between each input and the target */
dataSciencePilot.exploreCorrelation /
table = {name="org_part", where="_partind_=0"},
inputs = {"DemAffl","DemAge","PromSpend","PromTime","DemCluster",
"DemGender","DemReg","DemTVReg","PromClass"},
nominals = {"DemCluster","DemGender","DemReg","DemTVReg","PromClass","targetbuy"},
target = "targetbuy", event = "1",
casOut = {name="dsp_corr", replace=true};
quit; proc sort data=casuser.dsp_corr out=work.dsp_corr; by descending mi; run;
title "Mutual information with TARGETBUY (higher = more informative)";
proc print data=work.dsp_corr noobs; var firstvariable secondvariable type mi; run;
The ranking agrees with the information values from step 4.2, and it adds the categorical variables: gender is the third most informative input, regions are nearly irrelevant.
screenVariables gives a keep or remove recommendation per input.
proc cas;
/* keep / remove recommendation per variable */
dataSciencePilot.screenVariables /
table = {name="org_part", where="_partind_=0"},
inputs = {"DemAffl","DemAge","PromSpend","PromTime","DemCluster",
"DemClusterGroup","DemGender","DemReg","DemTVReg","PromClass"},
nominals = {"DemCluster","DemClusterGroup","DemGender","DemReg","DemTVReg",
"PromClass","targetbuy"},
target = "targetbuy",
casOut = {name="dsp_screen", replace=true};
quit; title "Screening recommendation";
proc print data=casuser.dsp_screen noobs; run;
quit;
Summary
What you have learned:
The table had every customer five times. We removed the duplicates before splitting, which keeps validation and test data honest.
One customer in four buys. The three partitions have the same event rate.
Age, affluence and gender carry most of the information about the target. PROMSPEND is weak, regions are close to useless.
There are missing values in age (7%), affluence (5%) and especially gender (11%), and PROMSPEND is extremely skewed. These are the data quality issues to fix next.
In article xxx we fix them: we flag and impute missing values, build new features by hand and with the automatic feature machine, create customer segments with clustering, and select the variables worth modeling.
More of my articles and links can be found in my header article Data Science and Data Preparation Article Overview by Gerhard.
... View more