Homework 2 - Star Spangled Bayeser

This is a *group* assignment! Feel free to work in groups of up to 3 individuals.

Having done such good work on Solicitorbot, you have been promoted to an advertising data scientist at Forney Industries, which is just about to launch its newest Home Automation / Defense line of robotics.

The beta phase of Killbot 3000 Defendotron 3001 is complete, and initial sales have been made to a variety of customers around the US.

After each of these initial sales pitches (that ended in purchases or otherwise), Forney Industries collected demographic data on each participant, and quizzed them on a variety of metrics that were believed to be in some way related to the outcome of the sale.

The launch of the Defendotron line is now upon us, and two customizable models are available for public consumption:

  • Defendotron Basic [$500]: comes with a siren and tazer to alert you and protect your home from intruders.

  • Defendotron 'Murica [$1,776]: comes with a full arsenal, including SAM missile array to protect from drone attack. Plays the Star Spangled Banner in place of siren when an intruder is detected.

Defendotron Basic and 'Murica editions, renderings courtesy of Niccolo Menotti.


The Data


Pending the launch of the Defendotron line, you are now analyzing the data collected by the in-person sales team in which a variety of traits and features must be integrated into an online advertising agent meant to select an ad that is most likely to be converted into a sale.

In particular, before giving their pitch, the members of the sales team showed participants ads with two key variables:

  • Ad Video Choice [Ad1]: the video shows either a scare tactic of a home robbery (Ad1 = 0) or a patriotic montage with lots of guns and flags waving (Ad1 = 1).

  • Ad Music Choice [Ad2]: the video either has a narrator's voice-over explaining the product (Ad2 = 0) or some tasteful classic rock that mentions freedom a bunch (Ad2 = 1).

The sales team showed each of these ad combinations at random, then collected data on several important, binary features (described below) as well as the *ternary* (3 values) outcome of the sales call:

  • Political Leaning [P]: the political leaning of the interviewee (0 = conservative, 1 = liberal)

  • Age Group [A]: generational age group of interviewee (0 = millennial, 1 = baby boomer+)

  • Position on Gun Control [G]: whether or not the interviewee is in support of stricter gun control legislation (0 = no, 1 = yes)

  • Possession of Home/Renter's Insurance [I]: whether or not the interviewee possesses home or renter's insurance (0 = no, 1 = yes)

  • Perceived Threat of Crime [T]: whether or not the interviewee believes they live in a crime-filled neighborhood (0 = no, 1 = yes)

  • Perceived Threat of Foreign Invasion [F]: whether or not the interviewee believes in a foreign threat to the homeland (0 = no, 1 = yes)

  • Home Ownership [H]: whether or not the interviewee owns their home (0 = doesn't own, 1 = owns).

  • Sold Defendotron [S]: outcome of the sales pitch (0 = didn't buy anything, 1 = bought Defendotron 'Murica, 2 = bought Defendotron basic)

You can find the dataset they collected from thousands of participants in the project skeleton.


Your Task


Your task: create a decision-network-based Ad Agent that will maximize Forney Industries' sales of Defendotrons online based on any of the user's collected demographic data on the metrics above. The agent must select the combination of Ad characteristics [Ad1, Ad2] that maximizes the expected utility of a sale.

The problem: for each online sale, only some of these features may be known / observed, and so we need a means of deciding which ad combination to show them to maximize our expected sales.

Specifically, you are tasked with the following:

  • Gain an understanding of the relationship between the variables collected by the sales team.

  • Use this understanding to create an autonomous advertising agent.


Solution Skeleton

Start with the solution skeleton for this part in-hand! Segments left for you to do are indicated in comments:

PostCommit


Included in the skeleton are:

  • warmup.py sandbox for figuring out the mechanics of probabilistic graphical models; a warmup exercise will help you understand the tools that you'll use in the main-course.

  • constants.py, containing some constants to be used in construction of the AdEngine.

  • ad_agent.py, the main workhorse of your solution that contains methods for computing expected utilities of certain ad actions.

  • ad_agent_skeleton_tests.py a selection of unit tests to help you validate your ad_agent performance. Per usual, there will be some hidden grading tests so validate carefully!

  • price_is_right.py, used to create "games" of mock customer data through which to test your ad agent's savvy.

  • price_is_right_skeleton_tests.py, simulations for testing your agent's ability to discern between information that is valuable or not.

  • mypy.ini, pytest.ini configuration files for mypy, pytest respectively. Do not change these!

  • .gitignore a set of patterns for git to avoid committing. You may modify this file if your commit attempts to add any project files to the repo (e.g., VSCode .project files or pycache folders, which should not be submitted).


We'll also be using a few great programs and libraries that are popularly employed in this domain:

  • Tetrad

    Download Tetrad (Most Recent)

    If the above doesn't work for you / you have issues loading data, try this older version:

    Download Tetrad (Legacy)

  • pgmpy (= probabilistic graphical model... py), a library for Bayesian Inference (among many others), which can be installed via the instructions listed on its GitHub page (as simple as pip install pgmpy):

    Get pgmpy

  • Pandas Data Frames, a library for structuring, reading, and manipulating tabular data like in a .csv file. Getting pandas is as simple as pip install pandas. You can find a tutorial for using its (intuitive) interface here:

    Pandas Tutorial

    For a brisk introduction, focus on the tutorial sections of: Object Creation, Viewing Data, Selection, Operations, Merging, Grouping.

To install any missing mypy types from these libraries, navigate to the src directory and run: mypy --install-types (you may need to open a terminal in Administrator mode or use the sudo command to elevate permissions here)

Throughout this process, you will be using some programmatic tools and some non-programmatic tools; when asked to record certain parts of the process, make additions to a Report file that you will submit as some sort of text / pdf document within a doc folder of your PostCommit Repository.



Bayesian Network Modeling

To address the goals above, we will familiarize ourselves with several popular probabilistic reasoning machine learning toolkits.

Since we are starting this endeavor with only the dataset, our first task is to examine the putative structure of the BN using a bottom-up approach.

This is not difficult to automate for some models, but in general, may require some companion human intervention. At the very least, it gives us and our greater marketing team some insights into what our customer-base looks like.

However, when it comes to using Bayesian Networks to model causal relationships, the story is a bit trickier for a familiar reason:

Observational equivalence: we may have independence relationships between variables that can be explained by different structures (e.g., \(X \rightarrow Z \rightarrow Y\) and \(X \leftarrow Z \rightarrow Y\) make the same independence claim that \(X \indep Y~|~Z\), but which is the "correct" causal story requires a human's assumptions since this is not a determination that can be made from the data alone).

As such, we'll use a structure learning tool that can help us determine what parts of the BN structure can be learned from data and which require humans to set into place.


There are several popular tools for BN structure learning, but one of the most developed and used in academic settings is Tetrad, which you can find and download in the Solution Skeleton section above (just get the most recent version and download the associated *-launch.jar):

Tetrad is developed at CMU/Pitt and is useful in both probabilistic and causal structure discovery -- it does not provide tools for inference, which we will find elsewhere once we have seen some causal discovery algorithms.

What follows is a walkthrough for using Tetrad to determine the BN structure modeling the dataset given above.


[Structure Learning]

Use the adbot-data.csv for this section to learn the Bayesian Network structure for the programmatic component that follows!

  1. Download the latest version of Tetrad (instructions above)

  2. Launch Tetrad (can just double click on the .jar file though Unix systems might need the terminal), after which you will be greeted with a new project window. Tetrad is modular, allowing you to make an analysis project that is comprised of various linkable stages.

    If Tetrad fails to load by double clicking on it, you can often instead launch via the terminal by (1) navigating to the directory of the .jar file, and then typing java -jar [name_of_tetrad_jar_file]. If you're on a Mac / Unix system, you may need to sudo this command, i.e., sudo java -jar [name_of_tetrad_jar_file]

  3. Since we are interested in learning a network structure from data, go to the menu at the top and select Pipelines -> Search then Estimate. What appears is a pipeline that will find as much of the network structure as possible, have us decide on the final model, and then will estimate the network parameters (CPTs). To do this, double click on each module in the following order, and perform the given steps:

    1. Data: load the dataset into Tetrad via File -> Load Data, making sure to select "Discrete" data in the dialogue that pops up. You should see all of the data in the table after this step.

      Note: If you're on MacOS and fail to find the data file at this step, it's the stupid Mac security settings. To overcome this, you must move BOTH the Tetrad jar file AND the csv file into a folder that is NOT in Documents, Downloads, or Desktop.

    2. Search: we'll now search for the network structure. In this module, you'll see that there are *many* structure learning algorithms for a variety of scenarios.

      • In our case, we'll use the PC method, which you shall select, then click "Set parameters" and finally "Run and Generate Graph." (there's also a small snippet on the right with what it does -- neat!)

      • You'll notice that the structure is *almost* completely directed, except for some edges that are not. These are the edges that are not discernable from the data alone and comprise the models in the observational equivalence class of the data.

        Sometimes, Tetrad will commit to one possible graph in the observational equivalence class and you won't see any undirected edges; that's fine too, just inspect each relationship to make sure they make sense!

      • Note which edges were not able to be directed at this point, you'll need those again in a second.

    3. Graph: it's time for us to provide the direction of the edges that had an unknown orientation from the structure learning.

      • Select "Choose DAG in CPDAG" the edges that need to have an orientation chosen will be highlighted in yellow (and should coincide with those that you noted in the earlier step), but you are given a "default" orientation that you (may) need to change. Inspect the graph for any observationally-equivalent edges that don't make realistic sense (e.g., the Age variable shouldn't be a child of another).

        Warning: the edges that need to be directed will be highlighted in yellow, and Tetrad will give you a *suggested* direction at this point that need not be your final answer! Read on for how to change the edge directions.

      • Under the Layout menu of this panel, choose a clearer means of ordering the nodes; I'd suggest the Fruchterman-Reingold layout (which is kinda fun that even algorithms for visualizing network structures are complex enough to get named... it's a hard problem!).

      • From here, choose an edge direction for these ambiguous edges based on logical relationships of cause and effect. It should be fairly obvious which direction the edges should point given the interpretations of the variables involved (though in general, you would need some sound, scientific rationale for orienting an ambiguous edge in a particular direction).

      • The above step will require you use the edge tool (\(X \rightarrow Y\) in the menu) which you select and drag from cause to effect. You will also have to select (by clicking on the edge [obnoxiously, the line, not the arrowhead]) and then delete (hitting the delete key) any suggested edges that you wanted to change.

      • Once you are satisfied (and have a proper DAG structure) hit the Done button.

    4. PM (Parameterized Model): just double click on this to verify the network structure, variable values, and expected CPTs.

    5. Estimator: this module will list the network CPTs and parameters from the structure you learned / provided, plus the data from the first step. If given an option, choose the ML = Maximum Likelihood Estimator. (Note: display of the CPTs can be finnicky and it looks like some versions of Tetrad don't show them all -- don't worry, you'll be able to find then using pgmpy in a future step).

[Report] Include the following your report:

  1. Take a screenshot of a topologically sorted arrangement of the nodes in the resulting network structure for your report (seeing nodes in their parent-child topologies is useful from a causal perspective; any display wherein its clear who's whose parent is fine).

  2. Without having to look up the PC Structure Learning algorithm, examine and then explain why structure discovery algorithms MIGHT be able to orient the direction of some edges, but not others. (hint: look at the relationship between A, H, I in the graph you found above)

  3. When you are finished, save the Tetrad Session to a tet folder at the top level of your git directory. Name the session bn_analysis



Probabilistic Graphical Model (PGM) Programming

Now that we have examined the network structure from the step above, it's time to head back to the programmatic side.


Important Documentation


Once installed, head over to warmup.py and then read the pgmpy documentation for querying a small Bayesian Network (notably, we're using the CausalInference package here to make use of the do operator for our decision networks!):

pgmpy BN Query


As a brief example, suppose we have a simple Bayesian Network with 4 binary variables \(W, X, Y, Z\) and the following structure:

  # Load the data into a pandas data frame
  csv_data = pd.read_csv("../dat/warmup-data.csv")
  
  # Set the edges of the network: tuples of the format (parent, child)
  edges = [("W", "X"), ("W", "Y"), ("X", "Z"), ("Y", "Z")]
  
  # Build the network structure from the edges
  model = DiscreteBayesianNetwork(edges)
  
  # "Fit" the model = learn the CPTs from the data and structure
  model.fit(csv_data)
  
  # Create the inference engine using the Variable Elimination algorithm
  # (a more efficient enumeration inference)
  inference = CausalInference(model)
  
  # Here's an example query: P(Y | X=0)
  query = inference.query(["Y"], evidence={"X": 0}, show_progress=False)
  print("P(Y | X=0)", query)
  
  # Now, suppose we instead intervene on do(X=0) (which is possible for any
  # node, in general, though we'll only intervene on decision nodes for this
  # assignment)
  query = inference.query(["Y"], do={"X": 0}, show_progress=False)
  print("P(Y | do(X=0))", query)
  
  # What do you notice about the query results above? (1) they are tables,
  # and (2) the results are different if you treat X as evidence vs. intervention!
  # (albeit slightly, but in general they can be much different)
  # Notice also that X DOES give some information about Y when it's evidence!
  # Can you see why in d-sep terms?
  
  # To programmatically access those table values, you can access the 
  # values attribute of the CPT and then grab any by index, e.g.,
  print("P(Y=0|do(X=0)) = " + str(query.values[0]))

Exercises


[Warmup]

For the following problems, use the starter code above in warmup.py to derive your answer. Each question is based off of the warmup-data.csv located in the project skeleton's dat directory.

  1. Use the network structure in the example above in this warmup.

  2. Having successfully constructed a Bayesian Network using the given warmup data, use the pgmpy interface to determine the answers to the following queries:

    1. \(P(Y)\) (i.e., for all values of \(Y\))

    2. \(P(Y | W=1)\)

    3. \(P(Z | W=1, do(X=1))\)

Hint: you can validate the first two queries immediately by looking at the network CPTs, though note that the values will be a bit messy because they're coming from simulated data rather than nice neat CPTs.

For later: note that this can be a great study aid as you're preparing for the exams -- make a Bayesian Network and use this warmup to check the answers!



Decision Network Programming

GenAI use for the entirety of all problems until stated otherwise is BANNED as it will shortcut your learning and generalizable skills (besides, there's not much code to write, the exercise is meant to teach you how to implement a decision network from first-principles) though is always OK for understanding error messages, interpreting skeleton code, etc. as outlined in the syllabus.


Back to the task at hand: you must design an agent that uses a decision network that, when given *some* of the features specified above, returns the best choices for any specified decision variables.

You will do so by completing the skeleton for the DecisionNetwork class that was included in the skeleton.

One quirk: we're using our 2 decision nodes "Ad1" and "Ad2" as though they were chance nodes, but each has \(P(Ad=a) = 0.5\), making them special randomly assigned nodes that have no parents. This is a detail we'll explore more in CMSI 4320, but for now, know that we're licensed to use them as decision nodes with the understanding that all queries we pose to this system will always have them as givens.


[Initialization]

There are two parts here: (1) to complete the DecisionNetwork constructor and (2) to complete the specific arguments for its use in the data attached.

Let's start with the constructor, which will be responsible for initializing the Decision Network's attributes!

  def __init__(self, bn_model: "DiscreteBayesianNetwork", dec_vars: list[str], util_map: dict[str, dict[int, int]]):
      """
      Responsible for initializing the Decision Network of the
      DecisionNetwork by taking in a pre-built Bayesian Network model,
      any decision variables, and a map of utilities
      
      Parameters:
          bn_model (DiscreteBayesianNetwork):
              A pre-built pgmpy DiscreteBayesianNetwork model
          dec_vars (list[str]):
              list of string names of variables to be
              considered decision variables for the agent. Example:
              ["Ad1", "Ad2"]
          util_map (dict[str, dict[int, int]]):
              Discrete, tabular, utility map whose keys
              are variables in network that are parents of a utility node, and
              values are dictionaries mapping that variable's values to a utility
              score, for example:
                {
                  "X": {0: 20, 1: -10}
                }
              represents a utility node with single parent X whose value of 0
              has a utility score of 20, and value 1 has a utility score of -10
      """
      # Set the model directly from the provided DiscreteBayesianNetwork
      self.model = bn_model
      self.nodes = list(bn_model.nodes())
      self.dec_var_names: list[str] = dec_vars
      self.util_map = util_map
      
      # TODO! PROBLEM 3: Any other initialization needed for the decision network

For simplicity's sake, we'll scale back our ambition and only require that your decision network works for inputs of a *single* chance node parent of the utility node. In other words, don't worry about having multiple nodes scored by the utility function, nor any decision nodes.

It will be up to you to determine the contributing variables and corresponding utility scores for the Defendotron example!


The constructor should perform the following:

  1. Keep track of the decision, chance, and utility variables through some record-keeping mechanism (noting that variables need not be binary, but that the possible values of any variable can be known in advance through the input BayesianNetwork -- hint, look up some pgmpy methods to get all variable vals.)

  2. Initialize any other attributes you may want in the methods that follow


Secondly, head on over to constants.py where you'll find some blanks to fill in under the AdBot example:

  • Using your work from learning the network structure in Tetrad, fill in the structure's list of edges for the ADBOT_STRUC constant.

  • Reading from the spec's overview, decide which variables will constitute the list of decision vars and add these to ADBOT_DEC

  • Also reading from the spec's intro, determine what the utility map should look like (i.e., which variable should be scored and to what utilities) by completing the ADBOT_UTIL map.


[EU / MEU]

Our agent would be pretty poor if it couldn't at least give some estimate for the expected utility of its available decisions; let's implement the Expected Utility (EU) and Maximum Expected Utility (MEU) methods to help us get those values and decisions.

  def eu(self, evidence: dict[str, int], decision: dict[str, int]) -> float:
      """
      Computes the Expected Utility (EU) of a given decision given some observed evidence
      and chosen decisions / actions, i.e., EU(decision | evidence).

      Parameters:
          evidence (dict[str, int]):
              Dict mapping network variables to their
              observed values, of the format: {"Obs1": val1, "Obs2": val2, ...}
          decision (dict[str, int]):
              Dict mapping decision variables to their
              chosen values, of the format: {"Dec1": val1, "Dec2": val2, ...}

      Returns:
          float:
              Float value indicating the EU(decision | evidence)
      """
  
  def meu(self, evidence: dict[str, int]) -> dict[str, Any]:
      """
      Computes the Maximum Expected Utility (MEU) defined as the choice of
      decision variable values that maximize expected utility of any evaluated
      chance nodes given in the agent's utility map.
      
      Parameters:
          evidence (dict[str, int]):
              dict mapping network variables to their observed values, 
              of the format: {"Obs1": val1, "Obs2": val2, ...}
      
      Returns: 
          dict[str, Any]:
              A dictionary with keys:
              - "a*": dictionary mapping decision variables to their MEU states
              - "meu": the MEU value (a float) of that decision combo
      """

Some pearls of wisdom:

  • Ample helper methods will be your friend here! Hint: do like we've done in the steps to compute MEU from a decision network in class: start with the needed probabilities, then EU, then MEU -- helper methods are encouraged! Don't try to do everything at once.

  • YOU DO NOT NEED TO DO THE STEPS OF ENUMERATION INFERENCE! Any time you need the results of a probabilistic expression, simply call the query method as demonstrated in the warmup.py

  • Note also when to use the evidence parameter and when to use the do parameter in the query method provided by pgmpy -- when in doubt, head to the equations in your notes!

  • Remember that the format of a* (the best "action" / decision) is a combination of available action choices and their possible values, so this resulting dictionary will have as many keys as there are decision variables input in the constructor.

  • Be wary of variable cardinality! In general, your solution should work for variables that aren't just binary, e.g., \(X \in \{0, 1, 2\}\). If you structure your solution to explore combinitorics correctly, it will work in any case [Hint: remember the itertools package might be useful in places!].

To run some of the sample unit tests, execute pytest -k eu


[VPI]

It wouldn't be an Ad Agent if we didn't throw in a little VPI -- let's equip our agent to be able to value the missing traits of any consumers it may be advertising to.

  def vpi(self, potential_evidence: str, observed_evidence: dict[str, int]) -> float:
      """
      Given some observed demographic "evidence" about a potential
      consumer, returns the Value of Perfect Information (VPI)
      that would be received on the given "potential" evidence about
      that consumer.
      
      Parameters:
          potential_evidence (str):
              string representing the variable name of the variable 
              under consideration for potentially being obtained
          observed_evidence (tuple[dict[str, int], float]):
              dict mapping network variables 
              to their observed values, of the format: 
              {"Obs1": val1, "Obs2": val2, ...}
      
      Returns:
          float:
              float value indicating the VPI(potential | observed)
      """

Some notes:

  • Believe it or not, this one should be pretty simple once you've got the MEU working -- just remember the VPI definition / equation and how there are different formats of the MEU computation inside.

  • Recall some important properties about VPI that will patch some edge cases (namely: information can never be harmful)

To run some of the sample unit tests, execute pytest -k vpi


[Price is Right]

GenAI use for the entirety of this problem is allowed! This portion is sophisticated enough such that, even if you choose to use GenAI, you will still need to develop your own planned steps for playing the Price Is Right game, just use GenAI to save you keystrokes when appropriate.


I sure hope I don't get sued for this part... or worse... haunted by Bob Barker.

Nonetheless, it's time to play some CMSI 3300 Price is Right! The game show where your sole duty is to determine, based on some fictitious customer data, whether or not you should pay some third party for access to their various traits.

Think this is a weird problem? It's actually what entire industries make their buck on! See, e.g., Axciom and definitely social media groups like Meta!

You'll have a chance to rebut this practice in a moment, but for now, it pays (heh) to know how it might be done.

OUR Price is Right game will be played as follows:

  1. Some fictitious customer data on a given Decision Network will be generated over N customers.

  2. Some of those customers' traits (like their political leaning) will be unknown / ablated / hidden.

  3. You will be given a dictionary of how much (in bulk, i.e., paying only once like for a service) each variable would be to buy for all customers in your sales group (i.e., the fake customers fed as input).

  4. You must decide which customer trait variables (if any) should be purchased!

Assuming the previous sections of this assignment have been completed correctly, you can run python price_is_right.py to run the demo and see some data like:

  Variable prices:
  {'P': 15.0, 'A': 20.0, 'H': 10.0, 'I': 25.0, 'T': 12.0, 'F': 18.0, 'G': 22.0}
  
  True customers (complete data):
     F  T  P  I  G  H  A
  0  1  1  0  1  0  1  1
  1  1  0  1  0  1  1  1
  2  0  1  1  1  1  0  0
  3  1  1  0  1  1  1  1
  4  1  1  0  1  1  1  1
  5  1  1  0  1  1  1  1
  6  0  1  0  0  0  1  1
  7  1  0  1  1  1  1  1
  8  1  1  0  0  1  0  0
  9  0  1  0  0  1  0  0
  
  Ablated customers (missing some data):
       F    T    P    I    G    H    A
  0  1.0  1.0  0.0  NaN  0.0  1.0  1.0
  1  1.0  0.0  1.0  0.0  1.0  1.0  1.0
  2  0.0  1.0  1.0  1.0  1.0  NaN  0.0
  3  NaN  1.0  NaN  1.0  NaN  1.0  1.0
  4  1.0  NaN  NaN  1.0  NaN  NaN  NaN
  5  NaN  NaN  0.0  1.0  1.0  NaN  1.0
  6  0.0  1.0  NaN  0.0  NaN  1.0  NaN
  7  1.0  0.0  1.0  1.0  1.0  1.0  1.0
  8  NaN  1.0  0.0  0.0  1.0  0.0  0.0
  9  0.0  1.0  NaN  0.0  NaN  NaN  0.0
  
  If your agent chooses to buy, e.g., ["T"], that data for all of your customers
  would be revealed:
       F    T    P    I    G    H    A
  0  1.0  1.0  0.0  NaN  0.0  1.0  1.0
  1  1.0  0.0  1.0  0.0  1.0  1.0  1.0
  2  0.0  1.0  1.0  1.0  1.0  NaN  0.0
  3  NaN  1.0  NaN  1.0  NaN  1.0  1.0
  4  1.0  1.0  NaN  1.0  NaN  NaN  NaN
  5  NaN  1.0  0.0  1.0  1.0  NaN  1.0
  6  0.0  1.0  NaN  0.0  NaN  1.0  NaN
  7  1.0  0.0  1.0  1.0  1.0  1.0  1.0
  8  NaN  1.0  0.0  0.0  1.0  0.0  0.0
  9  0.0  1.0  NaN  0.0  NaN  NaN  0.0

Your task: determine whether or not all of the juice (each variable) is worth the squeeze (the price being asked) using your decision network!

You'll implement this in the following method:

  def information_order(self, customer_data: "pd.DataFrame", variable_prices: dict[str, float], 
                       available_cash: float, customer_vars: set[str]) -> list[str]:
      """
      Determines the variables to purchase based on customer data, prices, and available cash.
      This method is called by the PriceIsRightGame exactly once, so any purchase orders can only happen a single time.
      
      Parameters:
          customer_data (pd.DataFrame):
              DataFrame containing customer profiles (may have missing values represented as NaN)
          variable_prices (dict[str, float]):
              Dictionary mapping variable names to their reveal prices
          available_cash (float):
              Total amount of cash available for purchasing information
          customer_vars (set[str]):
              Set of customer variable names that can be purchased
      
      Returns:
          list[str]:
              List of variable names to purchase.
              The list should contain only variables that can be afforded with the available cash,
              and may either be empty or contain a subset of the customer_vars.
      """
      # TODO: Problem 6!
      return []

Plainly, some methods from your Decision Network should be valuable here, but beware! Ensure you have re-read all of Week 6's lecture notes, especially when considering to purchase multiple variables!

Once you're confident in your information_order implementation, run pytest price_is_right_skeleton_tests.py, though per usual, this will only be a sample of the grading tests! Think carefully about edge cases here!


[AdTech Ethics]

Ever wondered what data companies have about you? You can take a (very high-level) look at some of your ad preferences if you're signed up with a Google account or other social networks like:

Google Ad Center

Facebook Ad Center

Instagram Ad Preferences


I do two things well: higher ed, and high-stakes Texas Hold'em (I actually have no idea why gambling [aka "Real Money Gaming"] was #1)


As an individual:

  1. Look up your ad preferences on at least one service (if any of the above apply to you -- I think everyone has to have at least Google?).

  2. Write down a sentence or two in reflection about: whether or not you were surprised by the ad preferences assigned to you and for any that were inaccurate, how you think those came to be? (you'll be adding these musings to your report so don't write anything here you wouldn't want shared!)

In your report (in several sentences each):

  1. Collect all group members' individual musings on their ad preferences from the previous step and log these in the report.

  2. As a group (or just yourself if you're working solo), make an argument for whether or not you believe it to be ethical for companies to sell this data for the purposes of targeted advertising.

  3. Repeat the previous problem, but for the purpose of targeted *political* advertising.



Hints

  • Although given a motivating example in the Defendotron setting, your solution should operate correctly for whatever properly formatted data-file, decision variables, and utility maps are provided to the AdEngine constructor [hint: make sure it works for multi-valued variables]!

  • Once again, you'll likely find the itertools package very useful in many of the above.

  • Not confident in your answer? Construct some simple DN's top-down like the ones we've done in class and compare your solution's answers to ours. I've given one such dataset in the lecture5-2-data.csv that emulates the web-dev interface selector decision network from Lecture 5-2.

  • Test as a community! Although you shouldn't be sharing code, you can certainly share cases and datasets (which you can generate via Tetrad's simulation module if you please).



Testing & Grading

I've given you *most* of the unit tests to validate your AdEngine, but you should make a few of your own to make sure the methods work as intended!

  pytest ad_agent_skeleton_tests.py         # Worth 70% of the assignment grade
  pytest price_is_right_skeleton_tests.py   # Worth 30% of the assignment grade
  mypy .                                    # Small penalty if non-compliant

Failing any tests in the set of full grading tests will yield partial credit, usually at the cost of -3/-4 per missed test depending on the class average.

Having syntax errors in any part of the above will yield a 0 for the assignment.

Read the spec carefully and make sure that your report contains all requested information; missing sections will be penalized.



Submission

You will be submitting your assignments through PostCommit!

What

Complete all classes that accomplishes the specification above, in the project structure given in the skeleton above.


How

To clone this assignment (if you need a refresher), consult the guide here:

PostCommit Tutorial

To submit this assignment:

  • Simply push your final, submission copy to the PostCommit repository associated with you or your group.

  • If you worked in a group (3 individuals maximum), ensure that your PostCommit group includes all members, and place all group members' names at the top of *all* modified files (in appropriate commenting fashion) AND THE README.md in the project directory.



  PDF / Print