xub <- read.csv("https://remiller1450.github.io/data/xubball2021.csv")
xub$win <- ifelse(xub$Margin > 0, 1, 0)33 Logistic Regression Practice
34 Practice Problems
34.1 Getting an A
Suppose we collect data for a group of students in a statistics class with variables \(X_1 =\) hours studied, \(X_2 =\) undergrad GPA, and \(Y =\) receive an A. We fit a logistic regression and produce estimated coefficient, \(\hat{\beta}_0 = −6\), \(\hat{\beta}_1 = 0.05\), \(\hat{\beta}_2 = 1\).
Estimate the probability that a student who studies for 40 h and has an undergrad GPA of 3.5 gets an A in the class.
How many hours would the student in part (a) need to study to have a 50% chance of getting an A in the class?
34.2 Men’s Basketball
The code below reads the Xavier men’s basketball 20-21 team game results and creates a dummy variable “win” that takes the numeric value of 1 if XU outscored their opponent and 0 otherwise. In this application we’ll use logistic regression to model wins/losses.
Fit the logistic regression model
win ~ X3P, which predicts whether a game was won or lost based upon the number of made 3-point shots. How does the number of made 3-point shots impact the odds of Xavier winning? Is the effect of “3XP” statistically meaningful?Fit the logistic regression model
win ~ X3P + X3P., which adjusts for the percentage of three point attempts that are made. How does the effect of “3XP” in this model differ from the effect you described in the previous question? Briefly explain why the adjusted effect is so different from the unadjusted effect.Use a likelihood ratio test to compare the two models described in (a) and (b). Does the test provide statistically compelling evidence that the larger model provides a better fit?
34.3 Spam Filter
Classifying emails as “spam” is a classical data-science application that involves modeling a binary outcome. The following questions will use the spam dataset contained in the kernlab package, which contains a sample of 4601 emails that were manually labeled as either “spam” or “nonspam” (recorded as the variable “type”), along with various predictors that describe the normalized frequencies of certain words/symbols within each email message. We will focus on the following predictors:
“capitalAve” - The average number of capitalized letters (per sentence) contained in the email.
“charDollar” - The normalized frequency of the dollar sign character
“charExclamation” - The normalized frequency of the exclamation point character
#install.packages("kernlab")
library(kernlab)
data("spam")
table(spam$type)
nonspam spam
2788 1813
Use boxplots to show the distribution of each of the three variables listed above in “spam” and “nonspam” emails. Based upon a visual inspection of these plots, which variable appears to be the strongest predictor of an email being “spam”? (Hint: Your choie of predictor is somewhat subjective, but try “zooming in” on your boxplots using the “xlim” or “ylim” arguments to help you make your selection)
Fit a logistic regression model that uses the variable you chose in (a) to predict “spam”. Then, use this model to intpret the effect of this variable on the odds of an email being “spam”.
Create a graph that displays the expected probability, along with 90% confidence intervals, of an email being spam in response to the predictor you identified in Question #13. (Hint: this graph should resemble the ones from the “Confidence and Prediction Intervals” section)
34.4 Paying Dividentds
Suppose that we wish to predict whether a given stock will issue a dividend this year (“Yes” or “No”) based on \(X\), last year’s percent profit. We examine a large number of companies and discover that the mean value of $X$ for companies that issued a dividend was \(\bar{X} = 10\), while the mean for those that didn’t was \(\bar{X} = 0\). In addition, the variance of \(X\) for these two sets of companies was \(\hat{\sigma}^2 = 36\). Finally, 80% of companies issued dividends. Assuming that \(X\) follows a normal distribution, predict the probability that a company will issue a dividend this year given that its percentage profit was \(X = 4\) last year.
34.5 Odds
This problem has to do with odds.
On average, what fraction of people with an odds of 0.37 of defaulting on their credit card payment will in fact default?
Suppose that an individual has a 16% chance of defaulting on her credit card payment. What are the odds that she will default?
34.6 Weekly
This question should be answered using the Weekly data set, which is part of the ISLR2 package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.
Produce some numerical and graphical summaries of the
Weeklydata. Do there appear to be any patterns?Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus
Volumeas predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.
Now fit the logistic regression model using a training data period from 1990 to 2008, with
Lag2as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).Experiment with different combinations of predictors, including possible transformations and interactions. Report the variables and associated confusion matrix that appears to provide the best results on the held out data.
34.7 Logistic Auto
In this problem, you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.
Create a binary variable,
mpg01, that contains a 1 ifmpgcontains a value above its median, and a 0 ifmpgcontains a value below its median. You can compute the median using themedian()function. Note you may find it helpful to use thedata.frame()function to create a single data set containing bothmpg01and the otherAutovariables.Explore the data graphically in order to investigate the association between
mpg01and the other features. Which of the other features seem most likely to be useful in predictingmpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.Split the data into a training set and a test set.
Perform logistic regression on the training data in order to predict
mpg01using the variables that seemed most associated withmpg01in (b). What is the test error of the model obtained?
34.8 Boston Logistic
Using the Boston data set, fit classification models in order to predict whether a given census tract has a crime rate above or below the median. Explore logistic regression and describe your findings.
Hint: You will have to create the response variable yourself, using the variables that are contained in the Boston data set. # Beyond STAT 340
These problems are excellent practice but they are beyond the material we cover in STAT 340.
34.9 Function Practice
This problem involves writing functions.
- Write a function,
Power(), that prints out the result of raising 2 to the 3rd power. In other words, your function should compute \(2^3\) and print out the results.
Hint: Recall that x^a raises x to the power a. Use the print() function to output the result.
- Create a new function,
Power2(), that allows you to pass any two numbers,xanda, and prints out the value ofx^a. You can do this by beginning your function with the line
Power2 <- function(x, a){}
You should be able to call your function by entering, for instance, Power2(3,8) on the command line. This should output the value of \(3^8\), namely, 6,561.
Using the
Power2()function that you just wrote, compute \(10^3\), \(8^{17}\), and \(131^3\).Now create a new function,
Power3(), that actually returns the resultx^aas an R object, rather than simply printing it to the screen. That is, if you store the value x^a in an object called result within your function, then you can simplyreturn()this result, using the following line:
return(result)
The line above should be the last line in your function, before the } symbol.
Now using the Power3() function, create a plot of \(f(x) = x^2\). The \(x\)-axis should display a range of integers from 1 to 10, and the y-axis should display \(x^2\). Label the axes appropriately, and use an appropriate title for the figure. Consider displaying either the \(x\)-axis, the \(y\)-axis, or both on the log-scale. You can do this by using
log = "x",log = "y", orlog = "xy"as arguments to theplot()function.Create a function,
PlotPower(), that allows you to create a plot ofxagainstx^afor a fixedaand for a range of values ofx. For instance, if you callPlotPower(1:10, 3)then a plot should be created with an \(x\)-axis taking on values \(1, 2, \ldots , 10\), and a \(y\)-axis taking on values \(1^3, 2^3, \ldots , 10^3\).