comparison python/ml.py @ 787:0a428b449b80 dev

improved script to display over world image
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Thu, 17 Mar 2016 16:01:19 -0400
parents 1f2b2d1f4fbf
children 5b970a5bc233
comparison
equal deleted inserted replaced
786:1f2b2d1f4fbf 787:0a428b449b80
193 clusterSizes = {i: sum(np.array(labels) == i) for i in prototypeIndices} 193 clusterSizes = {i: sum(np.array(labels) == i) for i in prototypeIndices}
194 clusterSizes['outlier'] = sum(np.array(labels) == outlierIndex) 194 clusterSizes['outlier'] = sum(np.array(labels) == outlierIndex)
195 return clusterSizes 195 return clusterSizes
196 196
197 # Gaussian Mixture Models 197 # Gaussian Mixture Models
198 def plotGMMClusters(model, dataset = None, colors = utils.colors): 198 def plotGMMClusters(model, dataset = None, fig = None, colors = utils.colors, nPixelsPerUnit = 1., alpha = 0.3):
199 '''plot the ellipse corresponding to the Gaussians 199 '''plot the ellipse corresponding to the Gaussians
200 and the predicted classes of the instances in the dataset''' 200 and the predicted classes of the instances in the dataset'''
201 fig = plt.figure() 201 if fig is None:
202 fig = plt.figure()
202 labels = model.predict(dataset) 203 labels = model.predict(dataset)
204 tmpDataset = nPixelsPerUnit*dataset
203 for i in xrange(model.n_components): 205 for i in xrange(model.n_components):
204 mean = model.means_[i] 206 mean = nPixelsPerUnit*model.means_[i]
207 covariance = nPixelsPerUnit*model.covars_[i]
205 if dataset is not None: 208 if dataset is not None:
206 plt.scatter(dataset[labels == i, 0], dataset[labels == i, 1], .8, color=colors[i]) 209 plt.scatter(tmpDataset[labels == i, 0], tmpDataset[labels == i, 1], .8, color=colors[i])
207 plt.annotate(str(i), xy=(mean[0]+1, mean[1]+1)) 210 plt.annotate(str(i), xy=(mean[0]+1, mean[1]+1))
208 211
209 # Plot an ellipse to show the Gaussian component 212 # Plot an ellipse to show the Gaussian component
210 v, w = np.linalg.eigh(model.covars_[i]) 213 v, w = np.linalg.eigh(covariance)
211 angle = np.arctan2(w[0][1], w[0][0]) 214 angle = np.arctan2(w[0][1], w[0][0])
212 angle = 180*angle/np.pi # convert to degrees 215 angle = 180*angle/np.pi # convert to degrees
213 v *= 4 216 v *= 4
214 ell = mpl.patches.Ellipse(mean, v[0], v[1], 180+angle, color=colors[i]) 217 ell = mpl.patches.Ellipse(mean, v[0], v[1], 180+angle, color=colors[i])
215 ell.set_clip_box(fig.bbox) 218 ell.set_clip_box(fig.bbox)
216 ell.set_alpha(.5) 219 ell.set_alpha(alpha)
217 fig.axes[0].add_artist(ell) 220 fig.axes[0].add_artist(ell)