We will generate some random points and cluster them, which means that points that are close to each other are put in the same cluster. This is only one of the many techniques that you can apply with scikit-learn
. Clustering is a type of machine learning algorithm, which aims to group items based on similarities. Second, we will calculate a square affinity matrix. An affinity matrix is a matrix containing affinity values; for instance, distances between points. Finally, we will cluster the points with the AffinityPropagation
class from scikit-learn
. Perform the following steps to cluster points:
positions = np.random.randint(0, 400, size=(30, 2))
positions_norms = np.sum(positions ** 2, axis=1) S = - positions_norms[:, np.newaxis] - positions_norms[np.newaxis, :] + 2 * np.dot(positions, positions.T)
AffinityPropagation
class the result from the previous step. This class labels the points with the appropriate cluster number.aff_pro = sklearn.cluster.AffinityPropagation().fit(S) labels = aff_pro.labels_
pygame.draw.polygon(screen, (255, 0, 0), polygon_points[i])
The result is a bunch of polygons for each cluster, as shown in the following screenshot:
The clustering example code is as follows:
import numpy as np import sklearn.cluster import pygame, sys from pygame.locals import * positions = np.random.randint(0, 400, size=(30, 2)) positions_norms = np.sum(positions ** 2, axis=1) S = - positions_norms[:, np.newaxis] - positions_norms[np.newaxis, :] + 2 * np.dot(positions, positions.T) aff_pro = sklearn.cluster.AffinityPropagation().fit(S) labels = aff_pro.labels_ polygon_points = [] for i in xrange(max(labels) + 1): polygon_points.append([]) # Sorting points by cluster for i in xrange(len(labels)): polygon_points[labels[i]].append(positions[i]) pygame.init() screen = pygame.display.set_mode((400, 400)) while True: for i in xrange(len(polygon_points)): pygame.draw.polygon(screen, (255, 0, 0), polygon_points[i]) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
The most important lines in the artificial intelligence example are described in more detail in the following table:
Function |
Description |
---|---|
This creates an | |
This draws a polygon given a surface, a color (red in this case), and a list of points. |