Skip to content
ResAI

USAAIO 2025

Round 1

Three multi-part problems that build from hand derivations to working code: linear algebra on the Fibonacci sequence, neural-network fundamentals in NumPy and PyTorch, and logistic regression on the Titanic dataset.
Problems
3
Parts
41
Total points
300

Problem 1Fibonacci numbers and eigenvalues

100 pts

SummaryWrite the Fibonacci recurrence in matrix form, prove that eigenvectors of a symmetric matrix are orthogonal, derive a closed form through spectral decomposition, and implement it in NumPy without loops.

    Linear algebraEigendecompositionNumPy

Let us consider the following sequence:

Fn=Fn−1+Fn−2, ∀ n≥2.F_n = F_{n-1} + F_{n-2} , \ \forall \ n \geq 2 .

Before starting this problem, make sure to run the following code first without any change:

# DO NOT CHANGE

import numpy as np

import matplotlib.pyplot as plt

""" END OF THIS PART """

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

  • All coding tasks shall run on CPUs, not GPUs.

Part 1

10 ptsNon-codingForum thread

Let F0=3F_0 = 3, F1=1F_1 = 1.

Manually write down FnF_n for n=2,3,4,5n = 2, 3, 4 , 5.

  • Reasoning is not required.
Show official solution

Official solution

F2=4,F3=5,F4=9,F5=14.\begin{align*} \boxed{F_2 = 4, F_3 = 5, F_4 = 9, F_5 = 14 .} \end{align*}

Part 2

10 ptsNon-codingForum thread

The recursive equation that defines the sequence in this problem can be written in a matrix form:

[FnFn−1]=A[Fn−1Fn−2], ∀ n≥2,\begin{bmatrix} F_n \\ F_{n-1} \end{bmatrix} = \mathbf{A} \begin{bmatrix} F_{n-1} \\ F_{n-2} \end{bmatrix}, \ \forall \ n \geq 2 ,

where A∈R2×2\mathbf{A} \in \Bbb R^{2 \times 2}.

Compute A\mathbf{A}.

  • Reasoning is not required.

  • The value of each entry in A\mathbf{A} must be exact. For instance, the following values are exact: 3\sqrt{3}, 27\frac{2}{\sqrt{7}}, π+38\pi + \frac{3}{8}, e2e^2, sin⁡40∘\sin 40^\circ, log⁡18\log 18. However, their float approximations are not exact.

Show official solution

Official solution

A=[1110].\boxed{\mathbf{A} = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} .}

Part 3

10 ptsNon-codingForum thread

Explain why A\mathbf{A} is a symmetric matrix.

Show official solution

Official solution

Because

A⊤=A=[1110],\mathbf{A}^\top = \mathbf{A} = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} ,

matrix A\mathbf{A} is symmetric.

Part 4

10 ptsNon-codingForum thread

In this part, you are asked to prove a general result that holds for any real-valued symmetric matrix.

Let U∈RN×N\mathbf{U} \in \Bbb R^{N \times N} be a real-valued symmetric matrix.

Consider the following eigenvalue equation

Uv=λv,\mathbf{U} \mathbf{v} = \lambda \mathbf{v} ,

where λ∈R\lambda \in \Bbb R and v∈RN×1\mathbf{v} \in \Bbb R^{N \times 1}.

Let λi\lambda_i and λj\lambda_j be two distinct real eigenvalues and vi,vj∈RN×1\mathbf{v}_i, \mathbf{v}_j \in \Bbb R^{N \times 1} be two eigenvectors associated with them, respectively.

Prove that

vi⊤vj=0.\mathbf{v}_i^\top \mathbf{v}_j = 0 .

That is, vectors vi\mathbf{v}_i and vj\mathbf{v}_j are orthogonal.

Show official solution

Official solution

We use two approaches to compute

vi⊤Uvj.\mathbf{v}_i^\top \mathbf{U} \mathbf{v}_j .

Approach 1

We have

vi⊤Uvj=vi⊤(Uvj)=vi⊤(λjvj)=λjvi⊤vj.(1)\begin{align*} \mathbf{v}_i^\top \mathbf{U} \mathbf{v}_j & = \mathbf{v}_i^\top \left( \mathbf{U} \mathbf{v}_j \right) \\ & = \mathbf{v}_i^\top \left( \lambda_j \mathbf{v}_j \right) \\ & = \lambda_j \mathbf{v}_i^\top \mathbf{v}_j . \hspace{1cm} (1) \end{align*}

Approach 1

We have

vi⊤Uvj=(vi⊤U)vj=(vi⊤U⊤)vj=(Uvi)⊤vj=(λivi)⊤vj=λivi⊤vj,(2)\begin{align*} \mathbf{v}_i^\top \mathbf{U} \mathbf{v}_j & = \left( \mathbf{v}_i^\top \mathbf{U} \right) \mathbf{v}_j \\ & = \left( \mathbf{v}_i^\top \mathbf{U}^\top \right) \mathbf{v}_j \\ & = \left( \mathbf{U} \mathbf{v}_i \right)^\top \mathbf{v}_j \\ & = \left( \lambda_i \mathbf{v}_i \right)^\top \mathbf{v}_j \\ & = \lambda_i \mathbf{v}_i^\top \mathbf{v}_j , \hspace{1cm} (2) \end{align*}

where the second equality follows from the property that U\mathbf{U} is a symmetric matrix.

Two approaches should yield the same result. Equating (1) and (2), we have

λjvi⊤vj=λivi⊤vj.\lambda_j \mathbf{v}_i^\top \mathbf{v}_j = \lambda_i \mathbf{v}_i^\top \mathbf{v}_j .

Because λi≠λj\lambda_i \neq \lambda_j, we must have

vi⊤vj=0.\mathbf{v}_i^\top \mathbf{v}_j = 0 .

This completes the proof.

Part 5

10 ptsNon-codingForum thread

Let us go back to our matrix A\mathbf{A}.

In the following eigenvalue equation

Ax=λx,\mathbf{A} \mathbf{x} = \lambda \mathbf{x} ,

compute two eigenvalues λ0\lambda_0 and λ1\lambda_1 whose values are in a descending order.

  • Reasoning is required.
Show official solution

Official solution

We solve the following characteristic equation:

det⁡(A−λI)=0.\det \left( \mathbf{A} - \lambda \mathbf{I} \right) = 0 .

Thus, we compute λ\lambda that satisfies

(1−λ)(−λ)−1⋅1=0.\left( 1 - \lambda \right) \left( - \lambda \right) - 1 \cdot 1 = 0 .

Hence, all eigenvalues are

λ0=1+52,λ1=1−52.\boxed{\lambda_0 = \frac{1 + \sqrt{5}}{2} , \quad \lambda_1 = \frac{1 - \sqrt{5}}{2} .}

Part 6

10 ptsNon-codingForum thread

In the remaining parts of this problem, for all non-coding tasks, when you need to use those eigenvalues,

keep them as λ0 and λ1. No need to apply their formulae.\color{red}{\textbf{keep them as \(\lambda_0\) and \(\lambda_1\). No need to apply their formulae.}}

Since matrix A\mathbf{A} is symmetric, let us do the spectral decomposition of it.

That is, you should write A\mathbf{A} in the following form:

A=QΛQ⊤,\mathbf{A} = \mathbf{Q} \mathbf{\Lambda} \mathbf{Q}^\top ,

where

  • Q∈R2×2\mathbf{Q} \in \Bbb R^{2 \times 2} is an orthonormal matrix.

  • Λ=[λ000λ1]∈R2×2\mathbf{\Lambda} = \begin{bmatrix} \lambda_0 & 0 \\ 0 & \lambda_1 \end{bmatrix} \in \Bbb R^{2 \times 2} is a diagnomal matrix with λ0>λ1\lambda_0 > \lambda_1

In this task, you need to compute Q\mathbf{Q}. Reasoning is required.

Show official solution

Official solution

To compute an eigenvector xi\mathbf{x}_i assocaited with the eigenvalue λi\lambda_i for i∈{0,1}i \in \left\{ 0, 1 \right\}, we solve the following equation:

[1−λi11−λi][xi0xi1]=[00].\begin{bmatrix} 1 - \lambda_i & 1 \\ 1 & - \lambda_i \end{bmatrix} \begin{bmatrix} x_{i0} \\ x_{i1} \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} .

Since the determintant of the 2-by-2 matrix on the L.H.S. is 0, the rank of this matrix is 1. Thus, it is sufficient to only solve the following equation:

[1−λi][xi0xi1]=[00].\begin{bmatrix} 1 & - \lambda_i \end{bmatrix} \begin{bmatrix} x_{i0} \\ x_{i1} \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} .

One solution is

xi=[xi0xi1]=[λi1].\mathbf{x}_i = \begin{bmatrix} x_{i0} \\ x_{i1} \end{bmatrix} = \begin{bmatrix} \lambda_i \\ 1 \end{bmatrix} .

Thus, the iith orthonormal vector is

qi=xi∣∣xi∣∣2=11+λi2[λi1].\begin{align*} \mathbf{q}_i & = \frac{\mathbf{x}_i}{|| \mathbf{x}_i ||_2} \\ & = \frac{1}{\sqrt{1 + \lambda_i^2}} \begin{bmatrix} \lambda_i \\ 1 \end{bmatrix} . \end{align*}

Therefore,

Q=[λ01+λ02λ11+λ1211+λ0211+λ12].\begin{align*} \mathbf{Q} = \boxed{\begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} \\ \frac{1}{\sqrt{1 + \lambda_0^2}} & \frac{1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} }. \end{align*}

Part 7

10 ptsNon-codingForum thread

Use the spectral decomposition result to derive a closed form of FnF_{n} for any n∈{0,1,⋯ }n \in \left\{ 0, 1, \cdots \right\}.

  • Reasoning is required.

  • Your answer shall be written in terms of λ0\lambda_0, λ1\lambda_1, and F0F_0 and F1F_1.

Show official solution

Official solution

For n≥1n \geq 1, we have

[FnFn−1]=An−1[F1F0]=(QΛQ⊤)n−1[F1F0]=QΛn−1Q⊤[F1F0].\begin{align*} \begin{bmatrix} F_n \\ F_{n-1} \end{bmatrix} & = \mathbf{A}^{n-1} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \left( \mathbf{Q} \mathbf{\Lambda} \mathbf{Q}^\top \right)^{n-1} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \mathbf{Q} \mathbf{\Lambda}^{n-1} \mathbf{Q}^\top \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} . \end{align*}

Thus, for n≥1n \geq 1, we have

Fn=[10]A[F1F0]=[10]QΛn−1Q⊤[F1F0]=[10][λ01+λ02λ11+λ1211+λ0211+λ12][λ0n−100λ1n−1][λ01+λ0211+λ02λ11+λ1211+λ12][F1F0]=[λ01+λ02λ11+λ12][λ0n−100λ1n−1][λ01+λ0211+λ02λ11+λ1211+λ12][F1F0]=[λ0n1+λ02λ1n1+λ12][λ01+λ0211+λ02λ11+λ1211+λ12][F1F0]=[λ0n+11+λ02+λ1n+11+λ12λ0n1+λ02+λ1n1+λ12][F1F0]=(λ0n+11+λ02+λ1n+11+λ12)F1+(λ0n1+λ02+λ1n1+λ12)F0.\begin{align*} F_n & = \begin{bmatrix} 1 & 0 \end{bmatrix} \mathbf{A} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \begin{bmatrix} 1 & 0 \end{bmatrix} \mathbf{Q} \mathbf{\Lambda}^{n-1} \mathbf{Q}^\top \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \begin{bmatrix} 1 & 0 \end{bmatrix} \begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} \\ \frac{1}{\sqrt{1 + \lambda_0^2}} & \frac{1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} \lambda_0^{n-1} & 0 \\ 0 & \lambda_1^{n-1} \end{bmatrix} \begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{1}{\sqrt{1 + \lambda_0^2}} \\ \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} & \frac{1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} \lambda_0^{n-1} & 0 \\ 0 & \lambda_1^{n-1} \end{bmatrix} \begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{1}{\sqrt{1 + \lambda_0^2}} \\ \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} & \frac{1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \begin{bmatrix} \frac{\lambda_0^n}{\sqrt{1 + \lambda_0^2}} & \frac{\lambda_1^n}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} \frac{\lambda_0}{\sqrt{1 + \lambda_0^2}} & \frac{1}{\sqrt{1 + \lambda_0^2}} \\ \frac{\lambda_1}{\sqrt{1 + \lambda_1^2}} & \frac{1}{\sqrt{1 + \lambda_1^2}} \end{bmatrix} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \begin{bmatrix} \frac{\lambda_0^{n+1}}{1 + \lambda_0^2} + \frac{\lambda_1^{n+1}}{1 + \lambda_1^2} & \frac{\lambda_0^{n}}{1 + \lambda_0^2} + \frac{\lambda_1^{n}}{1 + \lambda_1^2} \end{bmatrix} \begin{bmatrix} F_1 \\ F_0 \end{bmatrix} \\ & = \boxed{\left( \frac{\lambda_0^{n+1}}{1 + \lambda_0^2} + \frac{\lambda_1^{n+1}}{1 + \lambda_1^2} \right) F_1 + \left( \frac{\lambda_0^{n}}{1 + \lambda_0^2} + \frac{\lambda_1^{n}}{1 + \lambda_1^2} \right) F_0} . \end{align*}

For n=0n = 0, we can

λ00+11+λ02+λ10+11+λ12=0\frac{\lambda_0^{0+1}}{1 + \lambda_0^2} + \frac{\lambda_1^{0+1}}{1 + \lambda_1^2} = 0

and

λ001+λ02+λ101+λ12=1.\frac{\lambda_0^{0}}{1 + \lambda_0^2} + \frac{\lambda_1^{0}}{1 + \lambda_1^2} = 1 .

Therefore, the above answer holds for all n∈{0,1,⋯ }n \in \left\{ 0, 1, \cdots \right\}.

Part 8

10 ptsNon-codingForum thread

Compute

lim⁡n→∞ FnFn−1.\lim_{n \rightarrow \infty} \ \frac{F_n}{F_{n-1}} .
  • Reasoning is required.

  • Your answer shall be written in terms of one or two eigenvalues.

Show official solution

Official solution

We notice that ∣λ0∣>1| \lambda_0 | > 1 and ∣λ1∣<1| \lambda_1 | < 1.

Hence,

lim⁡n→∞ FnFn−1=λ0.\begin{align*} \lim_{n \rightarrow \infty} \ \frac{F_n}{F_{n-1}} & = \boxed{\lambda_0 } . \end{align*}

Define a class called My_Fib.

  • Attributes:

    • Q: This attribute is matrix Q\mathbf{Q} computed above. It is a numpy array with shape (2,2).

    • lambdas: This attribute is a numpy array with shape (2,) that includes two eigenvalues computed above.

  • Method __init__:

    • All atttribute values shall be initialized when an object in this class is constructed.
  • Method compute_fib:

    • This method computes the sequence values on designated indices.

    • You must use the spectral decomposition result to write this method.

    • You are not allowed to use any loop.

    • Inputs:

      • f0: The value of F0F_0

      • f1: The value of F1F_1

      • indices: a list/tuple/range object that includes indices with which the sequence values shall be computed.

      For instance, if indices takes the value [3, 5, 9], we need to compute F3F_3, F5F_5, F9F_9.

      In our test cases, you are guaranteed that len(indices) is at least 1. You do not need to worry about the size of the test cases or whether the sequence values are too big (that is, on your side, you do not need to worry about those corner cases).

    • Outputs:

      • Return a numpy array fib_values with shape (len(indices),) and datatype int32.

      • fib_values[i] takes the value of Findices[i]F_{indices[i]}.

      For instance, if indices takes the value [3, 5, 9], then fib_values has shape (3,). The values of fib_values[0], fib_values[1], fib_values[2] are F3F_3, F5F_5, F9F_9, respectively.

    • Inside this method:

      • Print fib_values.
  • Method plot_fib:

    • This method plots indices vs. sequence values on those indices.

    • Inputs: The same as the method compute_fib(f0, f1, indices).

    • Outputs: None.

    • In your plot,

      • All data points with input indices are with marker x.

      • The linestyle is --.

      • The color is red.

      • The x-lable is: nn.

      • The y-label is: FnF_n.

      • The title is: Fibounacci sequence.

Show official solution

Official solution


class My_Fib:
    def __init__(self):
        self.lambdas = np.array([(1 + 5**.5)/2, (1 - 5**.5)/2])
        self.Q = np.stack([self.lambdas / np.sqrt(1 + self.lambdas**2), np.ones(2) / np.sqrt(1 + self.lambdas**2)])

    def compute_fib(self, f0, f1, indices):
        fib_values = (np.power(self.lambdas, np.array(indices)[:, np.newaxis]) / np.sqrt(1 + self.lambdas**2)) \
                         @ (self.Q.T @ np.array([f1, f0]))

        fib_values = fib_values.astype(np.int32)
        print(fib_values)
        return fib_values

    def plot_fib(self, f0, f1, indices):
        fib_values = self.compute_fib(f0, f1, indices)
        plt.plot(indices, fib_values, marker = "x", linestyle = "--", color = "red")
        plt.xlabel('$n$')
        plt.ylabel('$F_n$')
        plt.title('Fibounacci sequence')

Do the following tasks in this part.

  • Define an object of the class My_Fib called my_fib.

  • Set f0 = 0, f1 = 1, indices = range(10).

  • Call method my_fib.plot_fib(f0, f1, indices).

Show official solution

Official solution


my_fib = My_Fib()

f0 = 0
f1 = 1
indices = range(10)

my_fib.plot_fib(f0, f1, indices)

Problem 2Neural network basics

100 pts

SummaryCompute gradients of a linear layer by hand, implement it in NumPy and PyTorch, count parameters and analyze rank, then build a ReLU module and an MLP and train it on a synthetic dataset.

    Linear layersGradientsPyTorchMLP

This problem is about the basics of neural network.

Before starting this problem, make sure to run the following code first without change:


""" DO NOT CHANGE """
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(2025)

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

  • All coding tasks shall run on CPUs, not GPUs.

Part 1

5 ptsNon-codingForum thread

The high level idea of affine transformation in math is that for each column vector x∈RN\mathbf{x} \in \Bbb R^N, an affine transformation maps it to another column vector y∈RM\mathbf{y} \in \Bbb R^M via

y=Wx+b,\mathbf{y} = \mathbf{W} \mathbf{x} + \mathbf{b} ,

where

  • W∈RM×N\mathbf{W} \in \Bbb R^{M \times N}.

  • b∈RM\mathbf{b} \in \Bbb R^{M}.

Now, let us study a small-sized problem.

Let

W=[2−313−20125−17−1−370]\mathbf{W} = \begin{bmatrix} 2 & -3 & 1 & 3 & -2 \\ 0 & 1 & 2 & 5 & -1 \\ 7 & -1 & -3 & 7 & 0 \end{bmatrix}

and

b=[10−1]\mathbf{b} = \begin{bmatrix} 1 \\ 0 \\ -1 \end{bmatrix}

and

x=[12−31−2]\mathbf{x} = \begin{bmatrix} 1 \\ 2 \\ -3 \\ 1 \\ -2 \end{bmatrix}

Answer the following questions:

  1. What is the value of NN?

  2. What is the value of MM?

  3. What is the value of y\mathbf{y}.

Questions 1 and 2 do not require reasoning. Question 3 requires reasoning.

Show official solution

Official solution

  1. N=5N = 5.

  2. M=3M = 3.

  3. We have

y=Wx+b=[2−313−20125−17−1−370][12−31−2]+[10−1]=[2⋅1+(−3)⋅2+1⋅(−3)∣3⋅1+(−2)⋅(−2)+10⋅1+1⋅2+2⋅(−3)+5⋅1+(−1)⋅(−2)+07⋅1(−1)⋅2+(−3)⋅(−3)+7⋅1+0⋅(−2)+(−1)]=[1320].\begin{align*} \mathbf{y} & = \mathbf{W} \mathbf{x} + \mathbf{b} \\ & = \begin{bmatrix} 2 & -3 & 1 & 3 & -2 \\ 0 & 1 & 2 & 5 & -1 \\ 7 & -1 & -3 & 7 & 0 \end{bmatrix} \begin{bmatrix} 1 \\ 2 \\ -3 \\ 1 \\ -2 \end{bmatrix} + \begin{bmatrix} 1 \\ 0 \\ -1 \end{bmatrix} \\ & = \begin{bmatrix} 2 \cdot 1 + (-3) \cdot 2 + 1 \cdot (-3) | 3 \cdot 1 + (-2) \cdot (-2) + 1 \\ 0 \cdot 1 + 1 \cdot 2 + 2 \cdot (-3) + 5 \cdot 1 + (-1) \cdot (-2) + 0 \\ 7 \cdot 1 (-1) \cdot 2 + (-3) \cdot (-3) + 7 \cdot 1 + 0 \cdot (-2) + (-1) \end{bmatrix} \\ & = \boxed{\begin{bmatrix} 1 \\ 3 \\ 20 \end{bmatrix} }. \end{align*}

Part 2

10 ptsNon-codingForum thread

Define ∇z f(z)\nabla_{\mathbf{z}} \ f\left( \mathbf{z} \right) to be the gradient of function ff with respect to vector/matrix z\mathbf{z}.

Compute the following gradients. Reasoning is required.

  1. ∇x y\nabla_{\mathbf{x}} \ y.

    The final answer should be in a matrix form.

  2. ∇W y\nabla_{\mathbf{W}} \ y.

    The final answer should be in an element-wise form.

  3. ∇b y\nabla_{\mathbf{b}} \ y.

    The final answer should be in a matrix form.

Show official solution

Official solution

  1. Since y∈RM\mathbf{y} \in \Bbb R^M and x∈RN\mathbf{x} \in \Bbb R^N, ∇x y∈RM×N\nabla_{\mathbf{x}} \ \mathbf{y} \in \Bbb R^{M \times N}.

We have

∂ym∂xn=∂(∑i=0N−1wmixi+bm)∂xn=wmn.\begin{align*} \frac{\partial y_m}{\partial x_n} & = \frac{\partial \left( \sum_{i=0}^{N-1} w_{mi} x_i + b_m \right)}{\partial x_n} \\ & = w_{mn} . \end{align*}

Therefore,

∇x y=W.\boxed{\nabla_{\mathbf{x}} \ \mathbf{y} = \mathbf{W} }.
  1. Since y∈RM\mathbf{y} \in \Bbb R^M and W∈RM×N\mathbf{W} \in \Bbb R^{M \times N}, ∇W y∈RM×M×N\nabla_{\mathbf{W}} \ \mathbf{y} \in \Bbb R^{M \times M \times N}.

We have

∂ym∂wkn=∂(∑i=0N−1wmixi+bm)∂wkn=xnδmk.\begin{align*} \frac{\partial y_m}{\partial w_{kn}} & = \frac{\partial \left( \sum_{i=0}^{N-1} w_{mi} x_i + b_m \right)}{\partial w_{kn}} \\ & = \boxed{x_n \delta_{mk}}. \end{align*}
  1. Since y∈RM\mathbf{y} \in \Bbb R^M and b∈RM\mathbf{b} \in \Bbb R^M, ∇b y∈RM×M\nabla_{\mathbf{b}} \ \mathbf{y} \in \Bbb R^{M \times M}.

We have

∂ym∂wk=∂(∑i=0N−1wmixi+bm)∂bk=δmk.\begin{align*} \frac{\partial y_m}{\partial w_k} & = \frac{\partial \left( \sum_{i=0}^{N-1} w_{mi} x_i + b_m \right)}{\partial b_k} \\ & = \delta_{mk} . \end{align*}

Therefore,

∇b y=IM×M.\boxed{\nabla_{\mathbf{b}} \ \mathbf{y} = \mathbf{I}_{M \times M}} .

In this part, you are asked to build an affine transformation module from scratch by using NumPy, NOT PyTorch or TensorFlow.

Define such a class as My_Linear_NumPy.

  • Attributes

    • in_features: Number of input features

    • out_features: Number of output features

    • weight: This refers to matrix W\mathbf{W} in Part 1. The shape is (out_features, in_features).

    • bias: This refers to vector b\mathbf{b} in Part 1. The shape is (out_features,).

    • random_seed: The NumPy random seed number used to generate initial values of weight and bias.

  • Method __init__:

    • To initialize an object in this class, you need to specify in_features and out_features.

    • You may initialize the object by specifying a value for random_seed. If it is not specified, then its default value is 42.

    • The initial values of weight and bias are random that follow standard normal distributions generated with the seed number attributerandom_seed.

  • Method forward:

    • Input x: numpy array with shape (n_0, n_1, ..., n_{d-1}, in_features) with an arbitrary dimension d=0,1,⋯d = 0, 1, \cdots.

    • Output y: numpy array with shape (n_0, n_1, ..., n_{d-1}, out_features).

    • The affine transformation works in a way that given the first d indices in x and y, it does affine transformation along the last axis of x and y.

  • Do not use any loop in your code.

Show official solution

Official solution


class My_Linear_NumPy:
    def __init__(self, in_features, out_features, random_seed=42):
        self.in_features = in_features
        self.out_features = out_features
        self.random_seed = random_seed
        np.random.seed(self.random_seed)
        self.weight = np.random.randn(self.out_features, self.in_features)
        self.bias = np.random.randn(self.out_features)

    def forward(self, x):
        return np.sum(x[..., np.newaxis] * self.weight.T, axis = -2) + self.bias

Do the following tasks in this part.

  1. Construct an object in the class My_Linear_Numpy called linear_model_np.

  2. Set in_features = 3 and out_features = 5.

  3. Create multiple X with the following different shapes, but common numpy random seed number 2025 and the same standard normal distribution.

    • (in_features,)

    • (10,in_features)

    • (10,20,in_features)

    • (10,20,30,in_features)

    After generating X, reset the numpy random seed number to its default value.

  4. We call our constructed function with each of the above X as the input. Print the shape of each output.

Show official solution

Official solution


in_features = 3
out_features = 5

linear_model_np = My_Linear_NumPy(in_features, out_features)

np.random.seed(2025)

X_list = [np.random.randn(in_features), np.random.randn(10,in_features), np.random.randn(10,20,in_features), np.random.randn(10,20,30,in_features)]

np.random.seed()

for X in X_list:
    print(linear_model_np.forward(X).shape)

In this part, you are asked to program with PyTorch, NOT NumPy.

Define a deep neural network module (class) named Linear_Model.

It has the following architecture:

  • 2 layers: 1 hidden layer and 1 output layer.

  • No activation function. That is, the connection between two consecutive layers is only an affine transformation.

Show official solution

Official solution


class Linear_Model(nn.Module):
    def __init__(self, in_features, hidden_features, out_features):
        super().__init__()
        self.in_features = in_features
        self.hidden_features = hidden_features
        self.out_features = out_features
        self.linear0 = nn.Linear(in_features, hidden_features)
        self.linear1 = nn.Linear(hidden_features, out_features)

    def forward(self, x):
        x = self.linear0(x)
        x = self.linear1(x)
        return x

Part 6

5 ptsNon-codingForum thread

We make the following modifications on the previous part.

  • We consider a special symmetric neural network that out_features = in_features.

  • No bias in all affine transformations.

  • The transformation matrix from the hidden layer to the output layer is binded to be the transpose of the transformation matrix from the input layer to the hidden layer

What is the total number of learnable parameters in this model?

  • Reasoning is not required.
Show official solution

Official solution

in_features * hidden_features

Part 7

5 ptsNon-codingForum thread

This question follows Part 6.

Denote by W∈Rhidden_features×input_features\mathbf{W} \in \Bbb R^{hidden\_features \times input\_features} the transformation matrix from the input layer to the hidden layer.

Given input x∈Rinput_features\mathbf{x} \in \Bbb R^{input\_features}, write down the formula of the output y\mathbf{y} and its shape.

  • Reasoning is not required.
Show official solution

Official solution

y=W⊤Wx∈Rinputfeatures.\begin{align*} \mathbf{y} & = \mathbf{W}^\top \mathbf{W} \mathbf{x} \\ & \in \Bbb R^{input_features} . \end{align*}

Part 8

10 ptsNon-codingForum thread

This question follows Part 7.

Denote r=rank(W)r = \text{rank} \left( \mathbf{W} \right).

Compute the rank of W⊤W\mathbf{W}^\top \mathbf{W}.

  • Reasoning is required.
Show official solution

Official solution

Let W\mathbf{W} be with the following singular value decomposition:

W=∑i=0r−1uiσivi⊤.\mathbf{W} = \sum_{i = 0}^{r-1} \mathbf{u}_i \sigma_i \mathbf{v}_i^\top .

Hence,

W⊤W=(∑i=0r−1uiσivi⊤)⊤(∑j=0r−1ujσjvj⊤)=∑i=0r−1∑j=0r−1viσiui⊤ujσjvj⊤=∑i=0r−1∑j=0r−1viσiσjδijvj⊤=∑i=0r−1viσi2vj⊤.\begin{align*} \mathbf{W}^\top \mathbf{W} & = \left( \sum_{i = 0}^{r-1} \mathbf{u}_i \sigma_i \mathbf{v}_i^\top \right)^\top \left( \sum_{j = 0}^{r-1} \mathbf{u}_j \sigma_j \mathbf{v}_j^\top \right) \\ & = \sum_{i = 0}^{r-1} \sum_{j = 0}^{r-1} \mathbf{v}_i \sigma_i \mathbf{u}_i^\top \mathbf{u}_j \sigma_j \mathbf{v}_j ^\top \\ & = \sum_{i = 0}^{r-1} \sum_{j = 0}^{r-1} \mathbf{v}_i \sigma_i \sigma_j \delta_{ij} \mathbf{v}_j^\top \\ & = \sum_{i = 0}^{r-1} \mathbf{v}_i \sigma_i^2 \mathbf{v}_j^\top . \end{align*}

This is the singular value decomposition of WW⊤\mathbf{W} \mathbf{W}^\top. Therefore, the rank of this matrix is also rr.

This question follows Part 6.

In this part, you are asked to program with PyTorch, not NumPy.

Build a deep neural network class named as Symmetric_Linear_Model that meets the modifications imposed in Part 6.

Show official solution

Official solution


class Symmetric_Linear_Model(nn.Module):
    def __init__(self, in_features, hidden_features):
        super().__init__()
        self.in_features = in_features
        self.hidden_features = hidden_features
        self.linear0 = nn.Linear(in_features, hidden_features, bias = False)

    def forward(self, x):
        x = self.linear0(x)
        x = torch.sum(self.linear0.weight * x.reshape(*x.shape, 1), dim = -2)
        return x

Rectified Linear Unit, or the "ReLU", is one of the most common used function in deep learning. It is defined as

ReLU(x)=max⁡{0,x}.\text{ReLU}(x)= \max \left\{ 0,x \right\} .

In this part, you are asked to use PyTorch to build a ReLU class named My_ReLU that subclasses nn.module.

A successful class works in the following ways:

  • The initialization of an object in My_ReLU does not take any input.

  • Suppose we have a My_ReLU object called activiation0. When we call activiation0(x)with input x that is a tensor x with an arbitrary dimension and shape, we get an output y from the element-wise ReLU acvitivation on x.

Show official solution

Official solution


class My_ReLU(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        return torch.max(torch.zeros_like(x), x)

It is known by math that the combination of several linear layers can still be seen as an linear layer, so we can add some non-linear activation functions, such as ReLU, in between to get better effect.

Multi-Layer Perceptron (MLP), is such a neural network composed of multiple fully connected layers with non-linear activations, commonly used in deep learning.

Please define a class called My_MLP_Model that subclasses nn.Module and works in the following ways:

  • The architecture consists of two hidden layers and one output layer.

  • Each hidden layer consists of an affine transformation module and a ReLU activiation module.

  • Each affine transformation module shall be initialized with the build-in class nn.Linear.

  • Each ReLU activiatio nmodule shall be initialized with your self-defined class My_ReLU.

Show official solution

Official solution


class My_MLP_Model(nn.Module):
    def __init__(self, in_features, hidden_features1, hidden_features2, out_features):
        super().__init__()
        self.in_features = in_features
        self.hidden_features1 = hidden_features1
        self.hidden_features2 = hidden_features2
        self.out_features = out_features
        self.seq = nn.Sequential(
            nn.Linear(in_features, hidden_features1),
            My_ReLU(),
            nn.Linear(hidden_features1, hidden_features2),
            My_ReLU(),
            nn.Linear(hidden_features2, out_features)
        )

    def forward(self, x):
        x = self.seq(x)
        return x

After building our deep neural network architecture in Part 11 and before using it to train our model, we need to prepare our training dataset.

Let us look at a simple application of deep neural network in studying harmonic motion in physics.

Write code to construct the following training dataset:

  • Use sample_size to store the number of samples. Set the value as 1000.

  • Define x_train as a tensor whose shape is (sample_size,) and the value on each entry is uniformly drawn between 0 and 1.

  • Define y_train as a tensor whose values are obtained from the following element-wise mapping from x_train:

    y=sin⁡(2πx)+0.1⋅N(0,1),y = \sin \left( 2 \pi x \right) + 0.1 \cdot \mathcal N \left( 0, 1 \right) ,

    where N(0,1)\mathcal N \left( 0, 1 \right) is a standard normal random variable.

  • Print the dimensions of x_train and y_train.

  • Print the shapes of x_train and y_train.

Show official solution

Official solution


sample_size = 1000
x_train = torch.rand(sample_size,)
y_train = torch.sin(2 * np.pi * x_train) + 0.1 * torch.randn_like(x_train)

print(x_train.ndim)
print(y_train.ndim)

print(x_train.shape)
print(y_train.shape)

In this part, we use the training dataset constructed in Part 12 to train a model defined in Part 11.

  • Use mean-squred error (MSE) as the loss function.

  • Use Adam as the optimization algorithm.

  • Do whole-batch training in each epoch.

  • After every 10 epochs, print the following sentence:

    Epoch: XXX. Loss: XXX.

    The loss value should be with 4 decimal places.

  • Generate an epoch-MSE loss plot after completing the training. Set the x-label as epoch and the y-label as MSE loss.

Show official solution

Official solution

# HYPERPARAMETERS
''' DO NOT CHANGE ANYTHING IN THIS CODE CELL '''

hidden_features1 = 32
hidden_features2 = 16

num_epochs = 500
learning_rate = 1e-3

my_mlp_model = My_MLP_Model(1, hidden_features1, hidden_features2, 1)
optimizer = torch.optim.Adam(my_mlp_model.parameters(), lr = learning_rate)
loss_fn = torch.nn.MSELoss()

loss_list_plot = []

for epoch in range(num_epochs):
    optimizer.zero_grad()
    y_pred = my_mlp_model(x_train.reshape(-1,1))
    loss = loss_fn(y_pred, y_train.reshape(-1,1))
    loss.backward()
    optimizer.step()

    if epoch % 10 == 0:
        print(f"Epoch: {epoch}. Loss: {loss.item():.4f}")
        loss_list_plot.append(loss.item())

plt.plot(loss_list_plot)
plt.xlabel("epoch")
plt.ylabel("MSE loss")
plt.show()

Problem 3Titanic survival with logistic regression

100 pts

SummaryClean and encode the Titanic data with pandas, derive the gradient and Hessian of the log-likelihood and prove its concavity, then implement logistic regression trained by gradient descent and Newton's method.

    pandasData preprocessingLogistic regressionConvexity

Before starting this problem, make sure to run the following code first without any change:

# DO NOT CHANGE

import numpy as np

import pandas as pd

import copy

import matplotlib.pyplot as plt

from sklearn.preprocessing import StandardScaler

np.random.seed(2025)

""" END OF THIS PART """

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

  • All coding tasks shall run on CPUs, not GPUs.

We study the dataset USAAIO_2025_round1_prob3_train.csv provided in this contest.

The dataset can be found here:

url = "https://drive.google.com/file/d/125YsFPS2nCNRvYyy1tgnD8RhYIUglLX9/view?usp=sharing"

Do the following tasks in this part.

  1. Load USAAIO_2025_round1_prob3_train.csv into a pandas DataFrame object called df_1.

  2. Print the first 10 rows.

  3. Define a function called data_summary that

    • Takes a DataFrame object as an input.

    • Prints the shape of the DataFrame.

    • Prints the data type for each column.

    • Prints the count of missing values for each column.

    • Delivers no output.

  4. After defining the above function, call it by feeding df_1 to it.

Show official solution

Official solution


df_1 = pd.read_csv('USAAIO_2025_round1_prob3_train.csv')
print(df_1.head(10))

def data_summary(df):
    print(f"Shape: {df.shape}")
    print(f"Data Types: {df.dtypes}")
    print(f"Missing Values per Column: {df.isnull().sum()}")

data_summary(df_1)

Do the following tasks in this part.

  1. Create a DataFrame object called df_2 that keeps the following columns in df_1 (all other columns in df_1 shall not appear in df_2):

    • Survived

    • Sex

    • Age

    • SibSp

    • Parch

    • Fare

    • Embarked

  2. Print the first 5 rows of df_2.

  3. Print the shape of df_2.

Show official solution

Official solution


df_2 = df_1[['Survived', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']]

print(df_2.head())

Do the following tasks in this part.

  1. In df_2, remove all rows that contain null (missing) values.

  2. Save the updated DateFrame object as df_3 (that is, the change of df_2 should not be inplace).

  3. For df_3, print the count of missing values per column.

  4. Print the shape of df_3.

Show official solution

Official solution

df_3 = df_2.dropna()

print(df_3.isnull().sum())

print(df_3.shape)

Do the following tasks in this part.

  1. Create a deep copy of df_3, named df_4.

  2. In df_4, create a new column called GroupSize. Its value is equal to SibSp + Parch + 1.

  3. Print the first five rows of df_3 and df_4.

  4. Print the shapes of df_3 and df_4.

Show official solution

Official solution

df_4 = copy.deepcopy(df_3)

df_4['GroupSize'] = df_4['SibSp'] + df_4['Parch'] + 1

print(df_3.head())
print(df_4.head())

print(df_3.shape)
print(df_4.shape)

Do the following tasks in this part.

  1. Remove columns SibSp and Parch in df_4, and save this new DataFrame object as df_5 (changes on df_4 should not be inplace).

  2. Print the first five rows of df_4 and df_5.

  3. Print the shapes of df_4 and df_5.

Show official solution

Official solution

df_5 = df_4.drop(columns=['SibSp', 'Parch'])

print(df_4.head())
print(df_5.head())

print(df_4.shape)
print(df_5.shape)

Part 6

5 ptsCoding + reasoningForum thread

In df_5, columns Sex and Embarked are categorical data.

Do the following tasks to process these categorical data.

  1. To do logistic regression on this dataset, we need to do one hot encoding on these two columns. Explain why?

  2. Do one hot encoding on these two columns. Set drop_first = True and dtype = np.int8. Save the new dataframe object as df_6.

  3. Explain what drop_first = True means and why we do so.

  4. Print the first five rows of df_5 and df_6.

  5. Print the shapes of df_5 and df_6.

Show official solution

Official solution


# Question 1
"""
Answer:

Logistic regression requires numerical data, not categorical data.

"""

# Question 2
# Answer: (put your code here)

df_6 = pd.get_dummies(df_5, columns=['Sex', 'Embarked'], drop_first = True, dtype = np.int8)

# Question 3
"""
Answer:

Suppose a categorical variable takes value k chosen from K categories, indexed as 0, 1, ..., K-1.

By setting drop_first = True, it is replaced by a vector with shape K-1.

If k = 0, then in this vector, all entries are 0.

If k is not 0, then in this vector, the (k-1)th entry (entry indices starts from 0 and ends with K-2) is 1 and all other entries are 0.

Setting drop_first = True avoids multicollinearity.

"""

# Question 4
# Answer: (put your code here)

print(df_5.head())
print(df_6.head())

# Question 5
# Answer: (put your code here)

print(df_5.shape)
print(df_6.shape)

Do the following tasks in this part.

  1. Define X that keeps all features in df_6 and drops the label column Survived.

  2. Define y that keeps the label column Survived in df_6 only.

  3. Print the types of objects X and y.

  4. Print the first five rows of X and the first five elements in y.

Show official solution

Official solution

X = df_6.drop(columns=['Survived'])
y = df_6['Survived']

print(type(X))
print(type(y))

print(X.head())
print(y.head())

Do the following tasks in this part.

  1. Define a function called my_train_test_split that splits the whole dataset into the training component and the test/validation component.

    • The split is random

    • Inputs

      • X: A DataFrame object of features of all sample data.

      • y: A Series object of labels of all sample data.

      • test_size: It takes a value between 0 and 1 that denotes the fraction of samples used for testing. That is, the number of samples used for testing is int(total number of samples * test_size).

    • Outputs

      • X_train: It keeps samples in X for training.

      • X_test: It keeps samples in X for testing.

      • y_train: It keeps samples in y for training.

      • y_test: It keeps samples in y for testing.

  2. Call this function with inputs

    • X = X

    • y = y

    • test_state = 0.2

  3. Print object types and shapes of X_train, X_test, y_train, y_test.

Show official solution

Official solution

def my_train_test_split(X, y, test_size):
    num_samples = X.shape[0]
    num_test_samples = int(num_samples * test_size)
    indices = np.random.permutation(num_samples)
    test_indices = indices[:num_test_samples]
    train_indices = indices[num_test_samples:]

    X_train = X.iloc[train_indices]
    X_test = X.iloc[test_indices]
    y_train = y.iloc[train_indices]
    y_test = y.iloc[test_indices]

    return X_train, X_test, y_train, y_test

X_train, X_test, y_train, y_test = my_train_test_split(X, y, 0.2)

print(type(X_train))
print(type(X_test))
print(type(y_train))
print(type(y_test))

print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)

Use StandardScaler that has been imported from sklearn.preprocessing (DO NOT IMPORT IT AGAIN) to do the following tasks.

  1. Create an object called scaler.

  2. Use scaler.fit_transform to scale each column in X_train to standard normal. Save the scaled training dataset as X_train_scaled.

  3. Use scaler.transform to scale X_test. Save the scaled test dataset as X_test_scaled.

  4. Add a column to X_train_scaled with all 1s. Do the same thing for X_test_scaled.

  5. Print the types of objects X_train_scaled and X_test_scaled.

  6. Print the shapes of objects X_train_scaled and X_test_scaled.

  7. Print the first five rows of X_train_scaled and X_test_scaled.

Show official solution

Official solution

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

X_train_scaled = np.concat([X_train_scaled, np.ones((X_train_scaled.shape[0], 1))], axis=1)
X_test_scaled = np.concat([X_test_scaled, np.ones((X_test_scaled.shape[0], 1))], axis=1)

print(type(X_train_scaled))
print(type(X_test_scaled))

print(X_train_scaled.shape)
print(X_test_scaled.shape)

print(X_train_scaled[:5])
print(X_test_scaled[:5])

Part 10

5 ptsNon-codingForum thread

So far, we have finished preprocessing our dataset. We use this dataset for the purpose of doing binary classification.

In all remaining parts in this problem, we will train a logistic regression model with our preprocessed data and test its performance.

Let all training samples be indexed as 0,1,⋯ ,N−10, 1, \cdots , N-1. For the nnth sample, denote by x(n)∈Rd×1\mathbf{x}^{(n)} \in \Bbb R^{d \times 1} a column vector of all features and y(n)∈{0,1}y^{(n)} \in \left\{ 0, 1 \right\} its ground-truth label.

In the logistic regression, denote by β∈Rd×1\mathbf{\beta} \in \Bbb R^{d \times 1} the learnable parameters.

Thus, our predicted label is determined according to:

ypredict(n)={1,with probability σ(x(n),⊤β)0,with probability 1−σ(x(n),⊤β)y^{(n)}_{predict} = \begin{cases} 1 , & \text{with probability } \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \\ 0, & \text{with probability } 1 - \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \\ \end{cases}

where

σ(z)=11+e−z\sigma \left( z \right) = \frac{1}{1 + e^{-z}}

is the sigmoid function.

Do the following task in this part.

To train our model, we need to solve the following optimization problem:

min⁡β L(β).\min_{\mathbf{\beta}} \ L \left(\mathbf{\beta} \right) .

Write down the loss function L(β)L \left(\mathbf{\beta} \right) in the following form (reasoning is not required):

L(β)=∑n=0N−1⋯ .L \left(\mathbf{\beta} \right) = \sum_{n=0}^{N-1} \cdots .
Show official solution

Official solution

L(β)=∑n=0N−1−(y(n)log⁡(σ(x(n),⊤β))+(1−y(n))log⁡(1−σ(x(n),⊤β))).\boxed{L \left( \mathbf{\beta} \right) = \sum_{n = 0}^{N-1} - \left( y^{(n)} \log \left( \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \right) + \left( 1 - y^{(n)} \right) \log \left( 1 - \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \right) \right) } .

Part 11

5 ptsNon-codingForum thread

Compute

dσ(z)dz.\frac{d \sigma \left( z \right)}{dz} .
  • Express your answer using σ(z)\sigma \left( z \right) only (eze^z or e−ze^{-z} should not appear in your final solution).

  • Reasoning is required.

Show official solution

Official solution

We have

dσ(z)dz=e−z(1+e−z)2=σ(z)(1−σ(z)).\begin{align*} \frac{d \sigma \left( z \right)}{d z} & = \frac{e^{-z}}{\left( 1 + e^{-z} \right)^2} \\ & = \boxed{ \sigma \left( z \right) \left( 1 - \sigma \left( z \right) \right) } . \end{align*}

Part 12

5 ptsNon-codingForum thread

In this part, you are asked to compute ∇β L(β)\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) and express your solutions in two forms. Reasoning is not required.

  1. Write ∇β L(β)\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) in the following summation form:

    ∇β L(β)=∑n=0N−1⋯ .\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) = \sum_{n=0}^{N-1} \cdots .
  2. Denote

    X=[x(0),⊤x(1),⊤⋮x(N−1),⊤]\mathbf{X} = \begin{bmatrix} \mathbf{x}^{(0), \top} \\ \mathbf{x}^{(1), \top} \\ \vdots \\ \mathbf{x}^{(N-1), \top} \end{bmatrix}

    and

    y=[y(0)y(1)⋮y(N−1)]\mathbf{y} = \begin{bmatrix} y^{(0)} \\ y^{(1)} \\ \vdots \\ y^{(N-1)} \end{bmatrix}

    and

    z=[σ(x(0),⊤β)σ(x(1),⊤β)⋮σ(x(N−1),⊤β)]\mathbf{z} = \begin{bmatrix} \sigma \left( \mathbf{x}^{(0), \top} \mathbf{\beta} \right) \\ \sigma \left( \mathbf{x}^{(1), \top} \mathbf{\beta} \right) \\ \vdots \\ \sigma \left( \mathbf{x}^{(N-1), \top} \mathbf{\beta} \right) \end{bmatrix}

    Write ∇β L(β)\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) in terms of X\mathbf{X}, y\mathbf{y}, z\mathbf{z} with matrix operations (the summation symbol is not allowed).

Show official solution

Official solution

We have

∇β L(β)=∑n=0N−1(σ(x(n),⊤β)−y(n))x(n)=X⊤(z−y).\begin{align*} \nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) & = \boxed{ \sum_{n = 0}^{N-1} \left( \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) - y^{(n)} \right) \mathbf{x}^{(n)} } \\ & = \boxed{\mathbf{X}^\top \left( \mathbf{z} - \mathbf{y} \right)} . \end{align*}

Part 13

5 ptsNon-codingForum thread

In this part, you are asked to compute ∇β2 L(β)\nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) and express your solutions in two forms. Reasoning is not required.

  1. Write ∇β2 L(β)\nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) in the following summation form:

    ∇β L(β)=∑n=0N−1⋯ .\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) = \sum_{n=0}^{N-1} \cdots .
  2. Denote

    Z=[z00⋯00z1⋯0⋮⋮⋱000⋯zN−1].\mathbf{Z} = \begin{bmatrix} z_0 & 0 & \cdots & 0 \\ 0 & z_1 & \cdots & 0 \\ \vdots & \vdots & \ddots & 0 \\ 0 & 0 & \cdots & z_{N-1} \end{bmatrix} .

    Write ∇β2 L(β)\nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) in terms of X\mathbf{X}, Z\mathbf{Z} with matrix operations (the summation symbol is not allowed).

Show official solution

Official solution

We have

∇β2 L(β)=∑n=0N−1σ(x(n),⊤β)(1−σ(x(n),⊤β))x(n)x(n)⊤=X⊤ZX.\begin{align*} \nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) & = \boxed{ \sum_{n = 0}^{N-1} \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \left( 1 - \sigma \left( \mathbf{x}^{(n), \top} \mathbf{\beta} \right) \right) \mathbf{x}^{(n)} \mathbf{x}^{(n)^\top} } \\ & = \boxed{\mathbf{X}^\top \mathbf{Z} \mathbf{X} } . \end{align*}

Part 14

5 ptsNon-codingForum thread

Prove that L(β)L \left( \mathbf{\beta} \right) is a (weakly) concave function.

  • Reasoning is required.
Show official solution

Official solution

Because σ(⋅)∈[0,1]\sigma \left( \cdot \right) \in \left[ 0 , 1 \right] and x(n)x(n)⊤\mathbf{x}^{(n)} \mathbf{x}^{(n)^\top} is a positive semidefinite matrix, we have that ∇β2 L(β)\nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) is a positive semidefinite matrix.

Therefore, L(β)L \left( \mathbf{\beta} \right) is (weakly) concave.

Part 15

5 ptsNon-codingForum thread

To learn β\mathbf{\beta}, we do whole-batch iteration with the gradient descent algorithm and the Netwon's method.

In this part, denote by η>0\eta > 0 the learning rate.

Do the following tasks in this part (reasoning is not required).

  1. Write down the gradient descent algorithm in the following form:

    β←β−η⋅???.\mathbf{\beta} \leftarrow \mathbf{\beta} - \eta \cdot \boxed{???} .
  2. Write down the Newton's method in the following form:

    β←β−η⋅???.\mathbf{\beta} \leftarrow \mathbf{\beta} - \eta \cdot \boxed{???} .
Show official solution

Official solution

β←β−η⋅∇β L(β).\mathbf{\beta} \leftarrow \mathbf{\beta} - \eta \cdot \boxed{\nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right)} .
β←β−η⋅(∇β2 L(β))−1(∇β L(β)).\mathbf{\beta} \leftarrow \mathbf{\beta} - \eta \cdot \boxed{\left( \nabla_{\mathbf{\beta}}^2 \ L \left( \mathbf{\beta} \right) \right)^{-1} \left( \nabla_{\mathbf{\beta}} \ L \left( \mathbf{\beta} \right) \right)} .

Define a function called my_signoid:

  • Input: A numpy array with any shape.

  • Output: Elementwise sigmoid functional values.

  • No loop in the body of your function.

Show official solution

Official solution

def my_sigmoid(z):
    return 1 / (1 + np.exp(-z))

Construct a class called My_Log_Reg whose objects are logistic regression models.

  • Method __init__

    • Inputs

      • solver: The value must be GD or Newton. Otherwise, it raises an error message Invalid solver.

      • lr: The learning rate.

      • num_iter: The total number of iterations.

    • Attributes

      • solver

      • lr

      • num_iter

      • coef_: β\mathbf{\beta} in our theoretical model. It shall be a 1-dim numpy array with shape (d,).

  • Method fit

    • Inputs

      • X: Features in a training dataset. The shape is (N_train,d).

      • y: Ground-truth labels in a training dataset. The shape is (N_train,)

    • In the body of this method

      • Use the configured solver to compute coef_.

      • Do whole-batch iteration.

      • After finishing training coef_, generate a plot about the loss function vs iteration.

        • The x-label is iter.

        • The y-label is loss.

        • The title is the optimization method: either GD or Netwon.

      • The only loop that you can use is the whole-batch iteration. Within each iteration, when you update coef_ by applying either GD or Newton, you are not allowed to use any loop.

    • Output

      • None
  • Method predict

    • Input

      • X: Features in a test dataset. The shape is (N_test,d).
    • Output

      • y_pred: Predicted labels in the test dataset. The shape is (N_test,).
  • Method score

    • Input

      • X: Features in a test dataset. The shape is (N_test,d).

      • y: Ground-truth labels in the test dataset. The shape is (N_test,).

    • Output

      • accuracy_score: The accuracy score of the prediction of y.
Show official solution

Official solution


class My_Log_Reg:
    def __init__(self, solver, lr, num_iter):
        self.solver = solver
        self.lr = lr
        self.num_iter = num_iter
        self.coef_ = None

    def fit(self, X, y):
        N, d = X.shape
        self.coef_ = np.zeros(d)
        loss_history = []
        loss = -np.sum(y * np.log(my_sigmoid(X @ self.coef_)) + (1 - y) * np.log(1 - my_sigmoid(X @ self.coef_)))
        loss_history.append(loss)

        if self.solver == 'GD':
            for i in range(self.num_iter):
                params_grad = X.T @ (my_sigmoid(X @ self.coef_) - y)
                self.coef_ -= self.lr * params_grad
                loss = -np.sum(y * np.log(my_sigmoid(X @ self.coef_)) + (1 - y) * np.log(1 - my_sigmoid(X @ self.coef_)))
                loss_history.append(loss)

            plt.plot(loss_history)
            plt.xlabel('iter')
            plt.ylabel('loss')
            plt.title('self.solver')
            plt.show()
        elif self.solver == 'Newton':
            for i in range(self.num_iter):
                params_grad = X.T @ (my_sigmoid(X @ self.coef_) - y)
                params_Hessian = X.T @ np.diag(my_sigmoid(X @ self.coef_) * (1 - my_sigmoid(X @ self.coef_))) @ X
                self.coef_ -= self.lr * np.linalg.inv(params_Hessian) @ params_grad
                loss = -np.sum(y * np.log(my_sigmoid(X @ self.coef_)) + (1 - y) * np.log(1 - my_sigmoid(X @ self.coef_)))
                loss_history.append(loss)

            plt.plot(loss_history)
            plt.xlabel('iter')
            plt.ylabel('loss')
            plt.title('self.solver')
            plt.show()
        else:
            raise ValueError('Invalid solver')

    def predict(self, X):
        y_pred = np.where(my_sigmoid(X @ self.coef_) >= 0.5, 1, 0)
        return y_pred

    def score(self, X, y):
        y_pred = self.predict(X)
        accuracy_score = np.mean(y_pred == y)
        return accuracy_score

Do the following tasks in this problem.

  1. Define two models:

    • model_GD = My_Log_Reg(solver='GD', lr=.01, num_iter=200)

    • model_Newton = My_Log_Reg(solver='Newton', lr=.1, num_iter=200)

  2. For each model,

    • Use the training dataset to train it.

    • Print the trained coefficients coef_.

    • Use the test dataset to compute the accuracy score. Print it.

Show official solution

Official solution

model_GD = My_Log_Reg(solver='GD', lr=.001, num_iter=200)
model_GD.fit(X_train_scaled, y_train)
print(model_GD.coef_)
print(model_GD.score(X_test_scaled, y_test))

model_Newton = My_Log_Reg(solver='Newton', lr=.1, num_iter=200)
model_Newton.fit(X_train_scaled, y_train)
print(model_Newton.coef_)
print(model_Newton.score(X_test_scaled, y_test))

Problems and solutions © USA-NA-AIO (USAAIO). Shown for educational purposes with attribution; summaries and topic tags are written by ResAI. Source: usaaio.org