Due: Thursday, October 2, 2014 11:59 PM
To submit your homework, create a folder named lastname_firstinitial_hw# and place your IPython notebooks, data files, and any other files in this folder. Your IPython Notebooks should be completely executed with the results visible in the notebook. We should not have to run any code. Compress the folder (please use .zip compression) and submit to the CS109 dropbox in the appropriate folder. If we cannot access your work because these directions are not followed correctly, we will not grade your work.
John Tukey wrote in Exploratory Data Analysis, 1977: "The greatest value of a picture is when it forces us to notice what we never expected to see." In this assignment we will continue using our exploratory data analysis tools, but apply it to new sets of data: gene expression and polls from the 2012 Presidental Election and from the 2014 Senate Midterm Elections.
First: You will use exploratory data analysis and apply the singular value decomposition (SVD) to a gene expression data matrix to determine if the the date that the gene expression samples are processed has large effect on the variability seen in the data.
Second: You will use the polls from the 2012 Presidential Elections to determine (1) Is there a pollster bias in presidential election polls? and (2) Is the average of polls better than just one poll?
Finally: You will use the HuffPost Pollster API to extract the polls for the current 2014 Senate Midterm Elections and provide a preliminary prediction of the result of each state.
We will use the following data sets:
A gene expression data set called exprs_GSE5859.csv
and sample annotation table called sampleinfo_GSE5859.csv
which are both available on Github in the 2014_data repository: expression data set and sample annotation table.
Polls from the 2012 Presidential Election: Barack Obama vs Mitt Romney. The polls we will use are from the Huffington Post Pollster.
Polls from the 2014 Senate Midterm Elections from the HuffPost Pollster API.
# special IPython command to prepare the notebook for matplotlib
%matplotlib inline
import requests
from StringIO import StringIO
import numpy as np
import pandas as pd # pandas
import matplotlib.pyplot as plt # module for plotting
import datetime as dt # module for manipulating dates and times
import numpy.linalg as lin # module for performing linear algebra operations
In this problem we will be using a gene expression data set obtained from a microarray experiement Read more about the specific experiment here. There are two data sets we will use:
The gene expression intensities where the rows represent the features on the microarray (e.g. genes) and the columsns represent the different microarray samples.
A table that contains the information about each of the samples (columns in the gene expression data set) such as the sex, the age, the treatment status, the date the samples were processed. Each row represents one sample.
Read in the two files from Github: exprs_GSE5859.csv and sampleinfo_GSE5859.csv as pandas DataFrames called exprs
and sampleinfo
. Use the gene names as the index of the exprs
DataFrame.
#your code here
Make sure the order of the columns in the gene expression DataFrame match the order of file names in the sample annotation DataFrame. If the order of the columns the exprs
DataFrame do not match the order of the file names in the sampleinfo
DataFrame, reorder the columns in the exprs
DataFrame.
Note: The column names of the gene expression DataFrame are the filenames of the orignal files from which these data were obtained.
Hint: The method list.index(x)
[read here] can be used to return the index in the list of the first item whose value is x. It is an error if there is no such item. To check if the order of the columns in exprs
matches the order of the rows in sampleinfo
, you can check using the method .all()
on a Boolean or list of Booleans:
Example code: (exprs.columns == sampleinfo.filename).all()
#your code here
Show the head of the two tables: exprs
and sampleinfo
.
#your code here
Extract the year and month as integers from the sampleinfo
table.
Hint: To convert a Series or a column of a pandas DataFrame that contains a date-like object, you can use the to_datetime
function [read here]. This will create a DatetimeIndex
which can be used to extract the month and year for each row in the DataFrame.
#your code here
Convert the dates in the date
column from the sampleinfo
table into days since October 31, 2002. Add a column to the sampleinfo
DataFrame titled elapsedInDays
containing the days since October 31, 2002. Show the head of the sampleinfo
DataFrame which includes the new column.
Hint: Use the datetime
module to create a new datetime
object for the specific date October 31, 2002. Then, subtract the October 31, 2002 date from each date from the date
column in the sampleinfo
DataFrame.
#your code here
Use exploratory analysis and the singular value decomposition (SVD) of the gene expression data matrix to determine if the date the samples were processed has large effect on the variability seen in the data or if it is just ethnicity (which is confounded with date).
Hint: See the end of the lecture from 9/23/2014 for help with SVD.
First subset the the sampleinfo
DataFrame to include only the CEU ethnicity. Call this new subsetted DataFrame sampleinfoCEU
. Show the head of sampleinfoCEU
DataFrame.
#your code here
Next, subset the exprs
DataFrame to only include the samples with the CEU ethnicity. Name this new subsetted DataFrame exprsCEU
. Show the head of the exprsCEU
DataFrame.
#your code here
Check to make sure the order of the columns in the exprsCEU
DataFrame matches the rows in the sampleinfoCEU
DataFrame.
#your code here
Compute the average gene expression intensity in the exprsCEU
DataFrame across all the samples. For each sample in the exprsCEU
DataFrame, subtract the average gene expression intensity from each of the samples. Show the head of the mean normalized gene expression data.
#your code here
Using this mean normalized gene expression data, compute the projection to the first Principal Component (PC1).
Hint: Use the numpy.linalg.svd()
function in the numpy.linalg
module (or the scipy.linalg.svd()
function in the scipy.linalg
module) to apply an singular value decomposition to a matrix.
#your code here
Create a histogram using the values from PC1. Use a bin size of 25.
#your code here
Create a scatter plot with the days since October 31, 2002 on the x-axis and PC1 on the y-axis.
#your code here
Around what day do you notice a difference in the way the samples were processed?
#your code here
Answer:
Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.
The HuffPost Pollster contains many political polls. You can access these polls from individual races as a CSV but you can also access polls through the HuffPost Pollster API to access the data.
Read in the polls from the 2012 Presidential Election: Barack Obama vs Mitt Romney into a pandas DataFrame called election
. For this problem, you may read in the polls for this race directly using the CSV file available from the HuffPost Pollster page.
#your code here
Show the head of the election
DataFrame.
#your code here
How many polls were conducted in November? Define this number as M.
Hint: Subset the election
DataFrame for only dates in the Start Date
column that are in November 2012.
#your code here
Answer:
What was the median of the number of observations in the November polls? Define this quantity as N.
#your code here
Answer:
Using the median sample size $N$ from Problem 1(a), simulate the results from a single poll: simulate the number of votes for Obama out of a sample size $N$ where $p$ = 0.53 is the percent of voters who are voting for Obama.
Hint: Use the binomial distribution with parameters $N$ and $p$ = 0.53.
#your code here
Now, perform a Monte Carlo simulation to obtain the estimated percentage of Obama votes with a sample size $N$ where $N$ is the median sample size calculated in Problem 2(a). Let $p$=0.53 be the percent of voters are voting for Obama.
Hint: You will repeat the simulation above 1,000 times and plot the distribution of the estimated percent of Obama votes from a single poll. The results from the single poll you simulate is random variable and will be different every time you sample.
#your code here
Plot the distribution of the estimated percentage of Obama votes from your single poll. What is the distribution of the estimated percentage of Obama votes?
#your code here
Answer:
What is the standard error (SE) of the estimated percentage from the poll.
Hint: Remember the SE is the standard deviation (SD) of the distribution of a random variable.
#your code here
Now suppose we run M polls where M is the number of polls that happened in November (calculated in Problem 2(a)). Run 1,000 simulations and compute the mean of the M polls for each simulation.
#your code here
What is the distribution of the average of polls?
Hint: Show a plot.
#your code here
Answer:
What is the standard error (SE) of the average of polls?
#your code here
Answer:
Is the SE of the average of polls larger, the same, or smaller than that the SD of a single poll (calculated in Problem 2(b))? By how much?
Hint: Compute a ratio of the two quantities.
#your code here
Answer:
Repeat Problem 2(c) but now record the across poll standard deviation in each simulation.
#your code here
What is the distribution of the across M polls standard deviation?
Hint: Show a plot.
#your code here
Answer:
What is the standard deviation of M polls in our real (not simulated) 2012 presidential election data ?
#your code here
Is this larger, the same, or smaller than what we expeced if polls were not biased.
#your code here
Answer:
For AC209 Students: Learn about the normal approximation for the binomial distribution and derive the results of Problem 2(b) and 2(c) analytically (using this approximation). Compare the results obtained analytically to those obtained from simulations.
#your code here
Answer:
Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.
Most undecided voters vote for one of the two candidates at the election. Therefore, the reported percentages underestimate the final value of both candidates. However, if we assume the undecided will split evenly, then the observed difference should be an unbiased estimate of the final difference.
Add a new column to the election
DataFrame containg the difference between Obama and Romeny called Diff
.
#your code here
Make a plot of the differences for the week before the election (e.g. 5 days) where the days are on the x-axis and the differences are on the y-axis. Add a horizontal line showing 3.9%: the difference between Obama and Romney on election day.
#your code here
Make a plot showing the differences by pollster where the pollsters are on the x-axis and the differences on the y-axis.
#your code here
Is the across poll difference larger than the between pollster difference?
Answer:
Take the average for each pollster and then compute the average of that. Given this difference how confident would you have been of an Obama victory?
Hint: Compute an estimate of the SE of this average based exclusively on the observed data.
#your code here
Answer:
For AC209 Students: Show the difference against time and see if you can detect a trend towards the end. Use this trend to see if it improves the final estimate.
#your code here
Answer:
Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.
In this last problem, we will use the polls from the 2014 Senate Midterm Elections from the HuffPost Pollster API to create a preliminary prediction of the result of each state.
The HuffPost Pollster API allows you to access the data as a CSV or a JSON response by tacking ".csv" or ".json" at the end of the URLs. For example the 2012 Presidential Election could be accessed as a .json instead of a .csv
Read in the polls for all of the 2014 Senate Elections using the HuffPost API. For example, we can consider the 2014 Senate race in Kentucky between Mitch McConnell and Alison Grimes.
To search for the 2014 Senate races, use the topics
parameter in the API [read more about topics here].
url_str = "http://elections.huffingtonpost.com/pollster/api/charts/?topic=2014-senate"
To list all the URLs related to the 2014 Senate races using the pollster API, we can use a list comprehension:
election_urls = [election['url'] + '.csv' for election in requests.get(url_str).json()]
election_urls
[u'http://elections.huffingtonpost.com/pollster/2014-kentucky-senate-mcconnell-vs-grimes.csv', u'http://elections.huffingtonpost.com/pollster/2014-arkansas-senate-cotton-vs-pryor.csv', u'http://elections.huffingtonpost.com/pollster/2014-michigan-senate-land-vs-peters.csv', u'http://elections.huffingtonpost.com/pollster/2014-louisiana-senate-cassidy-vs-landrieu.csv', u'http://elections.huffingtonpost.com/pollster/2014-new-hampshire-senate-brown-vs-shaheen.csv', u'http://elections.huffingtonpost.com/pollster/2014-west-virginia-senate-capito-vs-tennant.csv', u'http://elections.huffingtonpost.com/pollster/2014-new-hampshire-senate-bass-vs-shaheen.csv', u'http://elections.huffingtonpost.com/pollster/2014-north-carolina-senate-tillis-vs-hagan.csv', u'http://elections.huffingtonpost.com/pollster/2014-virginia-senate-gillespie-vs-warner.csv', u'http://elections.huffingtonpost.com/pollster/2014-colorado-senate-gardner-vs-udall.csv', u'http://elections.huffingtonpost.com/pollster/2014-illinois-senate-oberweis-vs-durbin.csv', u'http://elections.huffingtonpost.com/pollster/2014-alaska-senate-sullivan-vs-begich.csv', u'http://elections.huffingtonpost.com/pollster/2014-iowa-senate-ernst-vs-braley.csv', u'http://elections.huffingtonpost.com/pollster/2014-mississippi-senate-cochran-vs-childers.csv', u'http://elections.huffingtonpost.com/pollster/2014-oregon-senate-wehby-vs-merkley.csv', u'http://elections.huffingtonpost.com/pollster/2014-georgia-senate-perdue-vs-nunn.csv', u'http://elections.huffingtonpost.com/pollster/2014-louisiana-senate-sasse-vs-domina.csv', u'http://elections.huffingtonpost.com/pollster/2014-south-dakota-senate-rounds-vs-weiland.csv', u'http://elections.huffingtonpost.com/pollster/2014-maine-senate-collins-vs-bellows.csv', u'http://elections.huffingtonpost.com/pollster/2014-minnesota-senate-mcfadden-vs-franken.csv', u'http://elections.huffingtonpost.com/pollster/2014-texas-senate-cornyn-vs-alameel.csv', u'http://elections.huffingtonpost.com/pollster/2014-south-carolina-senate-graham-vs-hutto.csv', u'http://elections.huffingtonpost.com/pollster/2014-south-carolina-senate-scott-vs-dickerson.csv', u'http://elections.huffingtonpost.com/pollster/2014-oklahoma-senate-inhofe-vs-silverstein.csv', u'http://elections.huffingtonpost.com/pollster/2014-new-mexico-senate-weh-vs-udall.csv', u'http://elections.huffingtonpost.com/pollster/2014-new-jersey-senate-bell-vs-booker.csv', u'http://elections.huffingtonpost.com/pollster/2014-idaho-senate-risch-vs-mitchell.csv', u'http://elections.huffingtonpost.com/pollster/2014-tennessee-senate-alexander-vs-ball.csv', u'http://elections.huffingtonpost.com/pollster/2014-wyoming-senate.csv', u'http://elections.huffingtonpost.com/pollster/2014-kansas-senate-roberts-vs-orman-vs-taylor.csv', u'http://elections.huffingtonpost.com/pollster/2014-hawaii-senate-cavasso-vs-schatz.csv', u'http://elections.huffingtonpost.com/pollster/2014-oklahoma-senate-lankford-vs-johnson.csv', u'http://elections.huffingtonpost.com/pollster/2014-montana-senate-daines-vs-curtis.csv', u'http://elections.huffingtonpost.com/pollster/2014-rhode-island-senate-zaccaria-vs-reed.csv', u'http://elections.huffingtonpost.com/pollster/2014-massachusetts-senate-herr-vs-markey.csv', u'http://elections.huffingtonpost.com/pollster/2014-delaware-senate-wade-vs-coons.csv']
Because there so many Senate races, we can create a dictionary of pandas DataFrames that will be keyed by the name of the election (a string).
def build_frame(url):
"""
Returns a pandas DataFrame object containing
the data returned from the given url
"""
source = requests.get(url).text
# Use StringIO because pd.DataFrame.from_csv requires .read() method
s = StringIO(source)
return pd.DataFrame.from_csv(s, index_col=None).convert_objects(
convert_dates="coerce", convert_numeric=True)
# Makes a dictionary of pandas DataFrames keyed on election string.
dfs = dict((election.split("/")[-1][:-4], build_frame(election)) for election in election_urls)
Show the head of the DataFrame containing the polls for the 2014 Senate race in Kentucky between McConnell and Grimes.
#your code here
For each 2014 Senate race, create a preliminary prediction of the result for that state.
#your code here
To submit your homework, create a folder named lastname_firstinitial_hw# and place your IPython notebooks, data files, and any other files in this folder. Your IPython Notebooks should be completely executed with the results visible in the notebook. We should not have to run any code. Compress the folder (please use .zip compression) and submit to the CS109 dropbox in the appropriate folder. If we cannot access your work because these directions are not followed correctly, we will not grade your work.