01.04.2015 Views

1FfUrl0

1FfUrl0

1FfUrl0

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Getting Started with Python Machine Learning<br />

The funny thing starts when we realize just how much the NumPy package is<br />

optimized. For example, it avoids copies wherever possible.<br />

>>> b[1][0]=77<br />

>>> b<br />

array([[ 0, 1],<br />

[77, 3],<br />

[ 4, 5]])<br />

>>> a<br />

array([ 0, 1, 77, 3, 4, 5])<br />

In this case, we have modified the value 2 to 77 in b, and we can immediately see<br />

the same change reflected in a as well. Keep that in mind whenever you need a<br />

true copy.<br />

>>> c = a.reshape((3,2)).copy()<br />

>>> c<br />

array([[ 0, 1],<br />

[77, 3],<br />

[ 4, 5]])<br />

>>> c[0][0] = -99<br />

>>> a<br />

array([ 0, 1, 77, 3, 4, 5])<br />

>>> c<br />

array([[-99, 1],<br />

[ 77, 3],<br />

[ 4, 5]])<br />

Here, c and a are totally independent copies.<br />

Another big advantage of NumPy arrays is that the operations are propagated<br />

to the individual elements.<br />

>>> a*2<br />

array([ 2, 4, 6, 8, 10])<br />

>>> a**2<br />

array([ 1, 4, 9, 16, 25])<br />

Contrast that to ordinary Python lists:<br />

>>> [1,2,3,4,5]*2<br />

[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]<br />

>>> [1,2,3,4,5]**2<br />

Traceback (most recent call last):<br />

File "", line 1, in <br />

TypeError: unsupported operand type(s) for ** or pow(): 'list' and<br />

'int'<br />

[ 14 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!