| 39 | |
| 40 | |
| 41 | def plot_clusters(model, X, ax): |
| 42 | C = model.C |
| 43 | |
| 44 | xmin = min(X[:, 0]) - 0.1 * (max(X[:, 0]) - min(X[:, 0])) |
| 45 | xmax = max(X[:, 0]) + 0.1 * (max(X[:, 0]) - min(X[:, 0])) |
| 46 | ymin = min(X[:, 1]) - 0.1 * (max(X[:, 1]) - min(X[:, 1])) |
| 47 | ymax = max(X[:, 1]) + 0.1 * (max(X[:, 1]) - min(X[:, 1])) |
| 48 | |
| 49 | for c in range(C): |
| 50 | rv = multivariate_normal(model.mu[c], model.sigma[c], allow_singular=True) |
| 51 | |
| 52 | x = np.linspace(xmin, xmax, 500) |
| 53 | y = np.linspace(ymin, ymax, 500) |
| 54 | |
| 55 | X1, Y1 = np.meshgrid(x, y) |
| 56 | xy = np.column_stack([X1.flat, Y1.flat]) |
| 57 | |
| 58 | # density values at the grid points |
| 59 | Z = rv.pdf(xy).reshape(X1.shape) |
| 60 | ax = plot_countour(X, X1, Y1, Z, ax=ax, xlim=(xmin, xmax), ylim=(ymin, ymax)) |
| 61 | ax.plot(model.mu[c, 0], model.mu[c, 1], "ro") |
| 62 | |
| 63 | # plot data points |
| 64 | cm = ListedColormap(sns.color_palette().as_hex()) |
| 65 | labels = model.Q.argmax(1) |
| 66 | uniq = set(labels) |
| 67 | for i in uniq: |
| 68 | ax.scatter(X[labels == i, 0], X[labels == i, 1], c=cm.colors[i - 1], s=30) |
| 69 | return ax |
| 70 | |
| 71 | |
| 72 | def plot(): |