Homework 03
- Overall Info
- Due date: 2027-05-24
- Submit a
*.pyfile with comments for the code - In groups of 5-6 students
1. Linear Regression Fake Data
To illustrate the principle of linear regression we consider the following model
where
We assume that
with \(\varepsilon\) independent of \((X_1, X_2)\).
Consider the following specifications
import numpy as np
b = np.array([1, 1, -0.5]).T
mu = np.array([1, 0]).T
sigma1 = 1
sigma2 = 0.5
rho = 0.4
Sigma = np.array(
[
[sigma1 ** 2, sigma1 * sigma2 * rho],
[sigma1 * sigma2 * rho, sigma2 ** 2]
]
)
sigma = 2
# We prepare the dataset
# Fix random number generator and number of samples
rng = np.random.default_rng(seed = 150)
N = 1000
# generate samples
X = rng.multivariate_normal(mu, Sigma, size = N) # size N x 2
epsilon = rng.normal(0, sigma, size = N) # size N
# Add an axis of 1 to X
X = np.append(np.ones((N, 1)), X, axis = 1) # append Nx1 to Nx2 -> Nx3
# Generate Y
Y = X.dot(b) + epsilon # size N
Y
Question 1.
- Generate a scatter plot of \(Y\) against \(X_1\) and \(X_2\), as well as a scatter plot of \(X_1\) against \(X_2\).
- Implement the computation of \(\hat{\mathbf{b}}(N)\) from the \(N\) sample data and compare the obtained values with the true ones.
- Return the residual error \(\hat{\varepsilon}(N) = \mathbf{y} - \mathbf{x}\hat{\mathbf{b}}(N)\) and plot its histogram.
Question 2.
Since we fixed the random generator with seed=150 you always get the same result for \(\hat{\mathbf{b}}(N)\) as well as \(\hat{\varepsilon}(N)\).
Two sources of error can come into the linear regression: The randomness in the sample (the seed) as well as the number of samples N.
-
Define a function
f(N, M)whereNis the number of samples, and \(M\) is the number of trials where you draw this sample. This function shall return -
an array \(\hat{\mathbf{b}}(N)\) of size
3xMfor each computation of the regression coefficient (in the random generator you setseed = None) -
an array \(\hat{\varepsilon}(N)\) of size
NxMof the corresponding residual for each sample drawn. -
Fix
M=100and forN = 10, 100and1000plot the histogram of -
a(N),b_1(N)andb_2(N)(they are arrays ofM=100values) - mean and standard deviation in the direction of the
Naxis of \(\hat{\varepsilon}(N)\) (you get two arrays ofM=100values)
2. Linear Regression Real Data
As seen in the lecture, we are given a set of data in a dataframe df with
- a column
yfor the serie of outputs; dcolumnsx_0, ...,x_{d-1}for the series of inputs
In the following example we consider a dataset about wine
Question 1.
Proceed through the following:
- Load the dataset with pandas, check if the data are correct and provide some descriptive statistics.
The output \(\mathbf{y}\) is quality; the column type indicates whether the wine is red or white; all the other columns are characteristics of the wine.
-
Using plotly scatter plots, visualize the relation between each input dimension and the output dimension, for
redandwhite. -
Implement using
statsmodelsthe OLS regression ofqualityagainst the inputs and show the results.
Question 2.
The number of features is quite large and it is not clear which feature is relevant or not in the linear regression. The goal is to reduce the number of features so as to explain the output as much as possible.
Without going into feature selection, we just want to see which input is the most relevant. One indicator for the goodness of a linear regression is rsquared which can be obtained from the returned fitted model est = sm.OLS(y, X).fit() and then est.rsquared.
We just try to get the two best features
- Loop through every single input feature, perform the linear regression, get the rsquared.
- take the feature with the largest rsquared.
- Loop through each other feature, perform the linear regression together with the previously selected and first feature
- select the feature with the largest rsquared.
Note
Normally you should also consider whether the newly collected feature is not strongly collinear with the first one. To do so you should double check the VIF, see variance_inflation_factor.
3. Clustering
The principle of clustering is as follows. Given a set \(X = \{x_1, \ldots, x_N\}\) of \(N\) points in \(\mathbb{R}^d\), the goal is to find a partition (cluster) \(C_1, \ldots C_K \subseteq X\) which somehow group similar points.
Similarity between points is defined in terms of some distance \(d(x,y)\). The clustering aims to find an optimal cluster \(C_1^\ast, \ldots, C_K^\ast\) such that
for any other cluster \(C_1, \ldots, C_K\).
We denote by \(\mathfrak{C}\) the set of all clusters (or partitions) \(\mathcal{C} = \{C_1, \ldots, C_K\}\) of \(X\) in \(K\) elements and define
the problem can therefore be reformulated into an optimization problem
Computing \(F\) for a given cluster \(\mathcal{C}\) is relatively fast as long as the distance is quick to compute. However, the optimization problem itself is very difficult. Indeed, it is a minimization problem on a set \(\mathfrak{C}\) which does not have a suitable topology to define derivatives for instance. Hence, the only way a priori would be a brute force optimization, that is running through every possible partition, which is however not suitable since the cardinality of \(\mathfrak{C}\) is gigantic. It corresponds to the Stirling numbers of the second kind \({ N \brace K}\):
meaning that for a fixed number \(K\), the cardinality is growing exponentially in the size of the set. The problem can be refined and some better approximation can be found but in general this is NP-Hard.
However, with some assumptions about the distance, and geometrical consideration, an honest and fast algorithm can be designed to achieve some local optimum.
We consider as distance the square of the Euclidean norm, that is \(d(x,y) = \|x - y\|^2\).
Question 1.
Show that
where \(\mu = \frac{1}{\# C} \sum_{x \in C} x\) is the average/barycenter or centroid of \(C\).
Question 2.
Using Question 1 it follows that
With this reformulation in terms of the geometric center of \(C\), we get the following idea for an algorithm to select a partition.
- Initialize \(K\) centers \(\mu_1(0), \ldots, \mu_K(0)\) by choosing \(K\)-points in \(X\).
Recursively: While \(\mathcal{C}(n+1) \neq \mathcal{C}(n)\) at the end of the following do:
Given \(K\) \(\mu_1(n), \ldots \mu_K(n)\) define \(K\) sets \(C_1(n+1), \ldots, C_K(n+1)\):
\(C_k(n+1) = \left\{x \in X\colon \|x - \mu_k(n)\|^2 \leq \|x - \mu_j(n)\|^2 \text{ for any }j\neq k\right\}\)
If some point is assigned to two or more clusters, set it to a single one. The best way to do it is to assign the points to the first cluster, then assign the remaining points to the second one, etc.
update the new centers \(\mu_1(n+1), \ldots, \mu_K(n+1)\):
\(\mu_k(n+1) = \frac{1}{\# C_k(n+1)} \sum_{x \in C_k(n+1)} x\)
- Show that at each step \(F(\mathcal{C}(n+1))\leq F(\mathcal{C}(n))\), hence we find a sequence along which the cost function is decreasing.
- Show that the algorithm finishes after a finite number of steps.
- Implement the algorithm in numpy by choosing \(K\) elements of the set \(X\) randomly. (The set \(X\) can be represented by a numpy array
Nxd.)
Question 3.
Consider the dataset California Housing which represents housing data for California.
- Load the dataset and select the columns
longitude,latitudeandmedian_incomeas the final dataframedf. - Install (using conda or pip) the package
scikit-learnwhich is a standard machine learning library. - Cluster the data into 4 clusters using k-means:
from sklearn.cluster import KMeans. - given a numpy array
Xof sizeN x d, computing the clusters withKMeansis done as followsresult = KMeans(n_clusters = 4).fit(X)and the labels for the cluster are given byresult.labels_which is an array of sizeN. - join the cluster values in the dataframe as a new column.
- plot using plotly express scatter the scatter plot latitude against longitude with a different color for each cluster.