Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Question 1: Using a little bit of algebra, prove that (4.2) is equivalent to (4.3). In other words, the logistic function representation and logit representation for the logistic regression model are equivalent. Solution: Equation 4.2 in textbook is π(π₯) = π(π₯) 1βπ(π₯) = = π π½0+π½1 1+ π π½0+π½1 π½0 +π½1 β (π ) 1+ π π½0+π½1 (π π½0+π½1β 1β ) 1+ π π½0+π½1 π½0 +π½1 β (π ) 1+ π π½0+π½1 (1+π π½0+π½1 βπ π½0 +π½1β ) 1+ π π½0+π½1 = π π½0 +π½1 Therefore, Hence Proved that Logistic Function representation and Logit representation are equivalent. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Question 2: It was stated in the text that classifying an observation to the class for which (4.12) is largest is equivalent to classifying an observation to the class for which (4.13) is largest. Prove that this is the case. In other words, under the assumption that the observations in the kth class are drawn from a N(ΞΌk, Ο2) distribution, the Bayesβ classifier assigns an observation to the class for which the discriminant function is maximized. Solution: In the Linear Discriminant Analysis for p=1, Take log on the both sides for the equation ππ (x) in 4.12 and rearrange the terms, Log ππ (x) = Log( 2 (π₯βππ ) 1 ππ ππ₯π(β ) 2π2 β2ππ 2 (π₯βππ ) 1 π βπ=1 ππ ππ₯π(β ) 2π2 β2ππ = Log( 2 (π₯βππ ) ππ ππ₯π(β ) 2π2 2 (π₯βππ ) π βπ=1 ππ ππ₯π(β ) 2π2 ) ) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R (π₯βππ )2 = πππ (ππ ππ₯π (β )) 2π 2 πππ (βππ=1 ππ ππ₯π (β (π₯βππ )2 2π 2 )) As We know the formula (log(a/b) = log(a) β log(b)) Denominator is going to be the same for all classes as the variance π1 2 = β¦β¦β¦.. = ππ 2 as assumed. Which is a variance term shared across all K classes is same. Last term is independent of k, So we exclude that (π₯ β ππ )2 = πΏππ (ππ ππ₯π (β )) 2π 2 = Log(ππ ) + πΏπππ (π β(π₯βππ )2 2π2 (As log(ab)= log(a) + log(b)) = Log(ππ ) - (π₯βππ )2 2π 2 ) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R (π₯ 2 β2π₯ππ +ππ 2 ) = Log(ππ ) 2π 2 = Log(ππ ) - (π₯ 2 ) 2π 2 + 2π₯ππ 2π 2 - ππ 2 2π 2 The term π₯ 2 in the above equation is independent of k, so we can exclude it and we will find k as πππ(ππ ) + π₯ππ π2 - ππ 2 2π 2 Question 3: This problem relates to the QDA model, in which the observations within each class are drawn from a normal distribution with a class specific mean vector and a class specific covariance matrix. We consider the simple case where p = 1; i.e. there is only one feature. Suppose that we have K classes, and that if an observation belongs to the kth class then X comes from a one-dimensional normal distribution, X βΌ N(ΞΌk, ππ 2 ). Recall that the density function for the one-dimensional normal distribution is given in (4.11). Prove that in this case, the Bayesβ classifier is not linear. Argue that it is in fact quadratic. Hint: For this problem, you should follow the arguments laid out in Section 4.4.2, but without making the assumption that π1 2 = β¦β¦β¦.. = ππ 2 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Solution: The solution is same as the above problem but we cannot skip π₯ 2 term as ππ 2 varies across classes. So we find k using the term Log(ππ ) - (π₯ 2 ) 2π 2 + 2π₯ππ 2π 2 - ππ 2 2π 2 Question 4: When the number of features p is large, there tends to be a deterioration in the performance of KNN and other local approaches that perform prediction using only observations that are near the test observation for which a prediction must be made. This phenomenon is known as the curse of dimensionality, and it ties into the fact that curse of dinon-parametric approaches often perform poorly when p is large. We mensionality will now investigate this curse. (a) Suppose that we have a set of observations, each with measurements on p = 1 feature, X. We assume that X is uniformly (evenly) distributed on [0, 1]. Associated with each observation is a response value. Suppose that we wish to predict a test observationβs response using only observations Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R that are within 10 % of the range of X closest to that test observation. For instance, in order to predict the response for a test observation with X = 0.6, we will use observations in the range [0.55, 0.65]. On average, what fraction of the available observations will we use to make the prediction? Solution: Given there are some set of observations, with p=1. X is uniformly distributed on [0,1] There is a response value associated with each observation. To predict response for a test observation, with X=0.6, use observations in range [0.55,0.65] To predict response for a test observation, with X=0.1, use observations in range [0.05,0.15] To predict response for a test observation, with X=0.01, use observations in range [0.005,0.015] To predict response for a test observation, with X=0.95, use observations in range [0.90,1] To predict response for a test observation, with X=0.99, use observations in range [0.94,1.04] 10% of observations from interval of length 1 fall into interval of length 0.1 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R 50+5(0.1) = 50.5 f(x) = 50+5x, when 0<x<0.1 = 10, when 0.1<= x<= 0.9 = 10-50x, when 0.9<x<=1 We use 9% of observations to make the prediction. b) Now suppose that we have a set of observations, each with measurements on p = 2 features, X1 and X2. We assume that (X1, X2) are uniformly distributed on [0, 1] × [0, 1]. We wish to predict a test observationβs response using only observations that are within 10 % of the range of X1 and within 10 % of the range of X2 closest to that test observation. For instance, in order to predict the response for a test observation with X1 = 0.6 and X2 = 0.35, we will use observations in the range [0.55, 0.65] for X1 and in the range [0.3, 0.4] for X2. On average, what fraction of the available observations will we use to make the prediction? Solution: π1 , π2 are the two observations Which are uniformly distributed on [0,1] X [0,1] Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R As we take 9% of observations to make prediction in this case, answer is 9% X 9% = 0.81% As there are two observations here π1 , π2 . c) Now suppose that we have a set of observations on p = 100 features. Again the observations are uniformly distributed on each feature, and again each feature ranges in value from 0 to 1. We wish to predict a test observationβs response using observations within the 10 % of each featureβs range that is closest to that test observation. What fraction of the available observations will we use to make the prediction? Solution: Given p= 100, Observations are uniformly distributed, features ranges from 0 to 1. We predict test observations response using observations with in 10% of each featureβs range closest to that test observation. 9% to the power of 100 = (0.09)100 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R d) Using your answers to parts (a)β(c), argue that a drawback of KNN when p is large is that there are very few training observations βnearβ any given test observation. Solution: We use 90% of data to classify that point. Given a point in 2 dimensions, We use 90%^2 = 0.81% of the data near that point. When the dimensions are increased, we exponentially reduce the number of observations near the point in consideration. The drawback of knn is when p is large, there will be few training observations. e) Now suppose that we wish to make a prediction for a test observation by creating a p-dimensional hypercube centered around the test observation that contains, on average, 10 % of the training observations. For p = 1, 2, and 100, what is the length of each side of the hypercube? Comment on your answer. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Note: A hypercube is a generalization of a cube to an arbitrary number of dimensions. When p = 1, a hypercube is simply a line segment, when p = 2 it is a square, and when p = 100 it is a 100-dimensional cube Solution: The length of the each side of the hypercube 0.09 Question 5: We now examine the differences between LDA and QDA. (a) If the Bayes decision boundary is linear, do we expect LDA or QDA to perform better on the training set? On the test set? Solution: If Bayes decision boundary is linear, We expect QDA to perform better on training set because of its higher flexibility yield a closer fit. LDA to perform better than QDA because QDA would overfit linearity on the Bayes decision theory on the test set. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R b) If the Bayes decision boundary is non-linear, do we expect LDA or QDA to perform better on the training set? On the test set? Solution: QDA to perform better both on training, test sets. c) In general, as the sample size n increases, do we expect the test prediction accuracy of QDA relative to LDA to improve, decline, or be unchanged? Why? Solution: If training set is very large, QDA is more flexible than LDA and has higher variance. d) True or False: Even if the Bayes decision boundary for a given problem is linear, we will probably achieve a superior test error rate using QDA rather than LDA because QDA is flexible enough to model a linear decision boundary. Justify your answer. Solution: With fewer sample points, variance from using QDA, lead to overfit, leads to inferior test error rate. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Question 6: Suppose we collect data for a group of students in a statistics class with variables π1 = hours studied, π2 = undergrad GPA, and Y = receive an A. We fit a logistic regression and produce estimated coefficient, π½Μ0 = β6, π½Μ1 = 0.05, π½Μ2 = 1. (a) 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. (b) How many hours would the student in part (a) need to study to have a 50 % chance of getting an A in the class? Solution: Given π1 = hours studied π2 = undergrad GPA Y = receive an A π½Μ0 = β6, π½Μ1 = 0.05, π½Μ2 = 1 a) Given π1 = 40 hours, GPA = 3.5 ππ (x) = = Μ Μ π π½0+ π½1π1 + π2 Μ Μ 1+ π π½0+ π½1π1 + π2 π β6 + 0.05β40 + 3.5 1+ π β6+ 0.05β40+ 3.5 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R = = π β0.5 1+ π β0.5 06065 1.6065 = 0.3776 Probability is 0.3776 Question 7: 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 πΜ = 10, while the mean for those that didnβt was πΜ = 0. In addition, the variance of X for these two sets of companies was πΜ 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. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Hint: Recall that the density function for a normal random variable is f(x) = β(π₯βπ)2 π 2π2 β2ππ 2 . You will need to use Bayesβ theorem. Solution: Mean value of X, who issued a dividend is πΜ = 10 Mean value of X, who didnβt issue a dividend is πΜ = 0 Variance of X for 2 sets of companies πΜ 2 = 36 Assume X follows a normal distribution. Percentage profit was X = 4 in the last year Considering probability that X will issue a dividend ππ (x) = ππ 1 2ππ β βπ π=1 ππ ππ (x) = 2 β(π₯βππ ) ( ) 2π2 π 1 β2ππ From the equation 4.12 in textbook 2 β(π₯βππ ) ( ) 2π2 π 1 β2ππ β(π₯βππ )2 π 2π2 + ππ ππ 1 ππ β2ππ β(π₯βππ )2 π 2π2 1 π β2ππ β(π₯βππ )2 2π2 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Substitute X=4, ππ = 10, ππ = 0, π 2 = 36, ππ = 0.8, ππ = 0.2 in the above equation = β(4β10)2 1 0.8β β π 36β2 β2β3.14β6 β(4β0)2 β(4β10)2 1 1 0.8β β π 36β2 + 0.2 β β π 36β2 β2β3.14β6 β2β3.14β6 β36 = = = = 0.8β π 36β2 β36 + β16 0.8β π 36β2 0.2β π 36β2 0.8β π β0.5 0.8β π β0.5 + 0.8β π β0.22 0.485 0.485+0.1675 0.485 0.645503 = 0.751 Probability that X will issue a dividend is 0.751 Question 9: This problem has to do with odds. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R (a) On average, what fraction of people with an odds of 0.37 of defaulting on their credit card payment will in fact default? Solution: π(π) 1βπ(π) = 0.37 p(X) = 0.37(1-p(X)) p(X) = 0.37 β 0.37(p(X)) 1.37(p(X)) = 0.37 P(X) = 0.27 On an average, 27% of people are defaulting on their credit card payment. (b) Suppose that an individual has a 16 % chance of defaulting on her credit card payment. What are the odds that she will default? Solution: π(π) 1βπ(π) = 0.16 1β0.16 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R = 0.16 0.84 = 0.19 The odds that she will default is 19% Question 10: This question should be answered using the Weekly data set, which is part of the ISLR 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. 10) (a) Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns? Solutions: >library(ISLR) >summary(Smarket) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >pairs(Smarket) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >cor(Smarket[, -9]) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >attach(Smarket) >plot(Volume) (b) Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R results. Do any of the predictors appear to be statistically significant? If so, which ones? Solution >glm.fit=glm(Dimension~Lag1+Lag2+Lag3+Lag4+Lag5+ Volume,data=Smarket,family=binomial) >summary(glm.fit) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Lag1 has the lowest p-value. However, p-value is 0.145, which is relatively large, so there is no real association between Lag1 and Direction. 10)c) 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. >glm.probs=predict(glm.fit,type=βresponseβ) >glm.probs[1:10] >contrasts(Direction) >glm.pred=rep(βDownβ,1250) >glm.pred[glm.probs>.5]=βUpβ Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >table(glm.pred,Direction) Percentage of correct predictions on the training data is =( =( 145+507 ) 145+507+457+141 652 ) 1250 =0.5216 = 52.16% >mean(glm.pred==Direction) 0.5216 The training error rate is 100-52.16 = 47.84% Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R 10)d) Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as 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). Solution: >train = (Year<2005) >Smarket.2005 = Smarket[!train,] >Direction.2005 = Direction[!train] >glm2.fit = glm(Direction~Lag2,data=Smarket,family=binomial,subset =train) >summary(glm2.fit) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >probs2=predict(fit.glm2,Smarket.2005,type=βresponseβ) >glm2.pred=rep(βDownβ,length(probs2)) >glm2.pred[probs2>0.5]=βUpβ >table(glm2.pred,Direction.2005) Percentage of correct predictions on the training data is Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R =( =( 19+130 ) 19 +11+92+130 149 ) 252 =0.5088 = 50.88% >mean(glm2.pred==Direction) 0.5088 The training error rate is 100-50.88 = 49.12% 10)e) Repeat (d) using LDA. Solution: >library(MASS) >fit.lda<lda(Direction~Lag1+Lag2,data=Smarket,subset=train) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >lda.fit >plot(lda.fit) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >lda.pred=predict(lda.fit,Smarket.2005) >names(lda.pred) >lda.class=lda.pred$class >table(lda.class,Direction.2005) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Percentage of correct predictions on the test data is =( =( 35+106 ) 35 +35+76+106 141 ) 252 =0.5595 = 55.95% The test error rate is 100-55.95% = 44.05% (f) Repeat (d) using QDA. Solution: >qda.fit=qda(Direction~Lag1+Lag2,data=Smarket,subset=t rain) >qda.fit >qda.class=predict(qda.fit,Smarket.2005)$class Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >table(qda.class,Direction.2005) Percentage of correct predictions on the test data is =( =( 30+121 ) 30 +20+81+121 151 ) 252 =0.5992 = 59.92% The test error rate is 100-59.92% = 40.08% >mean(qda.class==Direction.2005) (g) Repeat (d) using KNN with K = 1. Solution: >library(class) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >train.X<-as.matrix(Lag2[train]) >test.X<-as.matrix(Lag2[!train]) train.Direction<-Direction[train] set.seed(1) pred.knn<-knn(train.X,test.X,train.Direction,k=1) table(pred.knn,Direction.2005) Percentage of correct predictions on the test data is =( =( 53+71 ) 53 +70+58+71 124 ) 252 =0.5 = 50% The test error rate is 100-50% = 50% Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R 10)h) Which of these methods appears to provide the best results on this data? Solution: When we are comparing the test error rates, qda and lda have minimum error rates, followed by Logistic regression and knn. 10)i) Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with values for K in the KNN classifier. Solutions: >glm.fit<-glm(Direction~Year,family=binomial) >summary(glm.fit) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R #QDA with sqrt(abs(Lag2)) >qda2.fit=qda >qda2.fit=qda(Direction~Lag1+sqrt(abs(Lag2)),data=Smark et,subset=train) >qda2.fit Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >qda2.pred=predict(qda2.fit,Smarket.2005) >table(qda2.pred$class,Direction.2005) Percentage of correct predictions on the test data is =( =( 34+121 ) 34 +20+77+121 155 ) 252 =0.5112 = 51.12% The test error rate is 100-51.12% = 48.88% Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R With k=3, knn classifier, >pred.knn<-knn(train.X,test.X,train.Direction,k=3) >table(pred.knn,Direction.2005) With k=100, knn classifier, >pred.knn<-knn(train.X,test.X,train.Direction,k=100) >table(pred.knn,Direction.2005) Question 11: 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. (a) Create a binary variable, mpg01, that contains a 1 if mpg contains a value above its median, and a 0 if mpg contains a value below its median. You can compute the median using the median() function. Note you may find it helpful to use the data.frame() function to create a single data set Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R containing both mpg01 and the other Auto variables. 172 4. Classification Solution: >attach(Auto) >mpg01<-rep(0,length(mpg)) >mpg01[mpg>median(mpg)]<-1 >Auto<-data.frame(Auto,mpg01) (b) Explore the data graphically in order to investigate the association between mpg01 and the other features. Which of the other features seem most likely to be useful in predicting mpg01? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings. Solution: >cor(Auto[, -9]) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >pairs(Auto) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >boxplot(cylinders~mpg01,data=Auto,main="Cylinders vs mpg01") >boxplot(displacement~mpg01,data=Auto,main="Displace ment vs mpg01") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >boxplot(horsepower~mpg01,data=Auto,main="Horsepow er vs mpg01") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >boxplot(weight~mpg01,data=Auto,main="Weight vs mpg01") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >boxplot(acceleration~mpg01,data=Auto,main="Accelerati on vs mpg01") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >boxplot(year~mpg01,data=Auto,main="Year vs mpg01") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R There is a relationship between βmpg01β and βcylindersβ, βweightβ, βdisplacementβ and βhorsepowerβ. (c) Split the data into a training set and a test set. Solution: >train<-(year %% 2 ==0) > Auto.train<-Auto[train,] > Auto.test<-Auto[!train,] > mpg01.test<-mpg01[!train] Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R (d) Perform LDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained? Solution: >fit.lda<lda(mpg01~cylinders+weight+displacement+horsepower,dat a=Auto,subset=train) >fit.lda >pred.lda<-predict(fit.lda,Auto.test) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >table(pred.lda$class,mpg01.test) The test error rate is 12.63% (e) Perform QDA on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained? Solution: >fit.qda<qda(mpg01~cylinders+weight+displacement+horsepower,da ta=Auto,subset=train) >fit.qda Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R >pred.qda<-predict(fit.qda,Auto.test) > table(pred.qda$class,mpg01.test) > mean(pred.qda$class!=mpg01.test) [1] 0.1318681 The test error rate is 13.18% (f) Perform logistic regression on the training data in order to predict mpg01 using the variables that seemed most associated with mpg01 in (b). What is the test error of the model obtained? Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Solution: > fit.glm<glm(mpg01~cylinders+weight+displacement+horsepower,da ta=Auto,subset=train) > summary(fit.glm) > probs<-predict(fit.glm,Auto.test,type="response") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R > pred.glm<-rep(0,length(probs)) > pred.glm[probs>0.5]<-1 > table(pred.glm,mpg01.test) > mean(pred.glm!=mpg01.test) [1] 0.1263736 The test error rate is 12.63% (g) Perform KNN on the training data, with several values of K, in order to predict mpg01. Use only the variables that seemed most associated with mpg01 in (b). What test errors do you obtain? Which value of K seems to perform the best on this data set? Solution: >train.X=cbind(cylinders,weight,displacement,horsepower) [train,] Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R > train.X<cbind(cylinders,weight,displacement,horsepower)[train,] > test.X<cbind(cylinders,weight,displacement,horsepower)[!train,] > train.mpg01<-mpg01[train] > set.seed(1) > pred.knn<-knn(train.X,test.X,train.mpg01,k=1) > table(pred.knn,mpg01.test) > mean(pred.knn!=mpg01.test) [1] 0.1538462 For k=1, the test error rate is 15.38% > pred.knn<-knn(train.X,test.X,train.mpg01,k=10) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R > table(pred.knn,mpg01.test) > mean(pred.knn!=mpg01.test) [1] 0.1648352 For k=10, the test error rate is 16.48% > pred.knn<-knn(train.X,test.X,train.mpg01,k=100) > table(pred.knn,mpg01.test) > mean(pred.knn!=mpg01.test) [1] 0.1428571 For k=100, the test error rate is 14.28%. So for k=100, it seems to perform the best test. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R 12) This problem involves writing functions. a) Write a function, Power(), that prints out the result of raising 2 to the 3rd power. In other words, your function should compute 23 and print out the results. Hint: Recall that x^a raises x to the power a. Use the print() function to output the result. Solution: > Power <- function() { 2^3 } > Power() [1] 8 (b) Create a new function, Power2(), that allows you to pass any two numbers, x and a, and prints out the value of x^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 38, namely, 6, 561. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Solution: > Power2 <- function(x,a) { x^a } > Power2(3,8) [1] 6561 (c) Using the Power2() function that you just wrote, compute 103, 817, and 1313. Solution: d) Now create a new function, Power3(), that actually returns the result x^a as 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 simply return() this return() result, using the following line: Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R The line above should be the last line in your function, before the } symbol. > Power3 <- function(x,a) { result<- x^a return(result) } e) Now using the Power3() function, create a plot of f(x) =π₯ 2 . The x-axis should display a range of integers from 1 to 10, and the y-axis should display π₯ 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ββ, or log=ββxyββ as arguments to the plot() function. Solution: > x <- 1:10 > plot(x, Power3(x,2), log= "xy", xlab="Log of x", ylab= "Log of x^2", main= "Log of x^2 vs Log of x") Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R (f) Create a function, PlotPower(), that allows you to create a plot of x against x^a for a fixed a and for a range of values of x. For instance, if you call > PlotPower (1:10,3) then a plot should be created with an x-axis taking on values 1, 2,..., 10, and a y-axis taking on values 13 , 23 ,..., 103 > PlotPower <- function(x,a) { plot(x, Power3(x,a)) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R } > PlotPower(1:10,3) 13. Using the Boston data set, fit classification models in order to predict whether a given suburb has a crime rate above or below the median. Explore logistic regression, LDA, and KNN models using various subsets of the predictors. Describe your findings. Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R Solution: > library(MASS) > attach(Boston) > crim01 <- rep(0, length(crim)) > crim01[crim > median(crim)] <- 1 > Boston <- data.frame(Boston, crim01) > train <- 1:(length(crim)/2) > test <- (length(crim) / 2 + 1):length(crim) > Boston.train <- Boston[train, ] > Boston.test <- Boston[test, ] > crim01.test <- crim01[test] > fit.glm <- glm(crim01~. - crim01 - crim, data = Boston, family = binomial, subset=train) Warning message: glm.fit: fitted probabilities numerically 0 or 1 occurred > probs <- predict(fit.glm, Boston.test, type = "response") > pred.glm <- rep(0, length(probs)) > pred.glm[probs > 0.5] <- 1 > table(pred.glm, crim01.test) Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R crim01.test pred.glm 0 1 0 68 24 1 22 139 > mean(pred.glm!=crim01.test) [1] 0.1818182 The test error rate for logistic regression is 18.18% > fit.glm <- glm(crim01~. -crim01 - crim - chas - nox, data = Boston, family = binomial, subset=train) Warning message: glm.fit: fitted probabilities numerically 0 or 1 occurred > probs <- predict(fit.glm, Boston.test, type = "response") > pred.glm <- rep(0, length(probs)) > pred.glm[probs > 0.5] <- 1 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R > table(pred.glm, crim01.test) crim01.test pred.glm 0 1 0 78 28 1 12 135 > mean(pred.glm!=crim01.test) [1] 0.1581028 The test error rate for this logistic regression is 15.81% > fit.lda <- lda(crim01~. - crim01 - crim, data = Boston, subset = train) > pred.lda <- predict(fit.lda, Boston.test) > table(pred.lda$class, crim01.test) > mean(pred.lda$class !=crim01.test) [1] 0.1343874 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R The test error rate for lda is 13.43% > fit.lda <- lda(crim01~. - crim01 - crim - chas - nox, data = Boston, subset = train) > pred.lda <- predict(fit.lda, Boston.test) > table(pred.lda$class, crim01.test) > mean(pred.lda$class !=crim01.test) [1] 0.1501976 The test error rate for this lda is 15.01% > train.X=cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black, lstat, medv)[train,] > train.X <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black, lstat, medv)[train,] > test.X <- cbind(zn, indus, chas, nox, rm, age, dis, rad, tax, ptratio, black, lstat, medv)[test,] Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R > train.crim01 <- crim01[train] > set.seed(1) > pred.knn <- knn(train.X, test.X, train.crim01, k=1) > mean(pred.knn !=crim01.test) [1] 0.458498 For this KNN (k=1), the test error rate is 45.84% > pred.knn <- knn(train.X, test.X, train.crim01, k=10) > table(pred.knn, crim01.test) crim01.test pred.knn 0 1 0 83 23 1 7 140 Chapter 4 Solutions for Classification Text book: An Introduction to Statistical Learning with Applications in R For this KNN (k=10), the test error rate is 11.85% > pred.knn <- knn(train.X, test.X, train.crim01, k=100) > table(pred.knn, crim01.test) > mean(pred.knn !=crim01.test) [1] 0.4901186 For this KNN (k=100), the test error rate is 49.01%
© Copyright 2024