def init(self, X, K, max_iters=100):
"""
Args:
X: the observations/datapoints, N x D numpy array
K: number of clusters/components
max_iters: maximum number of iterations (used in EM implementation)
"""
self.points = X
self.max_iters = max_iters
self.N = self.points.shape[0]
self.D = self.points.shape[1]
self.K = K
def softmax(self, logit):
"""
Args:
logit: N x D numpy array
Return:
prob: N x D numpy array. See the above function.
Hint:
Add keepdims=True in your np.sum() function to avoid broadcast error.
"""
logit_sub = logit - logit.max(axis=1, keepdims=True)
exp_logit = np.exp(logit_sub)
sum_exp_logit = np.sum(exp_logit, axis=1, keepdims=True)
return exp_logit / sum_exp_logit
def logsumexp(self, logit):
"""
Args:
logit: N x D numpy array
Return:
s: N x 1 array where s[i,0] = logsumexp(logit[i,:]). See the above function
Hint:
The keepdims parameter could be handy
"""
logit_max = np.max(logit, axis=1, keepdims=True)
return logit_max + np.log(
np.sum(np.exp(logit - logit_max), axis=1, keepdims=True)
)
def normalPDF(self, points, mu_i, sigma_i):
"""
Args:
points: N x D numpy array
mu_i: (D,) numpy array, the center for the ith gaussian.
sigma_i: DxD numpy array, the covariance matrix of the ith gaussian.
Return:
pdf: (N,) numpy array, the probability density value of N data for the ith gaussian
def multinormalPDF(self, points, mu_i, sigma_i):
"""
Args:
points: N x D numpy array
mu_i: (D,) numpy array, the center for the ith gaussian.
sigma_i: DxD numpy array, the covariance matrix of the ith gaussian.
Return:
normal_pdf: (N,) numpy array, the probability density value of N data for the ith gaussian
Hint:
np.linalg.det() and np.linalg.inv() should be handy.
Note the value in self.D may be outdated and not correspond to the current dataset.
You may wanna check if the matrix is singular before implementing calculation process.
"""
raise NotImplementedError
def create_mu(self):
"""
Intialize random centers for each gaussian
Args:
Return:
mu: KxD numpy array, the center for each gaussian.
"""
random_indices = np.random.choice(self.N, self.K, replace=False)
mu = self.points[random_indices, :]
return mu
def create_sigma(self):
"""
Initialize the covariance matrix with np.eye() for each k. For grads, you can also initialize the
by K diagonal matrices.
Args:
Return:
sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian.
You will have KxDxD numpy array for full covariance matrix case
"""
return np.repeat(np.eye(self.D)[np.newaxis, :, :], self.K, axis=0)
Assistant
User
aking sure GMM cluster image function respects the max_iteration given
Assistant
To ensure that the cluster_pixels_gmm function respects the maximum number of iterations specified during the Gaussian Mixture Model fitting, you need to set the parameter appropriately when initializing the instance. This parameter controls how many iterations the Expectation-Maximization (EM) algorithm will perform in the GMM implementation. Here's how you can adjust the function to respect the maximum iterations:
gmm_img = np.reshape(centers[cluster_ids], (im_height, im_width, im_ channel))
return gmm_img
use above code and format and use porperly
Assistant
def _init_components(self, **kwargs):
"""
Args:
kwargs: any other arguments you want
Return:
pi: numpy array of length K, prior
mu: KxD numpy array, the center for each gaussian.
sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian.
You will have KxDxD numpy array for full covariance matrix case
Hint: np.random.seed(5) must be used at the start of this function to ensure consistent outputs.
"""
np.random.seed(5)
pi = self.create_pi()
mu = self.create_mu()
sigma = self.create_sigma()
return pi, mu, sigma
def _ll_joint(self, pi, mu, sigma, full_matrix=FULL_MATRIX, **kwargs):
"""
Args:
pi: np array of length K, the prior of each component
mu: KxD numpy array, the center for each gaussian.
sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian. You will have KxDxD numpy
array for full covariance matrix case
full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.
Return:
ll(log-likelihood): NxK array, where ll(i, k) = log pi(k) + log NormalPDF(points_i | mu[k], sigma[k])
"""
N, D = self.points.shape
ll = np.zeros((N, self.K))
for k in range(self.K):
if not full_matrix:
pdf = self.normalPDF(self.points, mu[k], sigma[k])
ll[:, k] = np.log(pi[k] + LOG_CONST) + np.log(pdf + LOG_CONST)
return ll
def _E_step(self, pi, mu, sigma, full_matrix=FULL_MATRIX, **kwargs):
"""
Args:
pi: np array of length K, the prior of each component
mu: KxD numpy array, the center for each gaussian.
sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian.You will have KxDxD numpy
array for full covariance matrix case
full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.
Return:
tau: NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.
Hint:
You should be able to do this with just a few lines of code by using _ll_joint() and softmax() defined above.
"""
ll_joint = self._ll_joint(pi, mu, sigma, **kwargs)
tau = self.softmax(ll_joint)
return tau
def _M_step(self, tau, full_matrix=FULL_MATRIX, **kwargs):
"""
Args:
tau: NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.
full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.
Return:
pi: np array of length K, the prior of each component
mu: KxD numpy array, the center for each gaussian.
sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian. You will have KxDxD numpy
array for full covariance matrix case
Hint:
There are formulas in the slides and in the Jupyter Notebook.
Undergrads: To simplify your calculation in sigma, make sure to only take the diagonal terms in your covariance matrix
"""
N_k = np.sum(tau, axis=0)
pi = N_k / self.N
mu = np.dot(tau.T, self.points) / N_k[:, np.newaxis]
def call(
self, full_matrix=FULL_MATRIX, abs_tol=1e-16, rel_tol=1e-16, **kwargs
): # No need to change
"""
Args:
abs_tol: convergence criteria w.r.t absolute change of loss
rel_tol: convergence criteria w.r.t relative change of loss
kwargs: any additional arguments you want
Return:
tau: NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.
(pi, mu, sigma): (1xK np array, KxD numpy array, KxDxD numpy array)
Hint:
You do not need to change it. For each iteration, we process E and M steps, then update the paramters.
"""
pi, mu, sigma = self._init_components(**kwargs)
pbar = tqdm(range(self.max_iters))
prev_loss = None
for it in pbar:
tau = self._E_step(pi, mu, sigma, full_matrix)
pi, mu, sigma = self._M_step(tau, full_matrix)
joint_ll = self._ll_joint(pi, mu, sigma, full_matrix)
loss = -np.sum(self.logsumexp(joint_ll))
if it:
diff = np.abs(prev_loss - loss)
if diff < abs_tol and diff / prev_loss < rel_tol:
break
prev_loss = loss
pbar.set_description("iter %d, loss: %.4f" % (it, loss))
return tau, (pi, mu, sigma)
def cluster_pixels_gmm(image, K, max_iters=10, full_matrix=True):
"""
Clusters pixels in the input image
Each pixel can be considered as a separate data point (of length 3),
which you can then cluster using GMM. Then, process the outputs into
the shape of the original image, where each pixel is its most likely value.
Args:
image: input image of shape(H, W, 3)
K: number of components
max_iters: maximum number of iterations in GMM. Default is 10
full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.
Return:
clustered_img: image of shape(H, W, 3) after pixel clustering
Hints:
What do mu and tau represent?
"""
raise NotImplementedError
write code for cluster_pixels_gmm
3.3 Image Compression and pixel clustering [10pts]
Images typically need a lot of bandwidth to be transmitted over the network. In order to optimize this process, most image processors perform lossy compression of images (lossy implies some information is lost in the process of compression).
In this section, you will use your GMM algorithm implementation to do pixel clustering and compress the images. That is to say, you would develop a lossy image compression algorithm. This question is autograded based on your GMM implementation.
(Hint: you can adjust the number of clusters formed and justify your answer based on visual inspection of the resulting images or on a different metric of your choosing)
Implement the cluster_pixels_gmm function in gmm.py. Each pixel can be considered as a separate data point (of length 3), which you can then cluster using GMM. Then, process the outputs into the shape of the original image, where each pixel is its most likely value. What do μ and τ represent?
Special Notes
Try to add a small value(e.g. SIGMA_CONST and LOG_CONST) before taking the operation if the output image is solid black.
The output images may be slightly different due to different initialization methods in GMM() function.
Sample with replacement in create_mu
image = image.astype(np.float32)
Made sure my mu was sampled with replacement. Made sure it was a single call to random.choice
Added to GMM for float 64
To implement the cluster_pixels_gmm function in the provided Gaussian Mixture Model (GMM) class, the goal is to utilize the GMM to perform clustering on the pixels of an image, effectively compressing it by representing each pixel with a cluster center (or mean of the Gaussian component it belongs to). Here's how you can go about implementing it:
def cluster_pixels_gmm(image, K, max_iters=10, full_matrix=True):
"""
Clusters pixels in the input image
Args:
image: input image of shape (H, W, 3)
K: number of components
max_iters: maximum number of iterations in GMM. Default is 10
full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.
Return:
clustered_img: image of shape (H, W, 3) after pixel clustering
"""
# Convert image to a 2D array where each row is a pixel
H, W, C = image.shape
pixels = image.reshape(-1, C).astype(np.float32)
# Initialize and fit GMM
gmm = GMM(pixels, K, max_iters)
tau, (pi, mu, sigma) = gmm(full_matrix=full_matrix)
# For each pixel, choose the cluster with the highest probability as its cluster
pixel_clusters = np.argmax(tau, axis=1)
# Create the compressed image by replacing each pixel with its cluster's mean
clustered_pixels = mu[pixel_clusters]
# Reshape the compressed image back to (H, W, 3) shape
clustered_img = clustered_pixels.reshape(H, W, C).astype(np.uint8)
return clustered_img
Explanation:
Image Reshaping:
Reshape the image from (H, W, 3) to (H*W, 3), providing a format where each pixel is treated as a data point in a 3-dimensional space (representing its RGB values).
GMM Initialization and Execution:
Instantiate the GMM class using the reshaped pixel data.
Execute the GMM by calling it, which returns the posterior distribution (tau) and the parameters for each Gaussian component: prior probabilities (pi), means (mu), and covariances (sigma).
Cluster Assignment:
Use np.argmax on the tau array to determine the most likely cluster for each pixel, which corresponds to the Gaussian component with the highest posterior probability.
Image Reconstruction:
Replace each pixel with the mean value of its assigned cluster.
Reshape the clustered data back into the original image dimensions (H, W, 3).
Return:
Return the newly constructed image, which is a compressed form of the original image with each pixel replaced by the representative color of its corresponding cluster.
This method provides a form of lossy compression where the image quality might degrade depending on number of clusters (K), but results in reduced data size due to reduced color variance.
max_iters
GMM
def cluster_pixels_gmm(image, K, max_iters=10, full_matrix=True):
"""
Clusters pixels in the input image using Gaussian Mixture Model (GMM).
Args:
image: Input image of shape (H, W, 3).
K: Number of clusters/components.
max_iters: Maximum number of iterations in GMM. Default is 10.
full_matrix: Whether to use full covariance matrix in Normal PDF. Default is True.
Return:
clustered_img: Image of shape (H, W, 3) after pixel clustering.
"""
# Extract the dimensions of the image
H, W, C = image.shape
# Reshape the image to a 2D array where each row represents a pixel and its color (RGB values)
pixels = image.reshape(-1, C).astype(np.float32)
# Initialize the GMM with the specified number of clusters and iterations
gmm = GMM(pixels, K, max_iters=max_iters)
# Perform the GMM clustering process
tau, (pi, mu, sigma) = gmm(full_matrix=full_matrix)
# Determine the cluster for each pixel by finding the class with the highest probability in tau
pixel_clusters = np.argmax(tau, axis=1)
# Reconstruct the compressed image by replacing each pixel with the mean of its cluster
clustered_pixels = mu[pixel_clusters]
# Reshape the clustered pixels back to the original image dimensions
clustered_img = clustered_pixels.reshape(H, W, C).astype(np.uint8)
return clustered_img
Key Changes:
When calling the GMM class during its instantiation GMM(pixels, K, max_iters=max_iters), the max_iters parameter is set using the value provided to cluster_pixels_gmm. Therefore, the number of iterations the EM algorithm will run is governed by this parameter.
By setting max_iters in the GMM instance, you ensure that the clustering procedure adheres to the iteration constraints specified by the user when calling cluster_pixels_gmm. This provides control over the computational cost and convergence time of the image clustering process using the Gaussian Mixture Model.
Certainly! Here's how you can structure the cluster_pixels_gmm function using the code snippet you provided. This version is formatted properly to perform image clustering using a Gaussian Mixture Model, respecting the specified maximum number of iterations.
def cluster_pixels_gmm(image, K, max_iters=10, full_matrix=True):
"""
Clusters pixels in the input image using Gaussian Mixture Model (GMM).
Args:
image: Input image of shape (H, W, 3).
K: Number of clusters/components.
max_iters: Maximum number of iterations in GMM. Default is 10.
full_matrix: Whether to use full covariance matrix in Normal PDF. Default is True.
Return:
gmm_img: Image of shape (H, W, 3) after pixel clustering.
"""
# Get image dimensions
im_height, im_width, im_channel = image.shape
# Flatten the image to a 2D array where each row is a pixel
flat_img = np.reshape(image, [-1, im_channel]).astype(np.float32)
# Initialize and fit the GMM
gmm = GMM(flat_img, K=K, max_iters=max_iters)
gamma, (pi, mu, sigma) = gmm(full_matrix=full_matrix)
# Get the cluster IDs for each pixel
cluster_ids = np.argmax(gamma, axis=1)
# Replace each pixel with the corresponding cluster center
centers = mu
gmm_img = np.reshape(centers[cluster_ids], (im_height, im_width, im_channel))
return gmm_img
Explanation:
Image Reshaping:
The image is reshaped from (H, W, 3) to (H*W, 3), enabling each pixel and its RGB components to be treated as a single data point in a 3-dimensional space.
GMM Initialization and Execution:
An instance of the GMM class is created with the given number of clusters (K) and the specified maximum number of iterations (max_iters).
The GMM instance is called with the option for a full covariance matrix, returning gamma (the posterior distribution), and other GMM parameters (pi, mu, sigma).
Cluster Assignment:
The argmax function is used on gamma to find the cluster with the highest probability for each pixel.
Image Reconstruction:
Each pixel is replaced by the mean of its assigned cluster.
The reshaped array of clustered data is then formed back to the original image dimensions (H, W, 3).
Return:
The function returns gmm_img, the image after pixel clustering, which should effectively show reduced color variance typical of image compression through clustering.
This implementation should effectively handle image compression while respecting the iteration limits set for the GMM fitting process.