{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Proba / statistiques - TP0\n",
"\n",
"The goal of this lab exercise is to learn:\n",
"\n",
"- basics of Python\n",
"- how to use the numpy library\n",
"- code a few things related to probabilities :)\n",
"\n",
"This lab exercise is not evaluated, but do it seriously it will help you for the nextons.\n",
"\n",
"## Python and numpy\n",
"\n",
"You need to install the following libraries: numpy and matplotlib. Please refer to the internet for instruction if you don't know how to do that.\n",
"\n",
"Numpy is one of the most popular numerical computation library in Python. For this lab exercise we are mainly interested in tensor computation. To start, some reading on python and numpy: https://cs231n.github.io/python-numpy-tutorial/\n",
"\n",
"Take time to do a few test, understand the different operation, the different between in-place and out-of-place operations, etc. The most important resource you must use is the numpy documentation. As we usually say in computer science: Read The F*cking Manual https://numpy.org/doc/stable/reference/index.html"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# import libraries\n",
"import numpy as np\n",
"import sklearn.datasets\n",
"\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# create a 2D tensor (i.e. a matrix) of shape (2, 5) full of zeros\n",
"# by default the tensor will contain elements of type float\n",
"t = np.zeros((2, 5))\n",
"print(\"Shape of the tensor: \", t.shape)\n",
"print(\"Content:\")\n",
"print(t)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A vector is a one dimension tensor.\n",
"# its usual to think about them as \"column vector\",\n",
"# i.e. a vector of 5 elements is similar in practice to a matrix of shape (5, 1)\n",
"\n",
"t = np.zeros((5, ))\n",
"print(\"Shape of the tensor: \", t.shape)\n",
"# yes, its displayed as \"row\", but mentally you need to think about it as a column :)\n",
"print(\"Content:\")\n",
"print(t)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You can reshape tensors\n",
"# When you reshape a tensor, it does not change the data order in the underlying memory.\n",
"# By default, this is the \"C array order\", also called the row-major format.\n",
"# If you don't know about this, check the wikipedia page:\n",
"# https://en.wikipedia.org/wiki/Row-_and_column-major_order\n",
"\n",
"# for example, the following operation will reshape t as a vector with ten elements\n",
"t = np.zeros((2, 5))\n",
"t = t.reshape(-1) # -1 means \"put every there\"\n",
"print(t.shape)\n",
"\n",
"# here instead of having a vector we build a tensor with a single row with ten elements\n",
"t = t.reshape(1, -1)\n",
"# of cours we could have done t = t.reshape(1, 10)\n",
"print(t.shape)\n",
"\n",
"# here a tensor with a single column with ten elements\n",
"t = t.reshape(-1, 1)\n",
"# of cours we could have done t = t.reshape(10, 1)\n",
"print(t.shape)\n",
"\n",
"# reshape into the original shape\n",
"t = t.reshape(2, -1)\n",
"print(t.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# this creates a vector with values from 0 to 3 (not included)\n",
"t = np.arange(4)\n",
"print(t)\n",
"\n",
"# reshape\n",
"t = t.reshape((2, 2))\n",
"print(t)\n",
"\n",
"# .T returns the transposed tensor\n",
"print(t.T)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# multiply the content of the tensor by two\n",
"# this is an out-of-place operation: it does not modify the tensory memory but creates a new one\n",
"t2 = 2 * t\n",
"\n",
"print(\"Original tensor:\")\n",
"print(t)\n",
"print(\"New tensor:\")\n",
"print(t2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# do the same thing but in-place\n",
"t *= 2\n",
"print(\"New content:\")\n",
"print(t)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# There are two multiplication operators:\n",
"# * is the element wise multiplication operator (also called the Hadamard product)\n",
"# @ is the matrix multiplication operator\n",
"\n",
"a = np.arange(4).reshape(2, 2)\n",
"# one_like create a tensor with the same properties (i.e. type and shape) than the argument\n",
"# but filled with ones\n",
"b = 2 * np.ones_like(a) \n",
"\n",
"print(\"a:\")\n",
"print(a)\n",
"print(\"b:\")\n",
"print(b)\n",
"print()\n",
"\n",
"# element wise multiplication\n",
"c = a * b\n",
"print(\"a * b:\")\n",
"print(c)\n",
"print()\n",
"\n",
"# matrix multiplication\n",
"c = a @ b\n",
"print(\"a @ b:\")\n",
"print(c)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# you can easily retrieve one row or one column of a tensor\n",
"print(\"a:\")\n",
"print(a)\n",
"print()\n",
"\n",
"print(\"first row of a:\")\n",
"print(a[0])\n",
"print()\n",
"\n",
"print(\"first column of a:\")\n",
"print(a[:, 0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# the same approach can be used to update the data in-place\n",
"print(\"a:\")\n",
"print(a)\n",
"print()\n",
"\n",
"# set the second colums elements to 10\n",
"a[:, 1] = 10.\n",
"print(\"after update:\")\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"One of the most important feature you have to understand is broadcasting. You can read the following article to understand operation broadcasting: https://numpy.org/devdocs/user/theory.broadcasting.html\n",
"\n",
"It is a very important concept that is really helpful in numpy and other numerical computation library. The documentation often explain of broadcasting is implemented for a given operation, check for example the matrix multiplication page: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = np.arange(6).reshape(2, -1)\n",
"print(\"a: \")\n",
"print(a)\n",
"print()\n",
"\n",
"# we will multpliy the first row by 2 and the second row by 4 by using operation broadcasting\n",
"# np.array can be used to create a tensor from python data\n",
"b = np.array([2, 4]).reshape((2, 1))\n",
"c = a * b\n",
"\n",
"print(\"new tensor:\")\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Of course, you can also retrieve a specific index or write a specif value into a tensor."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"t = np.zeros((2, 2))\n",
"print(t)\n",
"t[0, 1] = 10\n",
"print(t)\n",
"t *= 2\n",
"print(t)\n",
"print(t[0, 1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Empirical distribution, mean and variance\n",
"\n",
"To sample from a Gaussian you can use normal(loc=0.0, scale=1.0, size=None). Note that the parameters are the mean and the *standard deviation*, not the variance (again, read the doc!).\n",
"\n",
"You can compute the empirical mean and varince of the samples using np.var and np.mean."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"normal_samples = np.random.normal(size=(100))\n",
"\n",
"print(np.mean(normal_samples), np.var(normal_samples))\n",
"print(normal_samples.mean(), normal_samples.var())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO: compute the mean and variance without using mean and var\n",
"# instead, use sum(), addition and division\n",
"\n",
"todo todo todo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Compute the empirical mean and variance using different number of samples, for example 2, 5, 10, 20, 50, 100, 500, 1000, etc (use a loop! with range() or with a list of predefined values). What do you observe? Try when sampling from Gaussian with larger variance."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"todo todo todo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## PDF of a Gaussian\n",
"\n",
"The goal of this section is to visualize the probability density function of a Gaussian distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def gaussian_pdf(x, mean = 0, variance = 1):\n",
" # ** is the power operator\n",
" return np.exp( -( (x - mean)**2 ) / (2 * variance) ) / np.sqrt(variance * 2 * np.pi)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# display the PDF of a gaussian,\n",
"# try to play a little bit with the \n",
"mean = 0\n",
"variance = 1\n",
"\n",
"# the gaussian_pdf function works with numpy vectors!\n",
"# x is a vector with values from -4 to 4, taking steps of 0.1\n",
"x = np.arange(-4, 4, 0.1)\n",
"y = gaussian_pdf(x, mean, variance)\n",
"\n",
"# print the first five values in vectors x and y\n",
"print(\"x: \", x[:5])\n",
"print(\"y: \", y[:5])\n",
"\n",
"plt.plot(x, y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# as a second example, we can plot the log of the PDF and see that it has a nice quadratic form!\n",
"plt.plot(x, np.log(y))\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are now going to approximate the Gaussian PDF from samples using bins:\n",
"\n",
"1. We break the x axis into bins of same size\n",
"2. We count the number of samples in each bins\n",
"3. We renormalize the count\n",
"4. We using the bin counts to approximate the Gaussian function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"inputs:\n",
" - values: samples from a distribution\n",
" - lower_bound: left limit on the x axis\n",
" - upper_bound: right limit on the x axis\n",
" - number of bins to create\n",
"outputs:\n",
" - list: number of elements in each bins\n",
" - list: list of tuples that indicates the left and right boundary of each bin\n",
" - float: normalization constant (used to make the area represented by the bins sum to one)\n",
"\"\"\"\n",
"def count_elements(values, lower_bound, upper_bound, n_bins):\n",
" if upper_bound <= lower_bound or min(values) < lower_bound and max(values) > upper_bound:\n",
" raise RuntimeError(\"Invalid bounds\")\n",
"\n",
" # given the upper bound, lower bound and n_bins,\n",
" # what is the size of each bin?\n",
" # put this value in delta\n",
" delta = TODO TODO TODO\n",
" \n",
" # vector that will contain the number of value in each bin\n",
" hist = np.zeros((n_bins))\n",
" # bin_span is a list containing the span in each bin.\n",
" # for example, if you have 10 spans ranging in x axis from 1 to 10,\n",
" # the bin_spans would be a list [(1, 2), (2, 3), etc etc, (9, 10)]\n",
" bin_spans = TODO TODO TODO\n",
" \n",
" # now you must fill bin_spans, ie count the number of samples in values\n",
" # in each bin\n",
" # smart solution\n",
" #for v in values:\n",
" # idx = int(np.floor((v-lower_bound)/delta))\n",
" # hist[idx] += 1\n",
" TODO TODO TODO\n",
" \n",
" # normalization constant\n",
" norm = sum(hist) * delta\n",
" return hist, bin_spans, norm\n",
"\n",
"# test the function with uniform samples in [0, 1]\n",
"uniform_samples = np.random.random((10000))\n",
"h1, h1_spans, norm = count_elements(uniform_samples,0,1,10)\n",
"\n",
"# raw count\n",
"print(h1)\n",
"# normalized count, every one must be close to one...\n",
"print(h1 / norm)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# test the function with uniform samples in [0, 0.1]\n",
"# what do you observe compared to the example in the cell above? why?\n",
"uniform_samples = np.random.random((10000)) / 10\n",
"h2, h2_spans, norm = count_elements(uniform_samples,0,0.1,10)\n",
"\n",
"print(h2)\n",
"print(h2 / norm)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# we now sample from a Gaussian and print a plot with the \"bins\"\n",
"\n",
"# samples from a Gaussian\n",
"normal_samples = np.random.normal(size=(10000))\n",
"# create the bins\n",
"h2,h2_spans, norm = count_elements(normal_samples, min(normal_samples)-0.01, max(normal_samples)+0.01, 50)\n",
"\n",
"# compute the x and y values\n",
"# xs: correspond to a bin, you can take the \"center\" of each bin,\n",
"# use the spans computed by the function!\n",
"xs = TODO TODO TODO\n",
"\n",
"# ys: values for the y axes. what should it be?\n",
"ys = TODO TODO TODO\n",
"\n",
"plt.plot(xs, ys, color=\"red\")\n",
"plt.plot(xs,gaussian_pdf(xs), color=\"blue\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Try to print the graph with different number of samples (i.e. a small number of values, and then more and more). What do you observe?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"todo todo todo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conditional distribution\n",
"\n",
"We are now going to manipulate discrete distributions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"size_x = 10\n",
"size_y = 5\n",
"\n",
"logits = np.random.rand(size_x, size_y)\n",
"logits"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What does the following two cells compute? Why do we need to do that? Try to understand this precisely!\n",
"\n",
"Bonus: try to stabilize the softmax function, see https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def softmax(v):\n",
" if len(v.shape) != 1:\n",
" raise RuntimeError(\"v must be a vector\")\n",
" \n",
" return np.exp(v) / np.exp(v).sum()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"joint_distrib = softmax(logits.reshape(size_x * size_y)).reshape(size_x, size_y)\n",
"joint_distrib"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# check that it is a valid distribution\n",
"print(joint_distrib.sum(), np.alltrue(joint_distrib >= 0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the joint distribution parameters, compute:\n",
"\n",
"- the parameters of the marginals distribution p(y)\n",
"- the parameters of the conditional distribution p(x | y)\n",
"- transform p(y) and p(x | y) to get back the joint distribution parameters, i.e. joint_distrib2\n",
"- check that joint_distrib and joint_distrib2 are (almost) equal (use np.allclose)\n",
"\n",
"(check the documentation of the numpy sum function!!!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"todo todo todo"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate a joint distribution where X and Y are statistically independent. How can you do that? Do the same exercise, as above. What do you observe for the distribution p(x | y) ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"todo todo todo"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}