Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #Libraries
  2. from sklearn.mixture import GaussianMixture
  3. from matplotlib.patches import Ellipse
  4.  
  5. #------Just To visualise the results----#
  6. def draw_ellipse(position, covariance, ax=None, **kwargs):
  7. """Draw an ellipse with a given position and covariance"""
  8. ax = ax or plt.gca()
  9.  
  10. # Convert covariance to principal axes
  11. if covariance.shape == (2, 2):
  12. U, s, Vt = np.linalg.svd(covariance)
  13. angle = np.degrees(np.arctan2(U[1, 0], U[0, 0]))
  14. width, height = 2 * np.sqrt(s)
  15. else:
  16. angle = 0
  17. width, height = 2 * np.sqrt(covariance)
  18.  
  19. # Draw the Ellipse
  20. for nsig in range(1, 4):
  21. ax.add_patch(Ellipse(position, nsig * width, nsig * height,
  22. angle, **kwargs))
  23.  
  24. def plot_gmm(gmm, X, label=True, ax=None):
  25. ax = ax or plt.gca()
  26. labels = gmm.fit(X).predict(X)
  27. if label=='r':
  28. ax.scatter(X[:, 0], X[:, 1], s=40, zorder=2, c=label,marker='+')
  29. else:
  30. ax.scatter(X[:, 0], X[:, 1], s=40, zorder=2,c=label,marker='_')
  31. ax.axis('equal')
  32.  
  33. w_factor = 0.2 / gmm.weights_.max()
  34. for pos, covar, w in zip(gmm.means_, gmm.covariances_, gmm.weights_):
  35. draw_ellipse(pos, covar, alpha=w * w_factor)
  36.  
  37. #Segragating the positive and negative class
  38. positive_class = df[df['Class']=='+'][['f1','f2']]
  39. negative_class = df[df['Class']=='-'][['f1','f2']]
  40.  
  41. #Fiting the Gaussian curve
  42. gmm_positive = GaussianMixture(n_components=1).fit(positive_class)
  43. gmm_negative = GaussianMixture(n_components=1).fit(negative_class)
  44.  
  45. #Visualising the results
  46. plot_gmm(gmm_positive, np.array(positive_class),label = 'r')
  47. plot_gmm(gmm_negative, np.array(negative_class),label = 'b')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement