Artificial intelligence (Intermediate)

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.

Getting ready

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.

How to do it...

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.

  1. Generating random points: We will generate 30 random point positions within a square of 400 by 400 pixels:
    positions = numpy.random.randint(0, 400, size=(30, 2))
    
  2. Calculating the affinity matrix: We will use the Euclidean distance to the origin as the affinity metric. The affinity matrix is a matrix holding affinity scores, in this case distances:
    positions_norms = numpy.sum(positions ** 2, axis=1)
    S = - positions_norms[:, numpy.newaxis] - positions_norms[numpy.newaxis, :] + 2 * numpy.dot(positions, positions.T)
    
  3. Clustering the points: Give the 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_
    
  4. Drawing polygons: We will draw polygons for each cluster. The function involved requires a list of points, a color (let's paint it red), and a surface:
    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:

    How to do it...

    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()

How it works...

The most important lines in the artificial intelligence recipe are described in more detail in the following table:

Function

Description

numpy.random.randint(0, 400, size=(30, 2))

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.

numpy.sum(positions ** 2, axis=1)

This sums an array of the square of the positions array.

numpy.dot(positions, positions.T)

This computes the dot product of the positions array and its transpose.

sklearn.cluster.AffinityPropagation().fit(S)

This creates an AffinityPropagation object and performs a fit using an affinity matrix.

pygame.draw.polygon(screen, (255, 0, 0), polygon_points[i])

This draws a polygon given a surface, a color (red in this case), and a list of points.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset