Commit 6c3c45fc authored by Taddeüs Kroes's avatar Taddeüs Kroes

StatRed: Implemented Lab Excercises 21 and 22.

parent 495fa7cb
#from math import mean
#import matplotlib.pyplot as plt
from numpy.random import multivariate_normal
def mu_est(x):
return sum(x) / float(len(x))
def cov_est(x):
avg = mean(x)
n = len(x)
# TODO: transpose the second "(i - avg)"
return sum([(i - avg)*(i - avg) for i in x]) / float(n-1)
mean = [0,0]
cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
N = 512 # Samples to use.
x,y = multivariate_normal(mean, cov, N).T
print 'x:', x
print 'y:', y
print 'mu_est(x):', mu_est(x)
print 'mu_est(y):', mu_est(y)
from pylab import array, eig, diagflat, dot, sqrt, randn, tile, \ from pylab import array, eig, diagflat, dot, sqrt, randn, tile, \
plot, subplot, axis, show, figure, clf plot, subplot, axis, figure, clf, savefig
mean = array([[3], mu = array([[3],
[4], [4],
[5], [5],
[6]]) [6]])
...@@ -15,20 +15,21 @@ cov = array( ...@@ -15,20 +15,21 @@ cov = array(
samples = 1000 samples = 1000
vector_size = 4 vector_size = 4
figure(16) def dataset():
clf() d, U = eig(cov)
L = diagflat(d)
A = dot(U, sqrt(L))
X = randn(vector_size, samples)
return dot(A,X) + tile(mu, samples)
d, U = eig(cov) if __name__ == '__main__':
L = diagflat(d) figure(vector_size**2)
A = dot(U, sqrt(L)) clf()
X = randn(vector_size, samples) Y = dataset()
Y = dot(A,X) + tile(mean, samples) for i in range(vector_size):
for j in range(vector_size):
for i in range(1, 5): if i != j:
for j in range(1, 5): subplot(vector_size, vector_size, (i+1) + j*vector_size)
if i != j: plot(Y[i], Y[j], 'x')
subplot(4, 4, i+(j-1)*4) axis('equal')
plot(Y[i-1], Y[j-1], 'x') savefig('figures/q21.pdf')
axis('equal')
show()
from q21_multivariate import dataset, samples
from numpy import array, mean, tile, newaxis, dot
n = 1000
Y = array([mean(dataset(), 1) for i in range(n)]).T
mu = mean(Y, 1)
Yzm = Y - tile(mu[:,newaxis], n)
S = dot(Yzm, Yzm.T) / (n - 1)
print 'S:', S
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment