Source

ml-class / ex2_2.py

#!/usr/bin/env python

import numpy as np
from ex2_1 import plot

def load():
    data = np.loadtxt('ex2/ex2data2.txt', delimiter=',')
    return data[:,0:2], data[:,2]

def map_feature(x1, x2):
    '''
    Maps the two input features to quadratic features.

    Returns a new feature array with more features, comprising of
    X1, X2, X1 ** 2, X2 ** 2, X1*X2, X1*X2 ** 2, etc...

    Inputs X1, X2 must be the same size
    '''
    x1.shape = (x1.size, 1)
    x2.shape = (x2.size, 1)
    degree = 6
    out = np.ones(shape=(x1[:, 0].size, 1))

    for i in range(1, degree + 1):
        for j in range(i + 1):
            r = (x1 ** (i - j)) * (x2 ** j)
            out = np.append(out, r, axis=1)

    return out



if __name__ == '__main__':
    data = load()
    plot(data, 't1', 't2')