Machine Learning-Python
Testing your Homework 2 Solutions...
In [1]: import numpy as np
In [2]: import homework2solution as hw
In [3]: #Testing the find_closest_example function
In [4]: #We'll place a datapoint in each quadrant (in 2D plane example)
In [5]: tdata = np.array([ [-1,1], [1,1], [1, -1], [-1, -1] ])
In [6]: hw.find_closest_example(tdata, np.array([-6,9]) )
Out[6]: 0
In [7]: hw.find_closest_example(tdata, np.array([4,9]) )
...:
Out[7]: 1
In [8]: hw.find_closest_example(tdata, np.array([-3,-4]) )
Out[8]: 3
In [9]: hw.find_closest_example(tdata, np.array([3,-4]) )
Out[9]: 2
In [10]: #Note that 0 means the first example, or the example in the first row in the training data
In [11]: #Now testing three dimensional problems
In [12]: tdata = np.array([ [1, -5, 1], [3, 5, 0], [-5, -6, -7] ])
In [13]: hw.find_closest_example(tdata, np.array([-2, -4,-8]) )
Out[13]: 2
In [14]: # Now testing the calculate_centroid_pos function
In [15]: mydata = np.array( [ [1, 2], [3, 4], [5, 6] ])
In [16]: hw.calculate_centroid_pos(mydata)
Out[16]: array([3., 4.])
In [17]: # Now testing higher dimensions
In [18]: mydata = np.array([ [ 1, 2, 3], [4, 5, 6], [7, 8, 9] ])
In [19]: hw.calculate_centroid_pos(mydata)
Out[19]: array([4., 5., 6.])
In [20]: # Now simulating perceptron classification (using examples from our lecture slides)
In [21]: w = np.array([-5, 1, 1])
In [22]: x = np.array([ [ 1, 5] ])
In [23]: hw.classify_examples(w, x)
Out[23]: array([1.])
In [24]: x = np.array([ [1, 3] ])
In [25]: hw.classify_examples(w, x)
Out[25]: array([-1.])
In [26]: x = np.array([ [1, 1] ])
In [27]: hw.classify_examples(w, x)
Out[27]: array([-1.])
In [28]: x = np.array([ [4, 3] ])
In [29]: hw.classify_examples(w, x)
Out[29]: array([1.])
In [30]: # Now we pass them as a batch 2D numpy array
In [31]: x = np.array([ [1,5], [1, 3], [1, 1], [4, 3] ])
In [32]: hw.classify_examples(w, x)
Out[32]: array([ 1., -1., -1., 1.])
In [33]: # Good luck! :)