Exercise 2D Gaussian Mixture

Introduction

In this notebook you will implement an EM algorithm to find meanvectors and covariance matricies for bivariate gaussians to solve a 2D classfication problem.

Requirements

Knowledge

To complete this exercise notebook, you should possess knowledge about the following topics:

  • Mixture Models
  • EM Algorihtm

The following material can help you to acquire this knowledge:

  • Bishop [BIS06], Chapter 9.2

Python Modules

import numpy as np
from matplotlib import pyplot as plt
from colorutils import Color
%matplotlib inline
np.random.seed(42)

Exercise

Consider the following "Mickey Mouse" like data set.

#Mickey Mouse example
variance1 = [[0.05,0.0 ],[0.0,0.07]]
loc1 = [-1.0,2.0]
x1,y1 = np.random.multivariate_normal(loc1,variance1,size=300).T

variance2 = [[0.05,0.0 ],[0.0,0.07]]
loc2 = [1.0,2.0]
x2,y2 = np.random.multivariate_normal(loc2,variance2,size=300).T

variance3 = [[0.2,0.0 ],[0.0,0.4]]
loc3 = [0.0,0.0]
x3,y3 = np.random.multivariate_normal(loc3,variance3,size=800).T

xData = np.concatenate((x1,x2,x3))
yData = np.concatenate((y1,y2,y3))

xyData = np.ndarray((xData.shape[0], 2))
xyData[:,0] = xData
xyData[:,1] = yData

plt.plot(xyData[:,0],xyData[:,1],'ro',label='Data')
plt.legend()
plt.grid()
plt.show()

Task

Read Chapter 9.2 in Bishop's book and implement a Gaussian mixture for multivariate Gaussians using the EM algorithm. As you can see above you may assume three multivariate Gaussians, so you will need to set three initial means, three covariance matrices and an initial mixing as your start values.

def multi_gaussian(data,mean,var):
    
    expo = -1.0/2.0 * np.dot((data-mean).T,np.dot(np.linalg.inv(var),(data-mean)))  
    return 1.0/np.sqrt((2*np.pi)**np.size(data)*np.linalg.det(var))*np.exp(expo)

def EM_Mixture_Gaussian(initial_mean,initial_cov,initial_mix,Data):
    
    K = np.size(initial_mean,axis=0)  #Number of assumed Gaussians
    N = np.size(Data,axis=0)          #Number of data points
    
    mean = initial_mean
    cov = initial_cov
    mix = initial_mix
    
    gamma_z_nk = np.zeros((N,K))
    
    #E-Step
    
    # Implement your E-Step here
    
    #M-Step
    
    # Implement your M-Step here
        
    
    return mean,cov,mix, gamma_z_nk #updated versions

Solution

The following two functions will help to visualize your EM-Steps. "asssigne_class_euclidean" plots a "hard-cut" classification using the minimal euclidean distance to the means and "asssigne_class_color_responsibility" plots a color mixing according to the responsibilties each data point has.

def asssigne_class_euclidean(Data,meanlist):
    K = np.size(meanlist,axis=0)  #Number of assumed Gaussians
    N = np.size(Data,axis=0)      #Number of data points
    mean = np.asarray(meanlist)
    distance = np.zeros(K)
    
    plt.subplot(121)
    for n in np.arange(N):
        for k in np.arange(K):
            distance[k] = np.linalg.norm(Data[n]-mean[k])
        maxindex = np.argmin(distance)
        col = 'C'+str(maxindex)
        plt.plot(Data[n,0],Data[n,1],'o',color=col)
    
    plt.plot(mean[0,0],mean[0,1],'o',markersize=10,color='black',label='mean class 1:('+str(np.round(mean[0,0],3))+','+str(np.round(mean[0,1],3))+')')
    plt.plot(mean[1,0],mean[1,1],'s',markersize=10,color='black',label='mean class 2:('+str(np.round(mean[1,0],3))+','+str(np.round(mean[1,1],3))+')')
    plt.plot(mean[2,0],mean[2,1],'*',markersize=10,color='black',label='mean class 3:('+str(np.round(mean[2,0],3))+','+str(np.round(mean[2,1],3))+')')
    
    plt.legend(loc='upper center',bbox_to_anchor=(0.5, 1.25))
    plt.grid()
    return True

def asssigne_class_color_responsibility(Data,gamma_z_nk,meanlist):
    N = np.size(Data,axis=0)      #Number of data points
    mean = np.asarray(meanlist)
    
    plt.subplot(122)
    for n in np.arange(N):
        colob = Color((gamma_z_nk[n][0],gamma_z_nk[n][1],gamma_z_nk[n][2]))
        col = colob.rgb
        plt.plot(Data[n,0],Data[n,1],'o',color=col)
    
    plt.plot(mean[0,0],mean[0,1],'o',markersize=10,color='black')
    plt.plot(mean[1,0],mean[1,1],'s',markersize=10,color='black')
    plt.plot(mean[2,0],mean[2,1],'*',markersize=10,color='black')
    
    plt.grid()
    return True

Choose your initial values and number of EM-Steps you wanna do.

initial_mean = [[0.0,0.0],[0.0,0.0],[0.0,0.0]]
initial_mix = [0.0,0.0,0.0]
initial_covariance = [[0.0,0.0],[0.0,0.0]]
L = 0 #number of steps
mean = initial_mean
mix = initial_mix
cov = [initial_covariance,initial_covariance,initial_covariance]

Run the following cell to visualize your classification.

print('------------------- Classes with EM -----------------------')
for l in np.arange(L):
    mean,cov,mix,gamma_z_nk = EM_Mixture_Gaussian(mean,cov,mix,xyData)
    if l%4 == 0:
        print('-------- Step='+str(l)+'---------')
        
        plt.figure(figsize=(15,5))
        asssigne_class_euclidean(xyData,mean) 
        asssigne_class_color_responsibility(xyData,gamma_z_nk,mean)
        plt.show()

Literature

Licenses

Notebook License (CC-BY-SA 4.0)

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

exercise-2D-gaussian-mixture-em
by Oliver Fischer
is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at https://gitlab.com/deep.TEACHING.

Code License (MIT)

The following license only applies to code cells of the notebook.

Copyright 2019 Oliver Fischer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.