QuantumCore

Hands-on lab · 1 step

Gradient of the mean-squared error

Implement the vectorised gradient of the mean-squared-error loss L(w,b)=1m∑i=1m(w⊤xi+b−yi)2\mathcal L(w,b)=\tfrac1m\sum_{i=1}^m(w^\top x_i+b-y_i)^2 of a linear model, namely ∇wL=2m∑irixi=2mX⊤r\nabla_w\mathcal L=\tfrac2m\sum_i r_ix_i=\tfrac2mX^\top r and ∂bL=2m∑iri\partial_b\mathcal L=\tfrac2m\sum_ir_i with residuals ri=w⊤xi+b−yir_i=w^\top x_i+b-y_i. The function is graded on one visible worked example and five hidden random problems with up to 5050 samples and 55 features, to absolute tolerance 10−910^{-9}.

0/1 step passedBest score 0/100

Step 1: Implement mseGradient

Complete the TypeScript function

mseGradient(w: number[], b: number, X: number[][], y: number[]): { gw: number[]; gb: number }

for the linear model y^i=w⊤xi+b\hat y_i=w^\top x_i+b and the loss

L(w,b)=1m∑i=1m(y^i−yi)2.\mathcal L(w,b)=\frac1m\sum_{i=1}^m\big(\hat y_i-y_i\big)^2 .

Shapes. w has dd entries; X has mm rows (X[i] is the feature vector xi∈Rdx_i\in\mathbb R^d); y has mm targets. Return gw with dd entries, gw[k] =∂L/∂wk=\partial\mathcal L/\partial w_k, and the number gb =∂L/∂b=\partial\mathcal L/\partial b. Do not modify the inputs.

What to compute. With residuals ri=y^i−yir_i=\hat y_i-y_i,

∇wL=2m∑i=1mri xi=2mX⊤r,∂L∂b=2m∑i=1mri.\nabla_w\mathcal L=\frac2m\sum_{i=1}^m r_i\,x_i=\frac2m X^\top r,\qquad \frac{\partial\mathcal L}{\partial b}=\frac2m\sum_{i=1}^m r_i .

Tests (all compared with absolute tolerance 10−910^{-9}):

  • worked-example (visible): w=(0.5,−0.25)w=(0.5,-0.25), b=0.1b=0.1, X=(1234)X=\begin{pmatrix}1&2\\3&4\end{pmatrix}, y=(1,2)y=(1,2). The predictions are y^=(0.1,0.6)\hat y=(0.1,0.6), the residuals r=(−0.9,−1.4)r=(-0.9,-1.4), hence gw =(-5.1,-7.4)and‘gb‘ and `gb` =−2.3=-2.3.
  • random-1 to random-5 (hidden): random problems with 5≤m≤505\le m\le50 samples and 1≤d≤51\le d\le5 features, entries in [−2,2][-2,2]. Only their arguments are sent to your browser; the expected gradients stay on the server.
TypeScript: export mseGradient · 6 tests · imports: quantumcore, quantumcore/qml
Run the tests first; the results of your latest run are submitted.