CS 460G Midterm Hub / Notebooks / Linear Regression
Python notebook · Linear-Regression.ipynb

Linear Regression

Diabetes progression from BMI — least squares end to end

practice nbQ6 material

The regression twin of the classification notebook, with one structural difference: the target is continuous, so the metrics change and the "confusion matrix" disappears.

Cell-by-cell

1. Loading from a URL, not a CSV

diab = np.loadtxt('https://www4.stat.ncsu.edu/~boos/var.select/diabetes.tab.txt',
                  delimiter='\t', dtype='str')
feature_names, diab = diab[0,:10], diab[1:].astype('float')

np.loadtxt with dtype='str' first, so the header row can be kept as names, then the body is cast to float in one slice. diab ends up (442, 11) — ten features plus the response.

What to explain: the delimiter='\t' matters because the file is tab-separated; the two-step load exists because a single loadtxt with dtype=float would crash on the header.

2. Read the dataset description

diab_sk = sklearn.datasets.load_diabetes()
print(diab_sk.DESCR)

The DESCR string is worth reading once: 442 patients, ten baseline variables (age, sex, bmi, bp, s1..s6), and one crucial line —

> Each of these 10 feature variables have been mean centered and scaled by the standard deviation times the square root of n_samples.

That sentence is the reason you do not scale again. The sklearn copy is already standardised; scaling twice changes nothing but it is worth knowing why.

3. Split features and target

features = diab[:, :10]
labels   = diab[:, 10]
features.shape, labels.shape      # ((442, 10), (442,))

4. Label distribution

plt.hist(labels, bins=50)
labels.max(), labels.min()        # (346.0, 25.0)

A right-skewed distribution of disease-progression scores from 25 to 346. For regression, this replaces the class-balance check — you are looking for skew, outliers and range, not class proportions.

5. Scatter one feature against the target

plt.scatter(features[:,2], labels, marker='*', c='b')   # features[:,2] is BMI
plt.xlabel(feature_names[2]); plt.ylabel('Diabetes Progression')

A clear positive trend with substantial vertical spread. That spread is the $R^2$ you are about to compute, seen before you compute it.

6. Deliberately use one feature

X = features[:, 2].reshape(-1, 1)   # (442, 1)

reshape(-1,1) is required: scikit-learn estimators expect a 2-D X even for one feature. Forgetting it raises Expected 2D array, got 1D array.

Why only one feature: it makes the fitted line drawable, and it establishes the baseline that adding features must beat.

7. Split with a seed

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=999)
# (331, 1), (111, 1), (331,), (111,)

Note random_state=999 — unlike the classification notebook. Reproducibility is a graded criterion in the assignments.

8. Fit and predict

from sklearn.linear_model import LinearRegression
LR_model = LinearRegression()
LR_model.fit(X_train, y_train)
y_pred = LR_model.predict(X_test)

LinearRegression has no hyperparameters — it solves the normal equations directly. That is a useful thing to say: there is nothing to tune, which is why it is the reference model.

9. Three diagnostic plots

plt.plot(y_test[:10], '*', label='actual')
plt.plot(y_pred[:10], 'o', label='prediction')

plt.bar(np.arange(111), np.abs(y_pred - y_test))     # per-sample error

plt.scatter(y_test, y_pred, c='g'); plt.plot(y_test, y_test, c='r')

The third is the important one: predicted vs actual with the identity line. Points on the line are perfect. Systematic curvature means the model is wrong (linear when it should not be); vertical spread means irreducible noise. Here the points scatter around the line with a lot of spread at both ends.

10. Read the parameters

print('Model coefficient: ', LR_model.coef_)      # [9.94204538]
print('Model intercept: ', LR_model.intercept_)   # -106.4754115887983

$$\hat y = 9.942\cdot\text{bmi} - 106.475$$

Interpretation: one unit of (standardised) BMI is associated with a 9.94-point increase in the progression score. The intercept is the prediction at BMI = 0 in standardised units, which is the mean BMI — not a clinically meaningful zero. Saying that is a good answer; confusing it with "a patient with BMI 0" is not.

11. The regression line on both splits

plt.subplot(121); plt.scatter(X_train, y_train, c='g')
plt.plot(X_train, X_train*LR_model.coef_ + LR_model.intercept_)
plt.subplot(122); plt.scatter(X_test, y_test, c='r')
plt.plot(X_test, X_test*LR_model.coef_ + LR_model.intercept_)

Same line, two point clouds. That is the visual definition of a parametric model: the fit is one global function, not a per-region rule. And the train and test panels looking similar is the evidence that it is not overfitting.

12. Metrics

print('MSE score: ', mean_squared_error(y_test, y_pred))    # 2976.43
print('R2 score: ', r2_score(y_test, y_pred))               # 0.4197
print('Max Error score: ', max_error(y_test, y_pred))       # 121.05
MetricValueReading
MSE2976.43average squared error, in squared progression units
RMSE$\sqrt{2976}=54.6$typical error of ~55 points on a 25–346 scale
$R^2$0.4197BMI explains 42% of the variance
Max error121.05worst single case is off by 121 points

The sentence to write: the model is clearly better than predicting the mean ($R^2=0.42 > 0$) but far from adequate — an RMSE of 55 on a target spanning 320 units is a coarse estimate, which is exactly the motivation for using all ten features, and then for regularisation.

What to notice about the code style

  • from google.colab import drive; drive.mount('/content/drive') appears here but is unused — the data is fetched over HTTPS. Leftover from the in-class version.
  • print('MSE score: ', ...) labels are reused verbatim across notebooks; that is the course's house style, not a mistake.
  • The R2 formula is spelled out in markdown as $1 - RSS/TSS$ with the code equivalent R2 = 1 - RSS/TSS right beside it. That is worth copying into an exam answer.