Often we need to mimic intelligent behavior within a game. The scikits-learn
project aims to provide an API for Machine Learning. What I like most about it is the amazing documentation.
We can install scikit-learn
by typing the following command at the command line:
pip install -U scikit-learn
Or:
easy_install -U scikit-learn
This might not work because of permissions, so you might need to put sudo
in front of the commands or log in as admin.
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 scikits-learn
. Clustering is a type of machine learning algorithm that aims to group items based on similarities.
positions = numpy.random.randint(0, 400, size=(30, 2))
positions_norms = numpy.sum(positions ** 2, axis=1) S = - positions_norms[:, numpy.newaxis] - positions_norms[numpy.newaxis, :] + 2 * numpy.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 shown as follows:
import numpy import sklearn.cluster import pygame, sys from pygame.locals import * positions = numpy.random.randint(0, 400, size=(30, 2)) positions_norms = numpy.sum(positions ** 2, axis=1) S = - positions_norms[:, numpy.newaxis] - positions_norms[numpy.newaxis, :] + 2 * numpy.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, l in enumerate(labels): polygon_points[l].append(positions[i]) pygame.init() screen = pygame.display.set_mode((400, 400)) while True: for point in polygon_points: pygame.draw.polygon(screen, (255, 0, 0), point) 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 recipe are described in more detail in the following table:
Function |
Description |
---|---|
|
This creates an array of 30 by 2 random integers. This corresponds to 30 points in two-dimensional space. The values are between 0 and 400. |
|
This sums an array of the square of the positions array. |
|
This computes the dot product of the positions array and its transpose. |
|
This creates an |
|
This draws a polygon given a surface, a color (red in this case), and a list of points. |