[Tutor] Help- Regarding python

Alan Gauld alan.gauld at btinternet.com
Mon Feb 4 09:45:10 CET 2013

On 04/02/13 06:24, Gayathri S wrote:
> Hi All....!
>              If i have data set like this means...
> 3626,5000,2918,5000,2353,2334,2642,1730,1687,1695,1717,1744,593,502,493,504,449,431,444,444,429,10
> 458,5022,3640,3644,5000,2922,5000,2346,2321,2628,1688,1666,1674,1696,744,590,496.
> How to do PCA on this data? if it is in array how to do that? and also
> how to use princomp() in PCA?

No idea. I don't know what pca or princomp are.
It looks like they might be numpy or pylab functions in which case you 
probably will get better results posting on a forum for those modules.
This list is for learning the core language and standard library.

Having said that it looks like you could use some time learning the 
basics before delving into numpy etc. comments below...

> from numpy import mean,cov,double,cumsum,dot,linalg,array,rank
> from pylab import plot,subplot,axis,stem,show,figure
> A = array([ [2.4,0.7,2.9,2.2,3.0,2.7,1.6,1.1,1.6,0.9],
>              [2.5,0.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1] ])
> M = (A-mean(A.T,axis=1)).T[latent,coeff] = linalg.eig(cov(M))
> score = dot(coeff.T,M)
> return coeff,score,latent

You have a return that is not inside a function. That makes no sense
and in fact I get a syntax error so presumably you haven't actually 
tried running this code.

> princomp(A):

This calls princomp() but does nothing with the return values

> coeff, score, latent = princomp(A.T)

This calls princomp() and stores 3 return values.
Its unusual for a function to have such different semantics.
Which is correct?

> figure()
> subplot(121)

Again calling functions without storing values. It may be valid
but looks unlikely...

> m = mean(A,axis=1)
> plot([0, -coeff[0,0]*2]+m[0], [0, -coeff[0,1]*2]+m[1],'--k')
> plot([0, coeff[1,0]*2]+m[0], [0, coeff[1,1]*2]+m[1],'--k')
> plot(A[0,:],A[1,:],'ob') # the data
> axis('equal')
> subplot(122)
> plot(score[0,:],score[1,:],'*g')
> axis('equal')
> plt.show()

Here you use plt but plt is not defined anywhere in your program.

I think you need to go back to Python basics and learn
how to write basic code before trying to use the more
exotic modules.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list