QUESTION 1
Imagine that you are studying the housing market. You have information about thousands of residential areas, and you want to answer a simple question: Do areas with higher household incomes tend to have more expensive homes? In this homework, you will investigate this question on a given dataset by implementing linear regression yourself.
1. Dataset, model and the error function
Use the California Housing dataset, containing 20,640 observations derived from the 1990 US census. Each observation describes a small residential area—not an individual house.
Download the dataset and save it as a separate file named housing.csv:
Select these two columns:
| Role | Column | Description |
|---|---|---|
| Input (x) | median_income |
Median household income, in the numerical units supplied in the file |
| Target (y) | median_house_value |
Median house value, in dollars |
Ignore the other columns. Your model is
\begin{eqnarray}
\hat y=ax+b,
\end{eqnarray}
where (a) and (b) are the parameters to be learned.
Minimize the squared-error objective
\begin{eqnarray}
J(a,b)=\frac{1}{2N}\sum_{i=1}^{N}(ax_i+b-y_i)^2,
\end{eqnarray}
where (N) is the number of observations
2. Implementation rules
Write your own Python implementations of all calculations and algorithms.
- NumPy may be used for arrays, arithmetic, reductions such as sums and means, and matrix operations.
- Libraries may be used for reading files, plotting, timing, matrix operations and random-number generation.
- Implement standardization, loss evaluation, analytical parameter calculation, gradients, and optimization loops yourself.
- No linear regression libraries are permitted. Do not use built-in regression models, least-squares solvers, optimizers, or automatic differentiation. This includes
numpy.polyfit,numpy.linalg.lstsq, and scikit-learn regression models. But you can use them to check your results. - Read the observations from
housing.csv. Do not embed the data in your source code.
You must be able to explain every part of your submitted code.
(a) Explore and visualize the observations
Load the two selected columns. Check for missing values and report the number of usable observations.
Calculate the minimum, maximum, mean, and standard deviation of each variable.
Create a scatter plot with income on the horizontal axis and house value on the vertical axis. Use small or partially transparent markers so that overlapping observations remain visible.
Briefly answer:
- Does income appear related to house value?
- Does a straight line appear capable of explaining all the variation?
- Do you notice any unusual patterns, such as horizontal bands or a ceiling in the recorded house values?
For this part, you will report the numbers asked above and the scatter plot.
(b) Find the analytical solution
Use the analytical formula derived in class to find the optimal parameters for both the raw dataset and the standardized dataset. Standardize only the input; leave the target unchanged.
For each case:
- Report the parameters $a$ and $b$. For the standardized solution, convert the parameters back to the original input units before reporting them.
- Report the minimum loss.
- Plot the fitted line over the original data scatter plot.
- Measure the execution time of the analytical calculation. Repeat the calculation at least 1,000 times and report the average time per calculation. Exclude file reading and standardization from this measurement.
For this part, report eight numbers—$a$, $b$, minimum loss, and average execution time for each case—and two plots.
(c) Compute and visualize the error surface
For each input version (standardized and nonstandardized):
- Construct a two-dimensional grid of parameter values ((a,b)).
- Use at least (100\times100) grid points.
- Evaluate the full-dataset loss at every grid point.
- Choose parameter ranges that clearly reveal the shape around the analytical minimum.
- Produce a figure containing the 3D error surface, Label the axes and mark the analytical optimum found above.
For this part, you will report two plots.
(d) Find the optimum point by stochastic gradient descent,
For both cases,
1. Find the local minimum by SGD, starting from 5 random initial points. Iterate till the solution converges. Mark the trajectory on the error surface for these 5 random initial points, using different colors.
2. Separately, measure the time required for SGD convergence. Do the SGD calculations at least 20 times for 20 random initial points and report its average convergence time and average error and the related standard deviations. Exclude file reading and standardization from this measurement.
For this part you will report two plots and eight numbers: mean convergence time, its standard deviation, mean error, and its standard deviation, for each input version.. You should choose your learning rate, stopping criterion, maximum number of updates, and distribution of random initial parameters
(e) Full linear regression
Do a linear regression on the full California Housing dataset (ie, use all features). Report the average error. Again, eliminate entries with missing observations.
Hint: The column ocean_proximity contains categories rather than numbers. Use one-hot encoding: create a binary input column for each category, indicating whether an observation belongs to that category.
When using one-hot encoding, retain all category columns but omit the bias (intercept). Including both creates linear dependence, because the category columns sum to the constant-one column represented by the bias.
QUESTION 2
Can measurements of cell size, shape, and texture help distinguish benign and malignant tumours? In this homework, you will fit a logistic regression model using all 30 numerical features of the Wisconsin Diagnostic Breast Cancer dataset.
Read the comma-separated file wdbc.data, containing 569 observations. Discard the first column, which is an ID. The second column contains the diagnosis: encode malignant (M) as $y=1$ and benign (B) as $y=0$. The remaining 30 columns are the input features.
Your model is
\begin{eqnarray}
\hat y_i &=& \frac{1}{1+e^{-(\mathbf w^T\mathbf x_i+b)}},
\end{eqnarray}
where $\mathbf w$ contains 30 weights and $b$ is the intercept. Minimize the binary cross-entropy over the training set:
\begin{eqnarray}
J(\mathbf w,b) &=& -\frac{1}{N_{\mathrm{train}}}\sum_{i=1}^{N_{\mathrm{train}}}
\left[y_i\log\hat y_i+(1-y_i)\log(1-\hat y_i)\right].
\end{eqnarray}
(a) Randomly divide the observations into an 80% training set and a 20% test set, using random seed 42. Keep approximately the same proportion of benign and malignant observations in both sets. Report the number of observations of each class in each set.
(b) Standardize each input feature separately using its training-set mean and standard deviation:
\begin{eqnarray}
z_{ij} &=& \frac{x_{ij}-\mu_j}{s_j}.
\end{eqnarray}
Apply these same training-set values $\mu_j$ and $s_j$ to standardize the test set. Use the standardized features as the model inputs. Do not standardize the labels. Briefly explain why the test set should not be used to calculate these statistics.
(c) Derive the gradients with respect to $\mathbf w$ and $b$, and write their gradient-descent update equations.
(d) Implement full gradient descent using only the training set. Initialize all weights and the intercept to zero, use learning rate $0.1$, and perform 10,000 updates. Plot the training loss against iteration number, and report the final weights, intercept, and training loss. Use a numerically stable implementation of the sigmoid and cross-entropy.
(e) Classify an observation as malignant when $\hat y_i\geq0.5$. Without changing the trained parameters, evaluate the model separately on the training and test sets. For each set, report:
- The percentage of correctly classified observations.
- The number of benign observations classified as malignant.
- The number of malignant observations classified as benign.
Briefly compare the training and test results.
Requirements: Implement data splitting, standardization, the model, loss, gradients, and optimization loop yourself in Python/NumPy. Libraries may be used for file reading, plotting, and random-number generation. No built-in regression models, optimizers, or automatic differentiation are permitted. Read the data from a separate file.
Submission: Submit your code, gradient derivation, training-loss plot, numerical results, and brief explanations.