File size: 6,120 Bytes
bcf16ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
{
 "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",
    "<div style=\"margin-top: 6px;\"></div>\n",
    "$\\large cov(X,Y)=E[(X-E[X])(Y-E(Y))]$\n",
    "<div style=\"margin-bottom: 6px;\"></div>\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",
    "<br> We can show that *covariance* can also be computed by:\n",
    "<div style=\"margin-top: 6px;\"></div>\n",
    "$\\large cov(X,Y)=E[XY]-E[X]E[Y]$\n",
    "<div style=\"margin-bottom: 6px;\"></div>\n",
    "\n",
    "**Hint:** We also call $E[X]$ the **mean** of $X$, and $E[Y]$ the mean of $Y$.\n",
    "<br>\n",
    "<br>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",
    "<div style=\"margin-top: 6px;\"></div>\n",
    "$\\large var(X+Y)=var(X)+var(Y)+2cov(X,Y)$\n",
    "<div style=\"margin-bottom: 6px;\"></div>\n",
    "\n",
    "**Reminder:** For the topic on the **expected value**, see the relevent post on this repository.\n",
    "<hr>\n",
    "\n",
    "**Contents:**\n",
    " - Computing the covariance for discrete random variables.\n",
    " - Computing the covariance for continuous random variables.\n",
    "\n",
    "<hr>\n",
    "https://github.com/ostad-ai/Machine-Learning\n",
    "<br> 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": [
    "<hr style=\"height:5px;background-color:lightgreen\">"
   ]
  },
  {
   "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
}