Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
| Download
Project: test
Views: 91872# -*- coding: utf-8 -*-1"""23py.test module to test stats.py module.456Created on Wed Aug 27 06:45:06 201478@author: rlabbe9"""10from __future__ import division11from math import pi, exp12import numpy as np13from stats import gaussian, multivariate_gaussian, _to_cov14from numpy.linalg import inv15from numpy import linalg161718def near_equal(x,y):19return abs(x-y) < 1.e-15202122def test_gaussian():23import scipy.stats2425mean = 3.26var = 1.527std = var**0.52829for i in np.arange(-5,5,0.1):30p0 = scipy.stats.norm(mean, std).pdf(i)31p1 = gaussian(i, mean, var)3233assert near_equal(p0, p1)34353637def norm_pdf_multivariate(x, mu, sigma):38""" extremely literal transcription of the multivariate equation.39Slow, but easy to verify by eye compared to my version."""4041n = len(x)42sigma = _to_cov(sigma,n)4344det = linalg.det(sigma)4546norm_const = 1.0 / (pow((2*pi), n/2) * pow(det, .5))47x_mu = x - mu48result = exp(-0.5 * (x_mu.dot(inv(sigma)).dot(x_mu.T)))49return norm_const * result50515253def test_multivariate():54from scipy.stats import multivariate_normal as mvn55from numpy.random import rand5657mean = 358var = 1.55960assert near_equal(mvn(mean,var).pdf(0.5),61multivariate_gaussian(0.5, mean, var))6263mean = np.array([2.,17.])64var = np.array([[10., 1.2], [1.2, 4.]])6566x = np.array([1,16])67assert near_equal(mvn(mean,var).pdf(x),68multivariate_gaussian(x, mean, var))6970for i in range(100):71x = np.array([rand(), rand()])72assert near_equal(mvn(mean,var).pdf(x),73multivariate_gaussian(x, mean, var))7475assert near_equal(mvn(mean,var).pdf(x),76norm_pdf_multivariate(x, mean, var))777879mean = np.array([1,2,3,4])80var = np.eye(4)*rand()8182x = np.array([2,3,4,5])8384assert near_equal(mvn(mean,var).pdf(x),85norm_pdf_multivariate(x, mean, var))8687888990