Principle component analysis (PCA)
Source code name: "stat_pca.py"
Programming language: Python
Topic: Statistics/PCA
DMelt Version 1. Last modified: 12/11/2015. License: Pro
https://datamelt.org/code/cache/stat_pca_5268.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.



from jhplot  import *
from java.util import Random
from jhplot.shapes import Line
from java.awt  import Color
from java.awt import BasicStroke


c1 = HPlot("Canvas",600,400)
c1.setNameX("X")
c1.setNameY("Y")
c1.visible(1)
c1.setRange(-4,4,-4,4)

p1 = P1D("Data")
rand = Random();
for i in range(200):
          x=rand.nextGaussian()
          y=rand.nextGaussian()
         #  p1.add(x, 0.5*x+0.1*y)
          # p1.add(x, -1.3*x-0.3*y)
          p1.add(x, y)
c1.draw(p1);


# principle component analysis
from jhpro.stat import * 
pca=EEcentricity(p1)
print "EECentricity 1=" ,pca.getEccentricity(), " angle=",pca.getAngle()



from jhplot.stat  import LinReg
r = LinReg(p1)
print "Intercept=",r.getIntercept(), "+/-",r.getInterceptError()
print "Slope=",r.getSlope(),"+/-",r.getSlopeError()

f1=r.getResult()
# get predictions as band
# pC=r.getConfidenceBand(Color.red,0.5)
c1.draw(f1)

# pP=r.getPredictionBand(Color.red,0.5)
# c1.draw(pP)



# principle component analysis
from jhplot.stat import PCA
pca=PCA(p1)
print "egev1=" , pca.getEigenvalue(0)
print "egen2=" , pca.getEigenvalue(1)

x1=pca.getEigenvalue(0)
x2=pca.getEigenvalue(1)
if (x1>x2) :
     x2=pca.getEigenvalue(0)
     x1=pca.getEigenvalue(1)
print "EEcentricity 2=",1-x1/x2


# draw 
p1=Line(pca.getMean(0),pca.getMean(1), pca.getCoordinate(0,0), pca.getCoordinate(0,1), BasicStroke(5),Color.red )
c1.add(p1)
p2=Line(pca.getMean(0), pca.getMean(1),pca.getCoordinate(1,0), pca.getCoordinate(1,1) ,BasicStroke(5),Color.red )
c1.add(p2)

c1.update()


You see the box below because you did not login.