SYDE 572 · Introduction to Pattern Recognition

Assignment 2

Linear basis function regression

Larissa Rudenko

Setup

The data is the Boston Housing set: 506 towns, 13 input features, and the median house value (in $1000s) as the target. I used the housing.data and housing.names files that came with the assignment. The first 100 rows are the training set and the other 406 rows are the test set. Every error on this page is an RMS error in $1000s.

Normalization. Each input feature is z-scored with the mean and standard deviation of the 100 training rows only. The test rows are scaled with those same numbers, so nothing from the test set goes into the fit. The target is not normalized.

Fitting. The unregularized fits use numpy's lstsq (a least squares solver based on the SVD). For the regularized fits (parts d and f) I minimize the squared error plus lambda times the sum of the squared weights, which has the closed form

\[ w = (\Phi^T \Phi + \lambda I')^{-1} \Phi^T t \]

where I' is the identity matrix with a 0 in the bias position, so the bias weight is not penalized. For lambda = 0 I use lstsq again.

Cross-validation. 10 folds, made by randomly splitting the 100 training rows (numpy seed 572, picked before I looked at any results). Inside each fold, the normalization is recomputed from that fold's training part only. In part (f) the Gaussian width and centers are also taken from that fold's training part only.

CHAS is always 0 in the training rows. In the first 100 rows the Charles River variable (CHAS) is 0 every time, so its standard deviation is 0 and there is nothing to learn from it. Its weight comes out as exactly 0 in the polynomial fits. It equals 1 in 35 of the test rows.
The training rows have almost no high-crime towns. In the training rows the crime rate (CRIM) has a standard deviation of 0.387 and a maximum of 1.61, but the test set goes up to 88.98. After normalizing, a test row can be 229.1 standard deviations from the training mean. This is what drives the very large test errors in part (a).
About the B column. The assignment says UCI took this dataset down over concerns about racial bias, and column B is computed from the proportion of Black residents in each town. The assignment tells us to use all the features, so I kept all 13, including B.

Part 1 - Polynomial Basis Functions

(a) Training and test error vs polynomial degree

For degree d, the feature matrix has a bias column plus the powers 1 to d of each of the 13 normalized features (no cross-terms), so there are 13d + 1 weights. I fit the weights on the first 100 rows, then computed the RMS error on those same 100 rows (training) and on the other 406 rows (test).

DegreeWeightsRank of feature matrixTraining RMSTest RMS
114132.03723.64 × 101
227251.57811.10 × 103
340371.44914.87 × 104
453481.27052.19 × 107
566541.09661.84 × 1010
679601.07255.02 × 1012
792660.88156.88 × 1015
training and test RMS error vs polynomial degree
Fig 1. Training and test RMS error vs polynomial degree. The y-axis is log scale because the test error spans many orders of magnitude. The last digits of the three largest test errors change a little from one machine to another, because those fits are numerically unstable.
Where the huge test errors come from. In the degree 1 fit, the median absolute test residual is 4.85, but the three worst test rows (lines 381, 419 and 406 of housing.data) have residuals (prediction minus true value) of -294.1, -250.7 and -227.0. Their crime rates are 88.98, 73.53 and 67.92, far above anything in the training rows (max 1.61). Raising such a value to the 7th power makes it much worse.
About the rank column. For degrees 1 to 3 the rank is lower than the number of weights by exactly the number of all-zero CHAS columns (one per degree). From degree 4 on, numpy reports an even lower rank, so some columns are nearly combinations of others.

Comment. As the polynomial degree increases, the training error decreases (from 2.04 at degree 1 to 0.88 at degree 7) because the model becomes more flexible and can fit the training data more closely. By degree 7 there are 92 weights for only 100 training rows. The test error goes the other way and increases dramatically at every degree, so the model does not generalize well to unseen data. Part of this is overfitting, but not all of it: the test error is already about 36 at degree 1, where the training error is only 2.04. A big part of the error comes from a few test rows with extreme feature values, such as the very high crime rates, which land far outside the training range after normalizing. Raising those values to higher powers makes the predictions much larger, so the error blows up as the degree goes up. Therefore, the model with the lowest training error (degree 7) is not the best model for new data. Here degree 1 has the lowest test error.

(b) Weights of the degree 1 fit

Degree 1 fit on the first 100 rows (training RMS 2.0372, test RMS 36.4449). The first weight column is for the z-scored features, which is what the model is actually fit on. The second column converts each weight back to the original units of the feature (the weight divided by that feature's training std, with the bias adjusted to match). The script checks that the raw-unit model gives the same training predictions as the z-scored one, and it does.

Feature #NameWeight (z-scored)Weight per raw unit
biasw022.3090-37.9042
1CRIM-1.3380-3.4559
2ZN0.12300.0054
3INDUS-0.5311-0.1688
4CHAS0.00000.0000
5NOX1.002721.5154
6RM4.19568.5910
7AGE-2.1663-0.0792
8DIS0.01070.0076
9RAD-0.1938-0.1399
10TAX-0.3486-0.0076
11PTRATIO0.26130.1546
12B0.18110.0066
13LSTAT0.14880.0262
Numbering. The assignment calls the weight on the 6th feature w5, so it numbers the features from 0 and keeps the bias separate. In this table the features are numbered from 1 and the bias has its own row, so RM is feature 6 and DIS is feature 8. The CHAS weight is 0 because its column is all zeros in the training rows.

Comment on RM (6th feature). The weight for RM is about +8.59 in the original feature units. Since the target is in $1000s, one extra room is associated with an increase of about $8,590 in predicted median house value, with the other features held constant. It is also the largest weight on the z-scored features (4.20), so RM matters most in this fit. A positive weight seems reasonable because houses with more rooms are generally larger and more valuable. However, the model was trained on only 100 rows, so this estimate may not represent the relationship across the whole dataset.

Comment on DIS (8th feature). The weight for DIS is about +0.0076 in the original units, which works out to under $8 per unit of distance since the target is in $1000s. On the z-scored features it is 0.0107, compared with 4.20 for RM, so it is tiny next to RM (comparing the raw weights directly would not be fair, because the features have different units). This suggests that distance to employment centres has very little influence on the prediction when the other features are held constant. The positive sign is somewhat unexpected, since being closer to employment centres might be expected to increase property values, but with a weight this close to 0 the sign probably does not mean much. The features may also be related to one another (in the training rows DIS has a correlation of 0.60 with ZN and -0.48 with NOX), which makes it hard to isolate the effect of distance, especially when the model is trained on only 100 rows.

(c) One feature only (ZN)

To be able to plot the result, I use only the 2nd feature, ZN (the proportion of residential land zoned for large lots), and fit polynomials of degree 1 to 7 to it. ZN is z-scored with the training mean and std before taking powers, and the curves are drawn on the original ZN axis. Every degree was fit; I show degrees 1, 3 and 7 below.

DegreeTraining RMSTest RMS
15.69519.3523
25.66969.4456
35.66499.4341
45.65069.3897
55.64759.3847
65.64739.3575
75.500610.4233
Why the points sit in vertical lines. ZN takes only 12 different values in the training rows, and 63 of the 100 training rows have ZN = 0 (309 of the 406 test rows do too).
degree 1 polynomial fit to ZN
Fig 2. Degree 1 polynomial, ZN only.

Comment on the degree 1 plot. The degree 1 fit is a nearly flat line that rises only slightly with ZN, which suggests that ZN alone does not have a strong linear relationship with median house value. The training RMS is 5.6951 and the test RMS is higher at 9.3523, so the fit does worse on unseen data than on the data it was trained on. Using only ZN is also much less accurate on the training data than the degree 1 fit with all 13 features (5.6951 vs 2.0372 in part a), so one feature is not enough to predict house values well. Its test error is lower than the 36.4449 from part (a), but that is probably only because ZN does not have extreme values like the crime rate does, which is what breaks the 13-feature fit.

degree 3 polynomial fit to ZN
Fig 3. Degree 3 polynomial, ZN only.

Comment on the degree 3 plot. Increasing the degree to 3 slightly reduces the training error from 5.6951 to 5.6649, but the test error goes up slightly from 9.3523 to 9.4341. The fitted curve is still fairly similar to the degree 1 result, so the extra polynomial terms do not seem to improve the model much. This suggests that a more complex polynomial is not particularly useful for this feature.

degree 7 polynomial fit to ZN
Fig 4. Degree 7 polynomial, ZN only.

Comment on the degree 7 plot. The degree 7 polynomial has the lowest training RMS of the seven degrees (5.5006) but also the highest test RMS (10.4233). The fitted curve swings up and down between the data clusters, which suggests it is fitting variations in the training data instead of a general relationship. This looks like overfitting, since the small improvement in training error comes with worse predictions on the test data.

(d) Regularization with 10-fold cross-validation (ZN, degree 8)

Here I use the first 100 rows, only the ZN feature, and a degree 8 polynomial with L2 regularization. For each λ in {0, 0.01, 0.1, 1, 10, 100, 1000} I ran 10-fold cross-validation and averaged the validation RMS over the 10 folds.

λAverage validation RMSStd over folds
08.46639.3906
0.016.32304.0941
0.19.204412.2161
19.681713.1129
109.771413.0908
1008.827010.3164
10006.48363.9586
average validation RMS vs lambda, degree 8, ZN only
Fig 5. Average 10-fold validation RMS vs λ (log axis). The dashed line is λ = 0, which can't be shown on a log axis.

The lowest average validation error is at λ = 0.01 (6.3230), so that is the value I would choose from this cross-validation.

The choice is not very stable. The standard deviation over the folds is large (up to 13), and the curve goes up and down. I repeated the whole cross-validation with other random splits of the 100 rows (seed 572 above was picked before I saw any results). Depending on the split, either 0.01 or 1000 wins, and their errors are close:
SeedBest λAvg val RMS at 0.01Avg val RMS at 1000
010007.826.88
10.016.776.89
20.016.096.78
3100026.516.08
40.016.776.98
5720.016.326.48

Comment on (d). Based on the 10-fold cross-validation, λ = 0.01 gives the lowest average validation RMS (6.3230), so I would select this value. However, the standard deviation across folds is fairly high (4.0941), so the error depends a lot on which rows end up in the validation fold. Different random splits also picked different values (0.01 or 1000, and λ = 1000 is almost as good here at 6.4836), so I would not consider this choice very reliable without more testing.


Part 2 - Gaussian Basis Functions

(e) Training and test error vs number of basis functions

Gaussian basis functions with K = 5, 15, ..., 95 centers, using all 13 normalized features. The centers are the first K points of one random permutation of the 100 training points (numpy seed 572), so the centers for a smaller K are also in the larger ones. The assignment doesn't give a width, so I used one width for all the basis functions: sigma = 4.6247, the median distance between pairs of training points. I used this rule instead of searching for the sigma with the lowest test error. There is a bias term and no regularization.

KTraining RMSTest RMS
52.71347.7587
152.19558.3585
251.62647.3325
351.35538.3304
451.23208.2442
551.18449.1713
651.05588.3185
750.664223.0202
850.462724.4488
950.375987.0259
training and test RMS vs number of Gaussian basis functions
Fig 6. Training and test RMS vs number of Gaussian basis functions (log y-axis).
This is one random permutation. The plot uses seed 572. With other permutations the test error also gets much larger for large K, but the exact values change a lot (test RMS):
SeedK=5152535455565758595
5727.768.367.338.338.249.178.3223.0224.4587.03
07.828.067.808.6613.0713.3819.0322.1344.1636.54
19.637.898.317.3912.318.2112.2827.3586.79239.62
214.1011.207.917.6816.9714.068.7749.92187.1257.88
39.308.659.8611.067.438.3720.5516.2412.0832.20
411.497.587.9212.1710.5513.1521.0455.4042.6848.81
The fit gets fragile as K grows. For the seed 572 fits, the condition number of the feature matrix and the largest weight both grow with K:
KWeightsCondition numberLargest |weight|
56214101.8
1516953110.3
25266.09e+03217.7
35361.27e+041126.8
45464.64e+041150.2
55568.42e+041518.6
65662.06e+053591.5
75764.51e+057819.8
85861.34e+0628338.5
95961.86e+0632499.8

Comment on (e). As the number of Gaussian basis functions goes from 5 to 95, the training RMS decreases from 2.7134 to 0.3759. The test error stays between about 7 and 9 up to K = 65, then jumps to 23.02, 24.45 and 87.03 at K = 75, 85 and 95. This suggests that more basis functions let the model fit the training data more closely, but past a point it overfits and generalizes poorly. At K = 95 there are 96 weights for only 100 training rows, and the largest weight grows from 101.8 at K = 5 to 32499.8, so the fit becomes very sensitive to the training data. This is also only one random choice of centers, and other permutations gave different test errors at large K.

(f) Regularization with 10-fold cross-validation (90 basis functions)

Here I use the first 100 rows and all 13 features, with 90 Gaussian basis functions and L2 regularization. For each λ in {0, 0.01, 0.1, 1, 10, 100, 1000} I ran 10-fold cross-validation (same folds as in part d). In each fold the training part has 90 rows, so the 90 centers are all of those rows. The width sigma is the median distance between pairs of the fold's training points, the same rule as in part (e).

λAverage validation RMSStd over folds
08.47787.2804
0.011.76750.9194
0.12.02240.9360
12.58580.7892
103.23010.8677
1004.34011.5848
10005.38621.8636
average validation RMS vs lambda, 90 Gaussian basis functions
Fig 7. Average 10-fold validation RMS vs λ (log axis). The dashed line is λ = 0.

The lowest average validation error is at λ = 0.01 (1.7675), so that is the value I would choose from this cross-validation. Unlike in part (d), this choice was the same for all six random splits I tried (seeds 0, 1, 2, 3, 4 and 572).

Things to keep in mind.

Comment on (f). The unregularized model (λ = 0) has a high validation RMS of 8.4778, and adding a small amount of regularization at λ = 0.01 brings it down to 1.7675. With λ = 0 there are more weights (91) than training rows in each fold (90), which is probably why it does so badly. As λ increases further the validation error rises steadily, reaching 5.3862 at λ = 1000, which suggests that too much regularization stops the model from fitting the data. I would choose λ = 0.01 because it has the lowest validation error of the values tested, and it was also the best value for all six random splits I tried. Since 0.01 is the smallest nonzero value in the grid, testing smaller values could show whether an even better one exists.


Code

All scripts are in this folder and need numpy and matplotlib. Put housing.data next to them and run any script with python3 from this folder. The plots are saved in media/. The assignment writes the function names with hyphens or spaces, but Python needs underscores.

FileWhat it does
common.pyloads the data, z-scoring, polynomial feature matrix, least squares, RMS
ridge.pyridge (L2) fit and the random 10-fold split
gauss.pyGaussian feature matrix and the median-distance width
a_polynomial_regression.pypolynomial_regression, part (a): table and Fig 1
a_check_outliers.pythe CHAS, CRIM and worst-residual numbers used in part (a) and the setup notes
b_weights.pypart (b): the weights table
b_check_dis.pyhow DIS is correlated with the other features
c_polynomial_regression_1d_vis.pypolynomial_regression_1d_vis, part (c): the ZN plots
c_check_zn.pythe ZN counts used in part (c)
d_polynomial_regression_reg.pypolynomial_regression_reg, part (d): cross-validation and Fig 5
d_check_seeds.pyrepeats (d) with other random splits
e_gaussian_regression.pygaussian_regression, part (e): table and plot
e_plot_ticks.pythe version of the part (e) plot used as Fig 6 (clearer y-axis labels)
e_check_seeds.pyrepeats (e) with other random permutations
e_check_conditioning.pycondition numbers and weight sizes for (e)
f_gaussian_regression_reg.pygaussian_regression_reg, part (f): cross-validation and Fig 7
f_check_seeds.pyrepeats (f) with other random splits

Larissa Rudenko - Fall 2026