{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Modules Imported!\n" ] } ], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import scipy as sp\n", "import scipy.stats as st\n", "from IPython.display import Latex,display,Math\n", "import pandas as pd\n", "print(\"Modules Imported!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Maximum Likelihood Estimation\n", "## Properties of MLE" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[4pts]__Task:__ Write a function that, given samples drawn from $N(\\mu,\\sigma^2)$, returns the maximum likelihood estimates of $\\mu$ and $\\sigma^2$." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def NormML(y):\n", " # Your answer here:\n", " \n", " return [mu_hat, sigma_hat]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bias\n", "The tendency of an estimator to over- or under-estimate can be measured by its bias. \n", "\n", "[10pts]__Task:__ Prove that the estimator in the previous task is unbiased when estimating the mean but biased when estimating the variance. Find the value of bias for variance. Is it an over-estimation or under-estimation? (You can turn in this part either using [Markdown](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html) or attach a pdf or a picture of your solution.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Your answer here:\n", "(double click to edit)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "___\n", "We now want to see the effect of bias via simulation. \n", "\n", "[10pts]__Task:__ Generate 10000 batches of $N(3,4)$ samples, each containing 10 samples. Compute the estimates for each batch and then take their averages across batches. How do these averages compare with the true values? Is there a difference between the behaviors for the mean and the variance?" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "theta0 = [3,4] #[mean,variance]\n", "mynorm = st.norm(theta0[0],np.sqrt(theta0[1]))\n", "N = 10000 # number of batches\n", "n = 10 # samples per batch\n", "y = mynorm.rvs([N,n])\n", "\n", "# Your answer here:\n", "\n", "# Hints: create variables as following:\n", "# estimates for mu and sigma\n", "# estimates for mu\n", "# estimates for sigma\n", "# average in lieu of expected value\n", "# average in lieu of expected value\n", "# print results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Consistentcy\n", "Intuitively, _an estimator is consistent if it gives us the correct solution when we have lots of data_. To see this formally, consider a data set $\\{y_1,\\dotsc,y_N\\}$ where the distribution of each $y_i$ depends on some parameter $\\theta$. Denote the true value of $\\theta$ by $\\theta_0$. Let the ML estimator for this dataset be denoted as $\\hat\\theta_N$. We'd like to see how the accuracy of this estimator changes as $N\\to\\infty$. In particular, _the estimator is said to be consistent if $\\hat\\theta_N$ gets closer and closer to the true value $\\theta_0$_:\n", "$$\\lim_{N\\to\\infty} \\hat\\theta_N=\\theta_0.$$\n", "\n", "___\n", "[13pts]__Task:__ Generate a vector $y$ consisting of $N$ normal samples drawn from $N(\\mu_0,\\sigma_0^2)$ for $\\mu_0=3$, $\\sigma_0^2=4$ and a large value of $N$, say $N=500$. Then compute the estimates for $\\mu$ and $\\sigma^2$ using the first $n$ sample (that is y[0:n]) as $n$ ranges from 1 to $N$, choosing an appropriate step size. Plot the result and discuss it in the context of consistency. _Spoiler Alert: ML is consistent._" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "theta0 = [3,4] #[mean,variance]\n", "\n", "# Your answer here:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multivariate Normal Estimation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider the dataset $\\{x_1,\\dotsc,x_N\\}$, where each $x_i$ is a vector of size $m$. Assuming this data is multivariate normal, i.e., $x_i\\sim \\mathcal N(\\mu,K)$, we would like to find estimate $\\mu$ and $K$ using maximum likelihood.\n", "___\n", "[5pts]__Task:__ Write a module for estimating $\\mu$ and $K$. Assume that the input is a $N\\times m$ array $X$, where each row $x_i$ of $X$ is an $m$-dimensional data sample, with distribution $x_i\\sim \\mathcal N(\\mu,K)$." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def MultiVarNormML(X):\n", " # Your answer here:\n", " \n", " return muhat,Khat" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will use this estimator to explore relationships from a [dataset](http://archive.ics.uci.edu/ml/datasets/student+performance) about math performance for a group of students. First we read the data and then normalize the columns that we care about to have variance equal to 1. These features are:\n", "* Medu - mother's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)\n", "* Fedu - father's education (numeric: 0 - none, 1 - primary education (4th grade), 2 – 5th to 9th grade, 3 – secondary education or 4 – higher education)\n", "* studytime - weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)\n", "* failures - number of past class failures (numeric: n if 1<=n<3, else 4)\n", "* goout - going out with friends (numeric: from 1 - very low to 5 - very high)\n", "* G3 - final grade (numeric: from 0 to 20, output target)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "T=pd.read_csv('student-mat.csv',delimiter=';')\n", "dims = ['studytime','goout','failures','Medu','Fedu','G3']\n", "for s in dims:\n", " T[s] = T[s]/np.std(T[s])\n", "X = T[dims].values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[10pts]__Task:__ Find the ML estimate of $K$ for this data and discuss a couple of relationships that you observe. In particular, what appears to be more strongly correlated with final grade: mother's or father's education?" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# Your answer here:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Your discussion here:\n", "(double click to edit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_____\n", "_____\n", "### One more estimator property: Asymptotic Normality (optional, no extra credit, do at your own risk!)\n", "From the asymptotic normality of the ML estimator we have\n", "$$\\sqrt{n}(\\hat\\mu_{ML}-\\mu)\\to N(0,I^{-1}(\\mu))$$\n", "where $I$ is the Fisher information and in this case equals $I(\\mu)=\\frac{1}{\\sigma^2}$.\n", "\n", "And for $\\sigma^2$,\n", "$$\\sqrt{n}({\\hat\\sigma^2}_{ML}-\\sigma^2)\\to N(0,I^{-1}(\\sigma^2)),$$\n", "where $I(\\sigma^2)=1/(2\\sigma^4)$. \n", "\n", "[15pts]__Task:__ Using the batches and estimates from [the Bias section](#Bias), plot the histograms for the estimates (multiplied by $\\sqrt{n}$ as above) and compare them with the limit distribution given on the right side of the above expressions. Are the approximations by the limit distributions accurate to the same degree for both mean and the variance? If not, why do you think that is the case? (You can try with batches with more samples and verify that for large batches, they become increasingly better approximations).\n", "\n", "[5pts]__Bonus:__ Prove that $I(\\mu)=\\frac1{\\sigma_2}$." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# Your answer here:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Bonus question answer here:\n", "(double click to edit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Bayesian Estimation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bernoulli data and Beta prior\n", "Suppose you are given a sample of $n$ iid Bernoulli random variables with probability of success equal to $\\theta$. \n", "\n", "[8pts]__Task:__ Write a function that produces the frozen posterior of $\\theta$ given a Beta prior with pramaters $\\alpha$ and $\\beta$. Recall that a frozen RV is an object representing an RV with fixed parameters, e.g., \n", "\n", "rv = st.beta(a, b)\n", "\n", "and can be called for example to compute the pdf at a certain point as \n", "\n", "rv.pdf(0.3)\n", "" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def bayesBernBeta(data,prior):\n", " \"\"\" \n", " input:\n", " - data is an iid sample of Bernoulli RVs\n", " - prior=[alpha,beta], prior Beta parameters\n", " \"\"\"\n", " # Your answer here:\n", " \n", " return posterior" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "___\n", "The data is given below, in three different sizes. " ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# the data is a sample of 1000 iid bernoulli rvs\n", "sample = np.array([0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1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0, 0, 0, 1, 0, 1])\n", "small_sample = sample[:3]\n", "med_sample = sample[:50]\n", "large_sample = sample" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will use three different beta priors:\n", "- non-informative: uniform: $Beta(1,1)$.\n", "- non-informative: Jeffery's: $Beta(1/2,1/2)$.\n", "- informative: we believe that the prior peaks at $\\theta = 1/3$ and furthermore, we believe that the probibility that $\\theta<0.5$ is $60\\%$.\n", "\n", "[25pts]__Task:__ For the last case, you must find the $\\alpha$ and $\\beta$ parameters for a Beta prior that satisfies the condition. Generate 9 posterior plots, for different data and prior combinations and discuss their differences." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# Your answer here:\n" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 1 }