Wednesday, September 28, 2011

Python 2.7 Setup Steps

UPDATE 2013:
Now follow these instructions: https://python-guide.readthedocs.org/en/latest/starting/install/win.html
Use distribute, not setuptools as described here
/UPDATE

I've set up Python 2.7 on several wind0ze machines recently, these are the "best practice" steps I now use:

  • Download and install Python 2.7 to C:\Python27
  • Download and install setuptools to C:\Python27\Lib\site-packages\
    (setuptools includes easy_install, so we can install pip! Read instructions for 32 vs 64bit versions)
  • Add env variable PYTHON_HOME=C:\Python27
  • Append env variable PATH with ;%PYTHON_HOME%;%PYTHON_HOME%\Scripts;
  • Run C:\Python27\Scripts>easy_install-2.7 pip to install pip
  • Install virtualenv: easy_install-2.7 virtualenv (now all pip install commands I run from a new virtualenv)
That takes care of the base environment.

Next is to install packages as required, remembering that matplotlib is best installed using an installer after executing "pip install numpy".

References:
pip Installation instructions (recommends installing pip using virtualenv)
Public service announcement (tool transition infographic)
How to install pip on Windows (installing pip globally using setuptools)
Installing matplotlib

Wednesday, September 14, 2011

python to solve linear system

Solving good ol' Ax=b:

>>> import numpy as np
>>> A = np.matrix('[3 -1 1; -1 1 -1; 1 -1 3]')
>>> A
matrix([[ 3, -1,  1],
        [-1,  1, -1],
        [ 1, -1,  3]])
>>> b = np.matrix('[1;1;1]')
>>> from scipy import linalg
>>> x = linalg.solve(A,b)
>>> x
array([[ 1.],
       [ 3.],
       [ 1.]])

See docs:
numpy.linalg.solve
routines.linalg
numpy solve examples (prob better than above!)

Tuesday, September 6, 2011

python to visualise vectors

I've been working on a simple example SVM problem and wanted to be able to visualise the vectors in 3D. Python with Matplotlib works nicely.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


fig = plt.figure()
ax = Axes3D(fig)


ax.plot3D([0,-1], [0,1], [0,1], zdir='z', label='x1 +1')
ax.plot3D([0,0], [0,1], [0,0], zdir='z', label='x2 -1')
ax.plot3D([0,1], [0,1], [0,1], zdir='z', label='x3 +1')
ax.plot3D([0,0], [0,0], [0,0], zdir='z', label='x4 +1')


ax.scatter([0,-1], [0,1], [0,1], zdir='z', label='x1')
ax.scatter([0,0], [0,1], [0,0], zdir='z', label='x2')
ax.scatter([0,1], [0,1], [0,1], zdir='z', label='x3')
ax.scatter([0,0], [0,0], [0,0], zdir='z', label='x4')


ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


ax.legend()
plt.show()



To add an equation to the graph:

import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x**2
ax.plot3D(x, y, 0);