Keywords

These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.

HTTP cookies are used to monitor web-traffic and track users surfing the Internet. We often notice that promotions (ads) on websites tend to match our needs, reveal our prior browsing history, or reflect our interests. That is not an accident. Nowadays, recommendation systems are highly based on machine learning methods that can learn the behavior, e.g., purchasing patterns, of individual consumers. In this chapter, we will uncover some of the mystery behind recommendation systems for transactional records. Specifically, we will (1) discuss association rules and their support and confidence; (2) the Apriori algorithm for association rule learning; and (3) cover step-by-step a set of case-studies, including a toy example, Head and Neck Cancer Medications, and Grocery purchases.

12.1 Association Rules

Association rules are the result of process analytics (e.g., market analysis) that specify patterns of relationships among items. One specific example would be:

$$ \left\{ charcoal, lighter, chicken\kern0.17em wings\right\}\to \left\{ barbecue\kern0.17em sauce\right\} $$

In words, charcoal, lighter and chicken wings imply barbecue sauce. Those curly brackets indicate that we have a set. Items in a set are called elements. When an item-set like {charcoal, lighter, chicken wings, barbecue sauce} appears in our dataset with some regularity, we can discover the above pattern.

Association rules are commonly used for unsupervised discovery of knowledge rather than prediction of outcomes. In biomedical research, association rules are widely used to:

  • Search for interesting or frequently occurring patterns of DNA.

  • Search for protein sequences in an analysis of cancer data.

  • Find patterns of medical claims that occur in combination with fraudulent credit card or insurance use.

12.2 The Apriori Algorithm for Association Rule Learning

Association rules are mostly applied to transactional data, like business, trade, service or medical records. These datasets are typically very large in number of transactions and features. This will add lots of possible orders and patterns when we try to do analytics, which makes data mining a very hard task.

With the Apriori rule, this problem is easily solved. If we have a simple prior (belief about the properties of frequent elements), we can efficiently reduce the number of features or combinations that we need to look at.

The Apriori algorithm has a simple apriori belief that all subsets of a frequent item-set must also be frequent. This is known as the Apriori property. The full set in the last example, {charcoal, lighter, chicken wings, barbecue sauce}, can be frequent if and only if itself and all its subsets of single elements, pairs and triples occur frequently. We can see that this algorithm is designed for finding patterns in large datasets. If a pattern happens frequently, it is considered “interesting”.

12.3 Measuring Rule Importance by Using Support and Confidence

Support and confidence are the two criteria to help us decide whether a pattern is “interesting”. By setting thresholds for these two criteria, we can easily limit the number of interesting rules or item-sets reported.

For item-sets X and Y, the support of an item-set measures how frequently it appears in the data:

$$ support(X)=\frac{count(X)}{N}, $$

where N is the total number of transactions in the database and count(X) is the number of observations (transactions) containing the item-set X. Of course, the union of item-sets is an item-set itself. For example, if Z = X, Y, then

$$ support(Z)= support\left(X,Y\right). $$

For a rule X → Y, the rule’s confidence measures the relative accuracy of the rule:

$$ confidence\left(X\to Y\right)=\frac{support\left(X,Y\right)}{support(X)} $$

This measures the joint occurrence of X and Y over the X domain. If whenever X appears Y tends to be present too, we will have a high confidence(X → Y). The ranges of the support and confidence are 0 ≤ support, confidence ≤ 1. Note that in probabilistic terms, Confidence (XY) is equivalent to the conditional probability P(YX).

{peanut butter} → {bread} would be an example of a strong rule because it has high support as well as high confidence in grocery store transactions. Shoppers tend to purchase bread when they get peanut butter. These items tend to appear in the same baskets, which yields high confidence for the rule {peanut butter} → {bread}.

12.4 Building a Set of Rules with the Apriori Principle

To build a set of rules, we need to go through two steps:

  • Step 1: Filter all item-sets with a minimum support threshold. This is accomplished iteratively by increasing the size of the item-sets. In the first iteration, we compute the support of singletons, 1-item-sets. At the next iteration, we compute the support of pairs of items, and so on. Item-sets passing iteration i could be considered as candidates for the next iteration, i + 1. If {A}, {B}, {C} are all frequent, but D is not frequent in the first singleton-selection round, then in the second iteration we only consider the support of these pairs {A, B}, {A,C}, {B,C}, ignoring all pairs including D. This substantially reduces the cardinality of the potential item-sets and ensures the feasibility of the algorithm. At the third iteration, if {A,C}, and {B,C} are frequently occurring, but {A, B} is not, then the algorithm may terminate, as the support of {A,B,C} is trivial (does not pass the support threshold), given that {A, B} was not frequent enough.

  • Step 2: Using the item-sets selected in Step 1, generate new rules with confidence larger than a predefined minimum confidence threshold. The candidate item-sets that passed Step 1 would include all frequent item-sets. For the highly-supported item-set {A, C}, we would compute the confidence measures for {A} → {C} as well as {C} → {A} and compare these against the minimum confidence threshold. The surviving rules are the ones with confidence levels exceeding that minimum threshold.

12.5 A Toy Example

Assume that a large supermarket tracks sales data by stock-keeping unit (SKU) for each item, i.e., each item, such as “butter” or “bread”, is identified by an SKU number. The supermarket has a database of transactions where each transaction is a set of SKUs that were bought together (Table 12.1).

Table 12.1 Item table

Suppose the database of transactions consist of following item-sets, each representing a purchasing order:

figure a

We will use Apriori to determine the frequent item-sets of this database. To do so, we will say that an item-set is frequent if it appears in at least 3 transactions of the database, i.e., the value 3 is the support threshold (Table 12.2).

Table 12.2 Size 1 support

The first step of Apriori is to count up the number of occurrences, i.e., the support, of each member item separately. By scanning the database for the first time, we obtain get:

figure b

All the item-sets of size 1 have a support of at least 3, so they are all frequent. The next step is to generate a list of all pairs of frequent items.

For example, regarding the pair {1, 2}: the first table of Example 2 shows items 1 and 2 appearing together in three of the item-sets; therefore, we say that the support of the item {1, 2} is 3 (Tables 12.3 and 12.4).

Table 12.3 Size 2 support
Table 12.4 Size 3 support
figure c

The pairs {1, 2}, {2, 3}, {2, 4}, and {3, 4} all meet or exceed the minimum support of 3, so they are frequent. The pairs {1, 3} and {1, 4} are not and any larger set which contains {1, 3} or {1, 4} cannot be frequent. In this way, we can prune sets: we will now look for frequent triples in the database, but we can already exclude all the triples that contain one of these two pairs:

figure d

In the example, there are no frequent triplets – the support of the item-set {2, 3, 4} is below the minimal threshold, and the other triplets were excluded because they were super sets of pairs that were already below the threshold. We have thus determined the frequent sets of items in the database, and illustrated how some items were not counted because some of their subsets were already known to be below the threshold.

12.6 Case Study 1: Head and Neck Cancer Medications

12.6.1 Step 1: Collecting Data

To demonstrate the Apriori algorithm in a real biomedical case-study, we will use a transactional healthcare data representing a subset of the Head and Neck Cancer Medication data, which is available in our case-studies collection as 10_medication_descriptions.csv. It consists of inpatient medications for head and neck cancer patients.

The data is in wide format, see Chap. 2, where each row represents a patient. During the study period, each patient had records for a maximum of 5 encounters. NA represents no medication administration records in this specific time point for the specific patient. This dataset contains a total of 528 patients.

12.6.2 Step 2: Exploring and Preparing the Data

Different from our data imports in the previous chapters, transactional data need to be ingested in R using the read.transactions() function. This function will store data as a matrix with each row representing an example and each column representing a feature.

Let’s load the dataset and delete the irrelevant index column. With the write.csv( R data, "path") function we can output our R data file into a local CSV file. To avoid generating another index column in the output CSV file, we can use the row.names = F option.

figure e

Now we can use read.transactions() in the arules package to read the CSV file we just outputted.

figure f

Here we use the option rm.duplicates = T because we may have similar medication administration records for two different patients. The option skip = 1 means we skip the heading line in the CSV file. Now we get a transactional data with unique rows.

The summary of a transactional data contains rich information. The first block of information tells us that we have 528 rows and 88 different medicines in this matrix. Using the density number we can calculate how many non NA medication records are in the data. In total, we have 528 × 88 = 46,464 positions in the matrix. Thus, there are 46,464 × 0.0209 = 971 medicines prescribed during the study period.

The second block lists the most frequent medicines and their frequencies in the matrix. For example, fentanyl injection uh appeared 211 times; that is 211/528 = 40 of the (treatment) transactions. Since fentanyl is frequently used to help prevent pain after surgery or other medical procedure, we can see that many of these patients were going through some painful medical procedures.

The last block shows statistics about the size of the transaction. 248 patients had only one medicine in the study period, while 12 of them had 5 medication records one for each time point. On average, the patients are having 1.8 different medicines.

12.6.2.1 Visualizing Item Support: Item Frequency Plots

The summary might still be fairly abstract; let’s visualize the data.

figure g

The inspect() call shows the transactional dataset. We can see that the medication records of each patient are nicely formatted as item-sets.

We can further analyze the frequent terms using itemFrequency(). This will show all item frequencies alphabetically ordered from the first five outputs (Fig. 12.1).

figure h
Fig. 12.1
figure 1

Rank-order plot of item frequencies

The above graph is showing us the top 20 medicines that are most frequently present in this dataset. Consistent with the prior summary() output, fentanyl is still the most frequent item. You can also try to plot the items with a threshold for support. Instead of topN = 20, just use the option support = 0.1, which will give you all the items have a support greater or equal to 0.1.

12.6.2.2 Visualizing Transaction Data: Plotting the Sparse Matrix

The sparse matrix will show what mediations were prescribed for each patient (Fig. 12.2).

Fig. 12.2
figure 2

A characteristic plot of the prescribed medications (columns) for the first 5 patients (rows)

figure i

The image on Fig. 12.2 has 5 rows (we only requested the first 5 patients) and 88 columns (88 different medicines). Although the picture may be a little hard to interpret, it gives a sense of what kind of medicine is prescribed for each patient in the study.

Let’s see an expanded graph including 100 randomly chosen patients (Fig. 12.3).

figure j
Fig. 12.3
figure 3

A characteristic plot of the prescribed medications (columns) for 100 random patients (rows)

It shows us clearly that some medications are more popular than others. Now, let’s fit the Apriori model.

12.6.3 Step 3: Training a Model on the Data

With the data in place, we can build the association rules using apriori() function.

figure k
  • Data: a sparse matrix created by read.transacations().

  • Support: minimum threshold for support.

  • Confidence: minimum threshold for confidence.

  • minlen: minimum required rule items (in our case, medications).

Setting up the threshold could be hard. You don’t want it to be too high so that you get no rules or rules that everyone knows. You don’t want to set it too low either, to avoid too many rules present. Let’s see what we get under the default setting support = 0.1, confidence = 0.8:

figure l

Not surprisingly, we have 0 rules. The default setting is too high. In practice, we might need some time to fine-tune these thresholds, which may require certain familiarity with the underlying process or clinical phenomenon.

In this case study, we set support = 0.1 and confidence = 0.25. This requires rules that have appeared in at least 10% of the head and neck cancer patients in the study. Also, the rules have to have least 25% accuracy. Moreover, minlen = 2 would be a very helpful option because it removes all rules that have fewer than two items.

The results suggest we have a new rules object consisting of 29 rules.

figure m

12.6.4 Step 4: Evaluating Model Performance

First, we can obtain the overall summary of this set of rules.

figure n

We have 13 rules that contain two items; 12 rules containing 3 items, and the remaining 4 rules contain 4 items.

The lift column shows how much more likely one medicine is to be prescribed to a patient given another medicine is prescribed. It is obtained by the following formula:

$$ lift\left(X\to Y\right)=\frac{confidence\left(X\to Y\right)}{support(Y)}. $$

Note that lift(X → Y) is the same as lift(Y → X). The range of lift is [0, ∞) and higher lift is better. We don’t need to worry about support since we already set a threshold that the support will exceed.

Using hte arugleViz package we can visualize the confidence and support scatter plots for all the rules (Fig. 12.4).

Fig. 12.4
figure 4

Confidence-Support scatterplot of 29 rules

figure o

Again, we can utilize the inspect() function to see exactly what are these rules.

figure p

Here, lhs and rhs refer to “left hand side” and “right hand side” of the rule, respectively. Lhs is the given condition and rhs is the predicted result. Using the first row as an example: If a head-and-neck patient has been prescribed acetaminophen (pain reliever and fever reducer), it is likely that the patient is also prescribed cefazolin (antibiotic that resist bacterial infections); bacterial infections are associated with fevers and some cancers.

12.6.5 Step 5: Improving Model Performance

12.6.5.1 Sorting the Set of Association Rules

Sorting the resulting association rules corresponding to high lift values will help us select the most useful rules.

figure q

These rules may need to be interpreted by clinicians and experts in the specific context of the study. For instance, the first row, {fentanyl, heparin, hydrocodone acetaminophen} implies {cefazolin}. Fentanyl and hydrocodone acetaminophen are both pain relievers that may be prescribed after surgery. Heparin is usually used before surgery to reduce the risk of blood clots. This rule may suggest that patients who have undergone surgical treatments may likely need cefazolin to prevent post-surgical bacterial infection.

12.6.5.2 Taking Subsets of Association Rules

If we are more interested in investigating associations that are linked to a specific medicine, we can narrow the rules down by making subsets. Let us try investigating rules related to fentanyl, since it appears to be the most frequently prescribed medicine.

figure r

In R scripting, the notation %in% signifies “belongs to.” There are 14 rules related to this item. Let’s plot them (Fig. 12.5).

Fig. 12.5
figure 5

Bubble chart of the grouped matric for 14 rules

figure s
figure t

12.6.5.3 Saving Association Rules to a File or Data Frame

We can save these rules into a CSV file using write(). It is similar with the function write.csv() that we have mentioned in the beginning of this case study.

figure u

Sometimes it is more convenient to convert the rules into a data frame.

figure v

As we can see, the rules are converted into a factor vector.

12.7 Practice Problems: Groceries

In this practice problem, we will investigate the associations of frequently purchased groceries using the grocery dataset in the R base. Firstly, let’s load the data.

figure w
figure x

We will try to find out the top 5 frequent grocery items and plot them (Fig. 12.6).

Fig. 12.6
figure 6

Top-5 grocery items according to their frequencies

Then, try to use support = 0.006, confidence = 0.25, minlen = 2 to set up the grocery association rules. Sort the top 3 rules with highest lift.

figure y
figure z

The number of rules (463) appears excessive. We can try stringer parameters. In practice, it’s more possible to observe underlying rules if you set a higher confidence. Here we set the confidence = 0.6.

figure aa
figure ab

We observe mainly rules between dairy products. It makes sense that customers pick up milk when they walk down the dairy products isle. Experiment further with various parameter settings and try to interpret the results in the context of this grocery case-study (Fig. 12.7).

Fig. 12.7
figure 7

Live demo: association rule mining

Mining association rules Demo https://rdrr.io/cran/arules/

figure ac

12.8 Summary

  • The Apriori algorithm for association rule learning is only suitable for large transactional data. For some small datasets, it might not be very helpful.

  • It is useful for discovering associations, mostly in early phases of an exploratory study.

  • Some rules can be built due to chance and may need further verifications.

  • See also Chap. 20 (Text Mining and NLP).

Try to replicate these results with other data from the list of our Case-Studies.

12.9 Assignments: 12. Apriori Association Rules Learning

Use the SOCR Jobs Data to practice learning via Apriori Association Rules

  • Load the Jobs Data. Use this guide to load HTML data.

  • Focus on the Description feature. Replace all underscore characters “_” with spaces.

  • Review Chap. 8, use tm package to process text data to plain text. (Hint: need to apply stemDocument as well, we will discuss more details in Chap. 20.)

  • Generate a “transaction” matrix by considering each job as one record and description words as “transaction” items. (Hint: You need to fill missing values since records do not have the same length of description.)

  • Save the data using write.csv() and then use read.transactions() in arules package to read the CSV data file. Visualize the item support using item frequency plots. What terms appear as more popular?

  • Fit a model: myrules <− apriori(data = jobs,parameter = list(support = 0.02, confidence = 0.6, minlen = 2)). Try out several rule thresholds trading off gain and accuracy.

  • Evaluate the rules you obtained with lift and visualize their metics.

  • Mine medical related rules (e.g., rules include “treatment”, “patient”, “care”, “diagnos.” Notice that these are word stems).

  • Sort the set of association rules for all and medical related subsets.

  • Save these rules into a CSV file.