Perceptron and Regression solution

$30.00

Description

Submission

Submit your solutions electronically on the course Gradescope site as PDF les.

If you plan to typeset your solutions, please use the LaTeX solution template. If you must submit scanned handwritten solutions, please use a black pen on blank white paper and a high-quality scanner app.

  • Perceptron [10 pts]

Design (specify for) a two-input perceptron (with an additional bias or o set term) that computes the following boolean functions. Assume T = 1 and F = 1. If a valid perceptron exists, show that it is not unique by designing another valid perceptron (with a di erent hyperplane, not simply through normalization). If no perceptron exists, state why.

(a) AND (b) XOR

  • Logistic Regression [10 pts]

Consider the objective function that we minimize in logistic regression:

N

X

J( ) = [yn log h (xn) + (1 yn) log (1 h (xn))]

n=1

  1. Find the partial derivatives @J .

@ j

  • Locally Weighted Linear Regression [10 pts]

Consider a linear regression problem in which we want to \weight” di erent training instances di erently because some of the instances are more important than others. Speci cally, suppose we want to minimize

N

X

J( 0; 1) = wn ( 0 + 1xn;1 yn)2:

n=1

Here wn > 0. In class, we worked out what happens for the case where all the weights (the wn‘s) are the same. In this problem, we will generalize some of those ideas to the weighted setting.

  1. Calculate the gradient by computing the partial derivatives of J with respect to each of the parameters ( 0; 1).

  1. Set each partial derivatives to 0 and solve for 0 and 1 to obtain values of ( 0; 1) that minimize J.

  • Understanding Linear Separability [25 pts]

De nition 1 (Linear Program) A linear program can be stated as follows:

~

R

m

, and ~c 2 R

n

~

2

R

n

, that minimizes the

Let A be an m n real-valued matrix, b 2

. Find a t

linear function

~

T~

z(t) = ~c

t

subject to

~

~

At

b

~

In the linear programming terminology, ~c is often referred to as the cost vector and z(t) is referred to as the objective function.1 We can use this framework to de ne the problem of learning a linear discriminant function.2

The Learning Problem:3 Let x~1; x~2; : : : ; x~m represent m samples, where each sample x~i 2 Rn is an n-dimensional vector, and ~y 2 f 1; 1gm is an m 1 vector representing the respective labels of each of the m samples. Let w~ 2 Rn be an n 1 vector representing the weights of the linear discriminant function, and be the threshold value.

We predict x~i to be a positive example if w~T x~i + 0. On the other hand, we predict x~i to be a negative example if w~T x~i + < 0.

We hope that the learned linear function can separate the data set. That is,

i

(

1 if w~T x~i + < 0:

y

=

1

if w~T x~i +0

In order to nd a good linear separator, we propose the following linear program:

min

subject to yi(w~T x~i + ) 1 ; 8(x~i; yi) 2 D

0

where D is the data set of all training examples.

(1)

(2)

  1. A data set D = f(x~i; yi)gmi=1 that satis es condition (1) above is called linearly separable. Show that if D is linearly separable, there is an optimal solution to the linear program (2) with = 0

  1. Now show that there is an optimal solution with = 0, then D is linearly separable.

  1. What can we say about the linear separability of the data set if there exists a hyperplane that satis es condition (2) with > 0?

  1. An alternative LP formulation to (2) may be

min

subject to yi(w~T x~i + ) ; 8(x~i; yi) 2 D

0

Find the optimal solution to this formulation (independent of D) to illustrate the issue with such a formulation.

(e) Let x~1 2 Rn, x~1T = 1 1 1

and y1 = 1. Let x~2 2 Rn, x~2T =

1

1 1

and y2 = 1.

The data set D is de ned as

D = f(x~1; y1); (x~2; y2)g:

Consider the formulation in (2) applied to D. What are possible optimal solutions?

  • Implementation: Polynomial Regression [45 pts]

In this exercise, you will work through linear and polynomial regression. Our data consists of inputs xn 2 R and outputs yn 2 R; n 2 f1; : : : ; Ng, which are related through a target function y = f(x). Your goal is to learn a linear predictor h (x) that best approximates f(x). But this time, rather than using scikit-learn, we will further open the \black-box”, and you will implement the regression model!

code and data

code : regression.py

data : regression_train.csv, regression_test.csv

This is likely the rst time that many of you are working with numpy and matrix operations within a programming environment. For the uninitiated, you may nd it useful to work through a numpy tutorial rst.4 Here are some things to keep in mind as you complete this problem:

If you are seeing many errors at runtime, inspect your matrix operations to make sure that you are adding and multiplying matrices of compatible dimensions. Printing the dimensions of variables with the X.shape command will help you debug.

When working with numpy arrays, remember that numpy interprets the * operator as element-wise multiplication. This is a common source of size incompatibility errors. If you want matrix multiplication, you need to use the dot function in Python. For example, A*B does element-wise multiplication while dot(A,B) does a matrix multiply.

Be careful when handling numpy vectors (rank-1 arrays): the vector shapes 1 N, N 1, and N are all di erent things. For these dimensions, we follow the the conventions of scikit-learn’s LinearRegression class5. Most importantly, unless otherwise indicated (in the code documentation), both column and row vectors are rank-1 arrays of shape N, not rank-2 arrays of shape N 1 or shape 1 N.

Visualization [5 pts]

As we learned last week, it is often useful to understand the data through visualizations. For this data set, you can use a scatter plot to visualize the data since it has only two properties to plot (x and y).

  1. Visualize the training and test data using the plot_data(…) function. What do you ob-serve? For example, can you make an educated guess on the e ectiveness of linear regression in predicting the data?

Linear Regression [25 pts]

Recall that linear regression attempts to minimize the objective function

N

X

J( ) = (h (xn) yn)2:

n=1

In this problem, we will use the matrix-vector form where

0

y1

1

0

x1T

1

y2

x2T

y =

B

...

C

;

X =

B

...

C

;

B

y

N

C

B

xT

C

B

C

B

N

C

@

A

@

A

and each instance xn = 1; xn;1; : : : ; xn;D T .

In this instance, the number of input features D = 1.

  • 1

0

    • 1 C

    • C = B 2 C

    • C

    • ... C @ A

D

Rather than working with this fully generalized, multivariate case, let us start by considering a simple linear regression model:

h (x) = T x = 0 + 1x1

regression.py contains the skeleton code for the class PolynomialRegression. Objects of this class can be instantiated as model = PolynomialRegression (m) where m is the degree of the polynomial feature vector where the feature vector for instance n, 1; xn;1; x2n;1; : : : ; xmn;1 T . Setting m = 1 instantiates an object where the feature vector for instance n, 1; xn;1 T .

  1. Note that to take into account the intercept term ( 0), we can add an additional \feature” to each instance and set it to one, e.g. xi;0 = 1. This is equivalent to adding an additional rst column to X and setting it to all ones.

Modify PolynomialRegression.generate_polynomial_features(…) to create the matrix X for a simple linear model.

  1. Before tackling the harder problem of training the regression model, complete PolynomialRegression.predict(…) to predict y from X and .

  1. One way to solve linear regression is through gradient descent (GD).

Recall that the parameters of our model are the j values. These are the values we will adjust to minimize J( ). In gradient descent, each iteration performs the update

N

X

j j 2 (h (xn) yn) xn;j (simultaneously update j for all j):

n=1

With each step of gradient descent, we expect our updated parameters j to come closer to the parameters that will achieve the lowest value of J( ).

6

As we perform gradient descent, it is helpful to monitor the convergence by computing

the cost, i.e., the value of the objective function J. Complete PolynomialRegression.cost(…) to calculate J( ).

If you have implemented everything correctly, then the following code snippet should return 40:234.

train_data = load_data( regression_train.csv )

model = PolynomialRegression()

model.coef_ = np.zeros(2)

model.cost(train_data.X, train_data.y)

Next, implement the gradient descent step in PolynomialRegression.fit_GD(…). The loop structure has been written for you, and you only need to supply the updates to and the new predictions y^ = h (x) within each iteration.

We will use the following speci cations for the gradient descent algorithm: { We run the algorithm for 10; 000 iterations.

{ We terminate the algorithm ealier if the value of the objective function is unchanged across consecutive iterations.

{ We will use a xed step size.

So far, you have used a default learning rate (or step size) of = 0:01. Try di erent = 10 4; 10 3; 10 2; 0:0407, and make a table of the coe cients, number of iterations until convergence (this number will be 10; 000 if the algorithm did not converge in a smaller number of iterations) and the nal value of the objective function. How do the coe cients compare? How quickly does each algorithm converge?

  1. In class, we learned that the closed-form solution to linear regression is = (XT X) 1XT y:

Using this formula, you will get an exact solution in one calculation: there is no \loop until convergence” like in gradient descent.

Implement the closed-form solution PolynomialRegression.fit(…).

What is the closed-form solution? How do the coe cients and the cost compare to those obtained by GD? How quickly does the algorithm run compared to GD?

  1. Finally, set a learning rate for GD that is a function of k (the number of iterations) (use k = 1+1k ) and converges to the same solution yielded by the closed-form optimization (minus possible rounding errors). Update PolynomialRegression.fit_GD(…) with your proposed learning rate. How long does it take the algorithm to converge with your proposed learning rate?

Polynomial Regression[15 pts]

Now let us consider the more complicated case of polynomial regression, where our hypothesis is

h (x) = T (x) = 0 + 1x + 2x2 + : : : + mxm:

7

  1. Recall that polynomial regression can be considered as an extension of linear regression in which we replace our input matrix X with

0

(x1)T

1

(x2)T

=

B

...

C

;

B

(x

N

)T

C

B

C

@

A

where (x) is a function such that j(x) = xj for j = 0; : : : ; m.

Update PolynomialRegression.generate_polynomial_features(…) to create an m + 1 dimensional feature vector for each instance.

  1. Given N training instances, it is always possible to obtain a \perfect t” (a t in which all

the data points are exactly predicted) by setting the degree of the regression to N 1. Of course, we would expect such a t to generalize poorly. In the remainder of this problem, you will investigate the problem of over tting as a function of the degree of the polynomial, m. To measure over tting, we will use the Root-Mean-Square (RMS) error, de ned as

p

ERMS = J( )=N ;

where N is the number of instances.6

Why do you think we might prefer RMSE as a metric over J( )?

Implement PolynomialRegression.rms_error(…).

  1. For m = 0; : : : ; 10, use the closed-form solver to determine the best- t polynomial regression model on the training data, and with this model, calculate the RMSE on both the training data and the test data. Generate a plot depicting how RMSE varies with model complexity (polynomial degree) { you should generate a single plot with both training and test error, and include this plot in your writeup. Which degree polynomial would you say best ts the data? Was there evidence of under/over tting the data? Use your plot to justify your answer.