Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Data C100, Final Exam

Summer 2022

1 First Question Troubles [11 Pts]

Anirudhan and Dominic are trying to write the final exam, but they have no idea what to ask! They decide to ask the students enrolled in the course for a few ideas in a Google Form survey as part of a weekly check. Even better, they realise that the construction of this Google Form survey could actually be the first question of the final exam!

(a)  [2 Pts]  Dominic messages Anirudhan about how he wants to conduct this survey, but it gets

corrupted by two blanks!  Fill in blanks A and B in the statement below to best complete Dominic’s message. Each blank can only be filled in with a singular word corresponding to the best response possible in that blank.

Ideally, I [Dominic] want everyone enrolled in the course to fill the form, which is most well known as a A . If a significant portion of the class does not respond, we may incur B bias.

(b)  [2 Pts]  Suppose they are unable to survey everyone in the course. Instead, they decide to only

poll people in the course that attend the final lecture live at 5:00 PM PT using a Zoom poll. Which of the following is true about the population and sampling frame?

□ The population is the same as the sampling frame.

□ The population is a subset of the sampling frame.

The sampling frame is a subset of the population.

The sampling frame does not well represent the population.

(c)  [3 Pts]  Suppose we want each student to only fill our Google Form survey once. To do this, Dominic decides to make students enter their student ID, which is a 9 or 10 digit numerical value. To make sure students have entered their SID correctly on the Google form, he wants to write a REGEX pattern to help him fully match all valid student IDs.  If a student ID is valid, we wish to replace the entire SID with the message  ‘success!’ .

Fill in the REGEX pattern below such that the output below is generated.

>>>  pattern  =  r'________________ '

>>>  re .sub(pattern,   'success!',   '123456789')

'success!'

>>>  re .sub(pattern,   'success!',   '2345678901')

'success!'

>>>  re .sub(pattern,   'success!',   '12345678a')

'12345678a'

>>>  re .sub(pattern,   'success!',   '!23456789')

'!23456789'

>>>  re .sub(pattern,   'success!',   '12345')

'12345'

>>>  re .sub(pattern,   'success!',   '123456789012')

'123456789012'

(d)  [4 Pts]  Rahul, a Data 100 TA, realizes that the form is still not secure enough! He decides to add a password to the form with two requirements shown below, both of which must be met for a valid password. The password must contain:

1 or more lowercase characters (i.e., a, b, c, ..., z)

1 or more uppercase letters (i.e., A, B, C, ..., Z)

To enforce the password requirements, he asks you to help him write a REGEX pattern to match all valid passwords and fail to match all invalid passwords. Fill in the REGEX pattern below such that the output below is generated.

Hint: Consider the different orders in which lowercase and uppercase letters may occur.

>>>  pattern  =  r'________________ '

>>>  test_passwords  =   ['Abc',   'abc',   'aBc',   'a@#',   'a!@#B'] >>>  for  password  in  test_passwords:

. . .           print(password,  "matches?",

. . .                         re .search(pattern,  password)  is  not  None)

...

Abc  matches?  True

abc  matches?  False

aBc  matches?  True

a@#  matches?  False

a!@#B  matches?  True

2 SQL to a Pandas Question [19 Pts]

Anirudhan and Dominic receive survey data from students about their preferences and interests which will help them write the final exam!  Siddhant, a Data 100 TA, decides to store the data in a table named survey data in a SQLite database since it is too large to open in Pandas on

DataHub.

An arbitrary selection of 5 rows of the collected survey data is shown below when the following query is executed.

SELECT  *  FROM  survey_data  LIMIT  5;

Each row represents one student response to the survey.   The  score represents the student’s score on the survey out of 3, the city and country represent the self-reported location where the student currently resides, n movies per yr represents the number of movies the student watches in a year, and pref cartoon character represents the student’s favourite animated character.

You may assume that there are no null values.

(a)  [4 Pts]  Siddhant wants to find out which cartoon characters are most popular among Data

100 students in the United States. Write a SQL query that returns the most popular preferred cartoon character among all students living in the  ‘United  States’ , in descending order of number of occurrences in the survey data.

The output should resemble the table shown below, with rows corresponding to each preferred cartoon character and respective counts. Note that the column names (aliases) must match.

(b)  [4 Pts]  Interestingly, Siddhant observes that all the favourite cartoon characters for students

living in the United States from the previous subpart were all originating from the United States! He wishes to explore this relation further and loads a table cartoon origin show- ing the origin for each cartoon character. A sample of 5 rows from this table are shown below.

Write a SQL query that shows the proportion of students living in each country from the survey data that chose cartoon characters originating from that country, ordered from greatest to least. For cartoon characters not listed in the cartoon origin table, assume by default they do not originate from the student’s country.

A sample of the output is shown below, where rows correspond to each country and desired proportion per the question specification. Note that the column names (aliases) must match.


Hint: Use a combination of two aggregation functions. Recall that SQL allows you to apply aggregation functions to column expressions!

[3 Pts]  Siddhant discovers that Data 100 students are from all over the world! He decides to find using SQL which students’ cities contain the word  ‘City’ in them. If the city contains the word  ‘City’ , then we want to output  ‘yes’ ; otherwise, we want to output  ‘no’ .

The output should resemble the table shown below, with rows corresponding to the city in each student’s response and whether it contains the word  ‘City’ . Your output should have

the same number of rows as survey data! Note that the column names (aliases) must match.

Fill in the blank below to accomplish this.


SELECT  city,  __________________________________

FROM  survey_data;


Hint: The following SQL syntax may be helpful.


CASE

WHEN  condition  THEN  result1

ELSE  result2

END




(d)  [4 Pts]  Instead of working with SQL, Siddhant decides to sample 100 rows of the SQL table into a Pandas DataFrame named survey sample and use Pandas instead of SQL! Using a one-line Pandas expression, find the average number of movies watched per year at each unique student location (that is, combination of city and country) of the sampled survey data survey sample.

A sample of the desired output is shown below as a Pandas DataFrame.



[2 Pts]  Siddhant does some research and discovers that Ireland,  South Korea, the United

States, and Australia visit the movies most on average per year.  Suppose we are provided the (real!)  data stored in a Pandas DataFrame movie data shown below about average movie visits per year for all countries in the world.


We wish to combine the average number of movies per year (avg n movies per yr) with the country information provided in the survey. That is, for each row in survey sample, the corresponding average number of movies per year is provided for the country specified in that row. Write a one-line Pandas expression that merges the two DataFrames to accomplish this.


(f)  [2 Pts]  Visualize using a histogram the number of movie visits for only students living in any of these countries using the sampled Pandas DataFrame survey sample:  [‘Ireland’,

‘South  Korea’,   ‘United  States’,   ‘Australia’]. Fill in the blank to output the following figure.


c  =   ['Ireland',   'South  Korea',

'United  States',   'Australia']

sns .histplot(data  =  _________________________________________ , x  =   'n_movies_per_yr')



3 Modeling with Mickey Mouse [20 Pts]


Anirudhan and Dominic invite the Data 100 staff to perform some initial modeling on some student survey data to understand student interests, preferences, and habits.

Specifically, we want to predict whether students live in the United States based on their favourite animated (cartoon) character (pref cartoon character) and number of movies watched per year (n movies per yr). The following training data is sampled from student responses to the Data 100 survey!



(a)  [2 Pts]  Which of the following variable types best describes the n movies per yr? ⃝  Quantitative continuous

Quantitative discrete

Qualitative nominal

Qualitative ordinal

(b)  [2 Pts]  Which of the following techniques are most suitable for this prediction task?

Classification

Clustering

Regression

Non-parametric modeling

(c)  [2 Pts]  Regardless of your previous answer, suppose we decide to use logistic regression. Using the LogisticRegression class in Scikit-learn with no regularization, we obtain 100% accuracy on the training set by training a model on one-hot encoded features specifying the cartoon character and the number of movies watched per year. Which of the following must be true if this has occurred?

The features are linearly separable based on the unique values of the response variable.


□ The response variable is linearly separable based on the unique values of the fea- tures.

□ The design matrix is linearly independent.

□ The response variable has a correlation coefficient of r = 1 or r = −1 with all of the design matrix features.

(d)  [3 Pts]  Instead of using one-hot encoding, suppose we encode the pref cartoon character with a 1 if the character originated from the United States and 0 if it did not. We train a logistic       regression model on this feature along with the number of movies per year and a bias feature.

Suppose the optimal parameters obtained for our optimal logistic regression model trained on these three features (including a bias feature, listed as the first element of the vector) are θˆ = [2, 1, 0.25]. Unfortunately, we find that an outlier has strongly affected our cross-entropy loss and our model parameters!

Calculate the cross-entropy loss (using log base e) on the outlier data point xoutlier  = [1, 1, 4] if the corresponding youtlier  = 0. Round to the nearest 3 decimal places, and do not show work. Hint: σ(z) = 1+e(1)


(e)  [3 Pts]  Suppose that we added a L2  regularization term to the logistic regression objective function from the previous function, shown below as R(θ), and we minimised this objective function to obtain θˆ for our logistic regression model.


n                                                                                                                          p



Which of the following is true?


□ There exists an optimal analytical solution to minimising this objective function R(θ) that can be derived either using calculus or geometry.

□ It is impossible to achieve an accuracy of 100% using any λ > 0.

If λ > 0, then the parameters in θˆfor this objective function do not diverge to.

This objective function is convex since both the empirical risk function and the regularization penalty term are convex.

(f)  [2 Pts]  After some tinkering, Dominic is able to train another logistic regression using regu- larization and obtains an optimal θˆ.  Suppose our test set consists of the following 6 points, with our corresponding predictions shown. Calculate the recall of our model on the test set.

Round to the nearest 3 decimal places, and do not show work.

y

1

0

1

1

0

1



(g)  [2 Pts]  Suppose we decide to train a decision tree or random forest instead of a logistic re- gression model.  Which of the following are true about the effect of the following model and hyperparameter choices on the estimated model bias and model variance of the resulting model on a training data point?

Note that unless specified otherwise, decision trees and random forests will not have any training restrictions (e.g., maximum depth).


A random forest will likely have lower model variance than a decision tree, when fully trained.

A decision tree will likely have lower model bias than a random forest, when fully trained.

□ A decision tree with depth 10 will likely have lower model variance than a decision tree with depth 2, when fully trained.

A random forest with 10 trees will likely have lower model variance than a random forest with 2 trees, when fully trained.

(h)  [4 Pts]  Rahul decides to train a decision tree for our prediction task without any training restrictions.  Suppose he uses simply one feature and a small subset of our data for training, shown below.  Which is the most optimal split point for the n movies per year using weighted node entropy?


⃝  1

3

5

⃝  7

Justify your answer by calculating the numerical weighted node entropy of only this split, the ideal split from your answer above (make sure to use log2 , and not loge or log10 ). Round to 3 decimal places, and do not show work.




4 Mmm... More Movie Modeling... [15 Pts]


Anirudhan and Dominic decide to focus on a different modeling problem: can we model and ex- plain the number of movies our students have watched per year? They will try to predict students’ number of movies watched per year using regression and as much data as possible from the ques- tions in the survey.


(a)  [2 Pts]  To begin, Anirudhan and Dominic decide to one-hot encode all the qualitative fea- tures in the survey results.  They sample a random subset of all p of these one-hot encoded features to obtain the 15 that they will use in their design matrix: x1 to x15 . They measure the correlation between the 15 sampled features with each other and with the number of movies watched (y), and the correlation heatmap below shows the results. Which of the following is true?


□ Since most of the correlation coefficients between the features and response variable are small, it is certain that the fit will be poor.

Since most of the the correlation coefficients between the features and response variable are small, it is possible that the fit will be poor.

It is likely that there is multicollinearity among the features in the model.

□ The correlation coefficients would change if the number of movies watched was standardised.

(b)  [3 Pts]  Using another random sample of features, Rahul decides to train a multiple linear

regression model optimizing the MSE that achieves an optimal average training loss of 0 and an average test loss of 12,000. Which of the following is true in this case?

□ The residuals on the test set are orthogonal to the span of the training set’s design matrix.

The residuals on the training set are orthogonal to the span of the training sets design matrix.

□ The residuals on the test set are orthogonal to the span of the test set’s design matrix.

The residuals on the training set are all zero.

The model is overfitting to the training data.

(c)  [2 Pts]  Using the same θˆ and the multiple linear regression model in the previous part, Rahul decides to interpret the parameters θˆ that were obtained.  One of his friends, Muthu, argues that this is a bad idea.  Another friend, Suriya, argues that this is fine as long as Rahul uses bootstrap sampling and confidence intervals.

Who is correct? Note that neither or both may be correct. Justify your answer.


(d)  [2 Pts]  Rahul is unhappy with the multiple linear regression model’s performance, and he decides to experiment with using the Ridge regression model using all of the one-hot encoded qualitative features to predict the number of movies per year.  Suppose that the resulting design matrix is 200 × 190.  Which of the following is true if he uses stochastic gradient descent to compute θˆ?

The θˆ computed by stochastic gradient descent may differ from the optimal solution.

□ There isn’t a unique optimal solution to minimise the Ridge objective function for this design matrix.

Given a good selection of λ, the Ridge regression model can reduce overfitting.

Increasing the regularization hyperparameter λ will never decrease the train- ing loss.

Increasing the regularization hyperparameter λ will never increase the test loss.

(e)  [4 Pts]  To find the optimal λ regularization parameter for his Ridge regression model, Rahul uses a cross-validation algorithm. Unfortunately, it’s incomplete! Help him fill in the blanks below to complete the algorithm.


def  cross_validate(X,  y,  model,  fold_idxs):

"""

Given  a  training  design  matrix  X,  response  vector  y, a  model  with  fit  and  predict  functions,  and  fold         indices,  return  the  average  cross-validated  mean         square  error .

"""

mse  =   []

for  train_idx,  test_idx  in  fold_idxs:

X_k_train,  X_k_test  =  X .loc[train_idx],  X .loc[test_idx] Y_k_train,  Y_k_test  =  Y .loc[train_idx],  Y .loc[test_idx] model .fit(_________ ,  _________ )

mse .append(______________________ )

return  np .______ (mse)


(f)  [2 Pts]  Assume you implemented the cross-validation algorithm in the previous subpart cor- rectly. Based on the results from that cross-validation algorithm applied to determine an ideal regularization hyperparameter λ for our Ridge model shown below, which of the following are true?

Assume we used the Ridge optimal analytical solution to compute θˆin any fit call.

□ λ = 0.01 is necessarily optimal for minimizing the training mean squared error.

□ λ = 0.01 is necessarily optimal for minimizing the test mean squared error.

For all the models shown, the sum of the residuals is non-zero even if there is a bias term.

For all the models shown, the training predictions (yˆ = Xθ) are within the span of the column vectors of the design matrix X used to train the model.


5 Slipping Down A New Loss Surface [16 Pts]


The Data 100 staff are trying to use modeling to predict Data 100 students’ number of movies watched per year given data from a survey. After attempts at using Ridge regression, it ultimately does not converge quickly enough!

Anirudhan decides to use simple linear regression instead with his own custom objective func- tion, which he hopes will converge sooner (and be easier for you to do calculus with)! However, they don’t have much time or any slip days left, so they decide to experiment with gradient descent techniques! For subparts (a) and (b) of this question, please use this dataset shown below.

x y

0 1

2 6

0 6

1 6

2 1

(a)  [3 Pts]  Suppose we wish to minimize Anirudhan’s custom objective function for SLR (i.e., yˆ = a + bx) using batch gradient descent, and our initialization is θ (0)  = [a(0) ,b(0)] = [0, 0]. Apply one gradient step using the data shown above and a learning rate of α = 0.1 to compute θ (1) .

n


i=1

Enter your answer as a vector containing two numbers, both rounded to 3 decimal places. For example, a sample response might be:  [3 . 141,  1 . 000].


(b)  [2 Pts]  Suppose the optimal solution is θˆ = [4, 0]. Using Anirudhan’s objective function R(θ) for SLR (i.e., yˆ = a + bx) shown in the above subpart, does there exist a scalar learning rate α that helps batch gradient descent converge to θˆin one step initializing at θ(0)  = [a(0) ,b(0)] = [0, 0]?

Yes, there is.

No, there is not.

(c)  [2 Pts]  Using batch gradient descent to minimize R(θ) from the previous subparts with an arbitrary initialization and learning rate, which of the following is possible?  Note that the optimal parameter in this context refers to the parameter which minimizes the empirical risk function on the training set.

The optimal parameter θˆ is found in a finite number of gradient steps, and gradient descent returns θˆ.

□ The optimal parameter θˆ is found in a finite number of gradient steps, but gradient descent does not return θˆ.

The optimal parameter θˆis not found.

(d)  [2 Pts]  Using stochastic gradient descent to minimize R(θ) from the previous subparts with an arbitrary initialization, batch size, and learning rate, which of the following is possible? Note that the optimal parameter in this context refers to the parameter which minimizes the empirical risk function on the training set.

The optimal parameter θˆ is found in a finite number of gradient steps, and gradient descent returns θˆ.

The optimal parameter θˆ is found in a finite number of gradient steps, but gradient descent does not return θˆ.

The optimal parameter θˆis not found.

(e)  [3 Pts]  Suppose we estimated the model bias and model variance using the bootstrap sam-

pling technique in Homework 6 to understand which gradient descent (stochastic gradient gradient or batch gradient descent) technique will work better for this task!

Assume for this case that there exists no observational noise (that is, ϵ = 0). Further, assume that we use a fixed initialization and that we use fixed, equivalent, and reasonable learning rates and the same number of gradient steps for both stochastic and batch GD. Which of the following is most likely to be true?