{ "cells": [ { "cell_type": "markdown", "id": "20fce00f", "metadata": {}, "source": [ "# ML, Data Analysis\n", "### Probability: covariance \n", "\n", "The **covariance** is a measure that indicates the extent to which two random variables change together. It is the expected value of the product of their deviations from their individual means. specifically covariance between two random variables $X$ and $Y$ is computed by the following formula:\n", "
\n", "$\\large cov(X,Y)=E[(X-E[X])(Y-E(Y))]$\n", "
\n", "\n", "where $E[X]$ and $E[Y]$ denote the *expected values* of random variables $X$ and $Y$, respectively. We have discussed about the **expected value** in an earlier post.\n", "
We can show that *covariance* can also be computed by:\n", "
\n", "$\\large cov(X,Y)=E[XY]-E[X]E[Y]$\n", "
\n", "\n", "**Hint:** We also call $E[X]$ the **mean** of $X$, and $E[Y]$ the mean of $Y$.\n", "
\n", "
Some properties of covariance:\n", "1. **Variance connection:** $cov(X,X)=var(X)$\n", "2. **Symmetry:** $cov(X,Y)=cov(Y,X)$\n", "3. **Linearity:** For constants $a$, $b$, $c$, and $d$ we have: $cov(aX+b,cY+d)=ac\\cdot cov(X,Y)$\n", "4. **Uncorrelated variables:** For *uncorrelated* random variables $X$ and $Y$ ($E[XY]=E[X]E[Y]$), we have:$cov(X,Y)=0$\n", "\n", "**Hint:** We can express the variance of sum of two random variables by:\n", "
\n", "$\\large var(X+Y)=var(X)+var(Y)+2cov(X,Y)$\n", "
\n", "\n", "**Reminder:** For the topic on the **expected value**, see the relevent post on this repository.\n", "
\n", "\n", "**Contents:**\n", " - Computing the covariance for discrete random variables.\n", " - Computing the covariance for continuous random variables.\n", "\n", "
\n", "https://github.com/ostad-ai/Machine-Learning\n", "
Explanation: https://www.pinterest.com/HamedShahHosseini/Machine-Learning/background-knowledge" ] }, { "cell_type": "code", "execution_count": 1, "id": "f0c89242", "metadata": {}, "outputs": [], "source": [ "# Import the required function for double integration\n", "from scipy.integrate import dblquad" ] }, { "cell_type": "code", "execution_count": 2, "id": "d4430b1d", "metadata": {}, "outputs": [], "source": [ "# Functions for discerete random variables\n", "def mean(data,probs=None):\n", " n=len(data)\n", " if probs is None:\n", " probs=[1/n]*n\n", " return sum(x*p for x,p in zip(data,probs))\n", "\n", "def covariance(X,Y,probs=None):\n", " if len(X) != len(Y):\n", " raise ValueError(\"X and Y must have the same length.\")\n", " mu_X = mean(X,probs)\n", " mu_Y = mean(Y,probs)\n", " n=len(X)\n", " if probs is None:\n", " probs=[1/n]*n\n", " cov = sum([p*(x - mu_X) *(y - mu_Y) for x,y,p in zip(X,Y,probs)])\n", " return cov" ] }, { "cell_type": "code", "execution_count": 3, "id": "eb2a6b01", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "We have pairs (x_i,y_i) as outcomes\n", "[(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]\n", "The covariance of X and Y: -2.9166666666666665\n" ] } ], "source": [ "# Example: discrete random variables\n", "xs = [1, 2, 3, 4, 5, 6]\n", "ys = [6, 5, 4, 3, 2, 1]\n", "print(f'We have pairs (x_i,y_i) as outcomes')\n", "print(f'{[(x,y) for x,y in zip(xs,ys)]}')\n", "print(f'The covariance of X and Y: {covariance(xs,ys)}')" ] }, { "cell_type": "markdown", "id": "1c730379", "metadata": {}, "source": [ "
" ] }, { "cell_type": "code", "execution_count": 4, "id": "e97de675", "metadata": {}, "outputs": [], "source": [ "# Functions for continuous random variables\n", "# Joint PDF: f(x, y) = x + y, defined on [0,1]x[0,1]\n", "def joint_pdf(x, y):\n", " return x + y if (0 <= x <= 1) and (0 <= y <= 1) else 0\n", "\n", "# Compute E[X], E[Y], E[XY], and Cov(X, Y)\n", "def compute_covariance():\n", " # Marginal mean E[X]\n", " E_X, _ = dblquad(lambda x, y: x * joint_pdf(x, y), 0, 1, 0, 1)\n", " \n", " # Marginal mean E[Y]\n", " E_Y, _ = dblquad(lambda x, y: y * joint_pdf(x, y), 0, 1, 0, 1)\n", " \n", " # E[XY]\n", " E_XY, _ = dblquad(lambda x, y: x * y * joint_pdf(x, y), 0, 1, 0, 1)\n", " \n", " # Covariance\n", " cov = E_XY - E_X * E_Y\n", " return cov" ] }, { "cell_type": "code", "execution_count": 5, "id": "d47e820d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The joint pdf is defined in [0,1]*[0,1] by f(x,y)=x+y\n", "The cov(X,Y): -0.006944\n" ] } ], "source": [ "# Example: continuous random variables\n", "covariance_XY = compute_covariance()\n", "print('The joint pdf is defined in [0,1]*[0,1] by f(x,y)=x+y')\n", "print(f\"The cov(X,Y): {covariance_XY:.6f}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "e4203044", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.1" } }, "nbformat": 4, "nbformat_minor": 5 }