#295Linear regression — sum of squared residuals (SSR)Easy

Linear regression — sum of squared residuals (SSR)

Background

The sum of squared residuals (SSR) is the loss linear regression minimises. For a line y^i=mxi+c\hat{y}_i = m x_i + c it is

SSR=J(m,c)=i=1n(yi(mxi+c))2\text{SSR} = J(m, c) = \sum_{i=1}^{n} \bigl(y_i - (m x_i + c)\bigr)^2

Squaring serves two purposes: it stops positive and negative residuals cancelling, and it punishes a big miss far more than a small one (an error twice as large adds four times as much). A single far-off point can dominate the total — exactly the effect the lesson's draggable SSR explorer shows.

Problem statement

Implement ssr(x, y, m, c) that returns the scalar SSR of the line y=mx+cy = m x + c on the data (x, y).

Input

  • x — array-like of inputs.
  • y — array-like of true targets, the same length.
  • mfloat, the slope.
  • cfloat, the intercept.

Output

Returns a Python float: i(yi(mxi+c))2\sum_i (y_i - (m x_i + c))^2.

Examples

Example 1 — a perfect fit scores zero

Input:  x = [2, 4, 5], y = [2, 8, 11], m = 3, c = -4
Output: 0.0

Explanation: the line y=3x4y = 3x - 4 passes through every point, so every residual is 0.

Example 2 — the lesson's bad starting guess

Input:  x = [51], y = [149], m = 1, c = 1
Output: 9409.0

Explanation: prediction =52= 52, residual =14952=97= 149 - 52 = 97, and 972=940997^2 = 9409.

Constraints

  • Build the prediction mx+cm x + c, take the residual yy^y - \hat{y}, square, and sum.
  • Return a plain float (wrap the NumPy scalar in float()).

Notes

  • This is the height of the "mountain" in the lesson's gradient-descent analogy. Gradient descent's whole job is to walk this number downhill — which is exactly the next problem.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Example: perfect fit scores zero
  • Reference bad guess: m=1, c=1 at x=51
  • Sample line with mixed residuals