{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "execution": {}, "id": "view-in-github" }, "source": [ "\"Open   \"Open" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "# Tutorial 1: Geometric view of data\n", "\n", "**Week 1, Day 4: Dimensionality Reduction**\n", "\n", "**By Neuromatch Academy**\n", "\n", "__Content creators:__ Alex Cayco Gajic, John Murray\n", "\n", "__Content reviewers:__ Roozbeh Farhoudi, Matt Krause, Spiros Chavlis, Richard Gao, Michael Waskom, Siddharth Suresh, Natalie Schaworonkow, Ella Batty" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "

" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Tutorial Objectives\n", "\n", "*Estimated timing of tutorial: 50 minutes*\n", "\n", "In this notebook we'll explore how multivariate data can be represented in different orthonormal bases. This will help us build intuition that will be helpful in understanding PCA in the following tutorial. \n", "\n", "Overview:\n", " - Generate correlated multivariate data.\n", " - Define an arbitrary orthonormal basis. \n", " - Project the data onto the new basis." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Tutorial slides\n", "\n", "# @markdown These are the slides for the videos in all tutorials today\n", "from IPython.display import IFrame\n", "IFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/kaq2x/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Video 1: Geometric view of data\n", "from ipywidgets import widgets\n", "\n", "out2 = widgets.Output()\n", "with out2:\n", " from IPython.display import IFrame\n", " class BiliVideo(IFrame):\n", " def __init__(self, id, page=1, width=400, height=300, **kwargs):\n", " self.id=id\n", " src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n", " super(BiliVideo, self).__init__(src, width, height, **kwargs)\n", "\n", " video = BiliVideo(id=\"BV1Af4y1R78w\", width=854, height=480, fs=1)\n", " print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n", " display(video)\n", "\n", "out1 = widgets.Output()\n", "with out1:\n", " from IPython.display import YouTubeVideo\n", " video = YouTubeVideo(id=\"THu9yHnpq9I\", width=854, height=480, fs=1, rel=0)\n", " print('Video available at https://youtube.com/watch?v=' + video.id)\n", " display(video)\n", "\n", "out = widgets.Tab([out1, out2])\n", "out.set_title(0, 'Youtube')\n", "out.set_title(1, 'Bilibili')\n", "\n", "display(out)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# Imports\n", "import numpy as np\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Figure Settings\n", "import ipywidgets as widgets # interactive display\n", "%config InlineBackend.figure_format = 'retina'\n", "plt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/main/nma.mplstyle\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Plotting Functions\n", "\n", "def plot_data(X):\n", " \"\"\"\n", " Plots bivariate data. Includes a plot of each random variable, and a scatter\n", " plot of their joint activity. The title indicates the sample correlation\n", " calculated from the data.\n", "\n", " Args:\n", " X (numpy array of floats) : Data matrix each column corresponds to a\n", " different random variable\n", "\n", " Returns:\n", " Nothing.\n", " \"\"\"\n", "\n", " fig = plt.figure(figsize=[8, 4])\n", " gs = fig.add_gridspec(2, 2)\n", " ax1 = fig.add_subplot(gs[0, 0])\n", " ax1.plot(X[:, 0], color='k')\n", " plt.ylabel('Neuron 1')\n", " plt.title('Sample var 1: {:.1f}'.format(np.var(X[:, 0])))\n", " ax1.set_xticklabels([])\n", " ax2 = fig.add_subplot(gs[1, 0])\n", " ax2.plot(X[:, 1], color='k')\n", " plt.xlabel('Sample Number')\n", " plt.ylabel('Neuron 2')\n", " plt.title('Sample var 2: {:.1f}'.format(np.var(X[:, 1])))\n", " ax3 = fig.add_subplot(gs[:, 1])\n", " ax3.plot(X[:, 0], X[:, 1], '.', markerfacecolor=[.5, .5, .5],\n", " markeredgewidth=0)\n", " ax3.axis('equal')\n", " plt.xlabel('Neuron 1 activity')\n", " plt.ylabel('Neuron 2 activity')\n", " plt.title('Sample corr: {:.1f}'.format(np.corrcoef(X[:, 0], X[:, 1])[0, 1]))\n", " plt.show()\n", "\n", "\n", "def plot_basis_vectors(X, W):\n", " \"\"\"\n", " Plots bivariate data as well as new basis vectors.\n", "\n", " Args:\n", " X (numpy array of floats) : Data matrix each column corresponds to a\n", " different random variable\n", " W (numpy array of floats) : Square matrix representing new orthonormal\n", " basis each column represents a basis vector\n", "\n", " Returns:\n", " Nothing.\n", " \"\"\"\n", "\n", " plt.figure(figsize=[4, 4])\n", " plt.plot(X[:, 0], X[:, 1], '.', color=[.5, .5, .5], label='Data')\n", " plt.axis('equal')\n", " plt.xlabel('Neuron 1 activity')\n", " plt.ylabel('Neuron 2 activity')\n", " plt.plot([0, W[0, 0]], [0, W[1, 0]], color='r', linewidth=3,\n", " label='Basis vector 1')\n", " plt.plot([0, W[0, 1]], [0, W[1, 1]], color='b', linewidth=3,\n", " label='Basis vector 2')\n", " plt.legend()\n", " plt.show()\n", "\n", "\n", "def plot_data_new_basis(Y):\n", " \"\"\"\n", " Plots bivariate data after transformation to new bases.\n", " Similar to plot_data but with colors corresponding to projections onto\n", " basis 1 (red) and basis 2 (blue). The title indicates the sample correlation\n", " calculated from the data.\n", "\n", " Note that samples are re-sorted in ascending order for the first\n", " random variable.\n", "\n", " Args:\n", " Y (numpy array of floats): Data matrix in new basis each column\n", " corresponds to a different random variable\n", "\n", " Returns:\n", " Nothing.\n", " \"\"\"\n", " fig = plt.figure(figsize=[8, 4])\n", " gs = fig.add_gridspec(2, 2)\n", " ax1 = fig.add_subplot(gs[0, 0])\n", " ax1.plot(Y[:, 0], 'r')\n", " plt.xlabel\n", " plt.ylabel('Projection \\n basis vector 1')\n", " plt.title('Sample var 1: {:.1f}'.format(np.var(Y[:, 0])))\n", " ax1.set_xticklabels([])\n", " ax2 = fig.add_subplot(gs[1, 0])\n", " ax2.plot(Y[:, 1], 'b')\n", " plt.xlabel('Sample number')\n", " plt.ylabel('Projection \\n basis vector 2')\n", " plt.title('Sample var 2: {:.1f}'.format(np.var(Y[:, 1])))\n", " ax3 = fig.add_subplot(gs[:, 1])\n", " ax3.plot(Y[:, 0], Y[:, 1], '.', color=[.5, .5, .5])\n", " ax3.axis('equal')\n", " plt.xlabel('Projection basis vector 1')\n", " plt.ylabel('Projection basis vector 2')\n", " plt.title('Sample corr: {:.1f}'.format(np.corrcoef(Y[:, 0], Y[:, 1])[0, 1]))\n", " plt.show()" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Section 1: Generate correlated multivariate data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Video 2: Multivariate data\n", "from ipywidgets import widgets\n", "\n", "out2 = widgets.Output()\n", "with out2:\n", " from IPython.display import IFrame\n", " class BiliVideo(IFrame):\n", " def __init__(self, id, page=1, width=400, height=300, **kwargs):\n", " self.id=id\n", " src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n", " super(BiliVideo, self).__init__(src, width, height, **kwargs)\n", "\n", " video = BiliVideo(id=\"BV1xz4y1D7ES\", width=854, height=480, fs=1)\n", " print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n", " display(video)\n", "\n", "out1 = widgets.Output()\n", "with out1:\n", " from IPython.display import YouTubeVideo\n", " video = YouTubeVideo(id=\"jcTq2PgU5Vw\", width=854, height=480, fs=1, rel=0)\n", " print('Video available at https://youtube.com/watch?v=' + video.id)\n", " display(video)\n", "\n", "out = widgets.Tab([out1, out2])\n", "out.set_title(0, 'Youtube')\n", "out.set_title(1, 'Bilibili')\n", "\n", "display(out)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "This video describes the covariance matrix and the multivariate normal distribution.\n", "\n", "
\n", " Click here for text recap of video \n", "\n", "To gain intuition, we will first use a simple model to generate multivariate data. Specifically, we will draw random samples from a *bivariate normal distribution*. This is an extension of the one-dimensional normal distribution to two dimensions, in which each $x_i$ is marginally normal with mean $\\mu_i$ and variance $\\sigma_i^2$:\n", "\n", "\\begin{equation}\n", "x_i \\sim \\mathcal{N}(\\mu_i,\\sigma_i^2).\n", "\\end{equation}\n", "\n", "Additionally, the joint distribution for $x_1$ and $x_2$ has a specified correlation coefficient $\\rho$. Recall that the correlation coefficient is a normalized version of the covariance, and ranges between -1 and +1:\n", "\n", "\\begin{equation}\n", "\\rho = \\frac{\\text{cov}(x_1, x_2)}{\\sqrt{\\sigma_1^2 \\sigma_2^2}}.\n", "\\end{equation}\n", "\n", "For simplicity, we will assume that the mean of each variable has already been subtracted, so that $\\mu_i=0$ for both $i=1$ and $i=2$. The remaining parameters can be summarized in the covariance matrix, which for two dimensions has the following form:\n", "\n", "\\begin{equation}\n", "{\\bf \\Sigma} = \n", "\\begin{pmatrix}\n", " \\text{var}(x_1) & \\text{cov}(x_1,x_2) \\\\\n", " \\text{cov}(x_1,x_2) &\\text{var}(x_2)\n", "\\end{pmatrix}.\n", "\\end{equation}\n", "\n", "In general, $\\bf \\Sigma$ is a symmetric matrix with the variances $\\text{var}(x_i) = \\sigma_i^2$ on the diagonal, and the covariances on the off-diagonal. Later, we will see that the covariance matrix plays a key role in PCA.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "## Coding Exercise 1: Draw samples from a distribution\n", "\n", "We have provided code to draw random samples from a zero-mean bivariate normal distribution with a specified covariance matrix (`get_data`). Throughout this tutorial, we'll imagine these samples represent the activity (firing rates) of two recorded neurons on different trials. Fill in the function below to calculate the covariance matrix given the desired variances and correlation coefficient. The covariance can be found by rearranging the equation above:\n", "\n", "\\begin{equation}\n", "\\text{cov}(x_1,x_2) = \\rho \\sqrt{\\sigma_1^2 \\sigma_2^2}.\n", "\\end{equation}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @markdown Execute this cell to get helper function `get_data`\n", "\n", "def get_data(cov_matrix):\n", " \"\"\"\n", " Returns a matrix of 1000 samples from a bivariate, zero-mean Gaussian.\n", "\n", " Note that samples are sorted in ascending order for the first random variable\n", "\n", " Args:\n", " cov_matrix (numpy array of floats): desired covariance matrix\n", "\n", " Returns:\n", " (numpy array of floats) : samples from the bivariate Gaussian, with each\n", " column corresponding to a different random\n", " variable\n", " \"\"\"\n", "\n", " mean = np.array([0, 0])\n", " X = np.random.multivariate_normal(mean, cov_matrix, size=1000)\n", " indices_for_sorting = np.argsort(X[:, 0])\n", " X = X[indices_for_sorting, :]\n", "\n", " return X\n", "\n", "help(get_data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "def calculate_cov_matrix(var_1, var_2, corr_coef):\n", " \"\"\"\n", " Calculates the covariance matrix based on the variances and correlation\n", " coefficient.\n", "\n", " Args:\n", " var_1 (scalar) : variance of the first random variable\n", " var_2 (scalar) : variance of the second random variable\n", " corr_coef (scalar) : correlation coefficient\n", "\n", " Returns:\n", " (numpy array of floats) : covariance matrix\n", " \"\"\"\n", "\n", " #################################################\n", " ## TODO for students: calculate the covariance matrix\n", " # Fill out function and remove\n", " raise NotImplementedError(\"Student exercise: calculate the covariance matrix!\")\n", " #################################################\n", "\n", " # Calculate the covariance from the variances and correlation\n", " cov = ...\n", "\n", " cov_matrix = np.array([[var_1, cov], [cov, var_2]])\n", "\n", " return cov_matrix\n", "\n", "\n", "# Set parameters\n", "np.random.seed(2020) # set random seed\n", "variance_1 = 1\n", "variance_2 = 1\n", "corr_coef = 0.8\n", "\n", "# Compute covariance matrix\n", "cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n", "\n", "# Generate data with this covariance matrix\n", "X = get_data(cov_matrix)\n", "\n", "# Visualize\n", "plot_data(X)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# to_remove solution\n", "\n", "def calculate_cov_matrix(var_1, var_2, corr_coef):\n", " \"\"\"\n", " Calculates the covariance matrix based on the variances and correlation\n", " coefficient.\n", "\n", " Args:\n", " var_1 (scalar) : variance of the first random variable\n", " var_2 (scalar) : variance of the second random variable\n", " corr_coef (scalar) : correlation coefficient\n", "\n", " Returns:\n", " (numpy array of floats) : covariance matrix\n", " \"\"\"\n", "\n", " # Calculate the covariance from the variances and correlation\n", " cov = corr_coef * np.sqrt(var_1 * var_2)\n", "\n", " cov_matrix = np.array([[var_1, cov], [cov, var_2]])\n", "\n", " return cov_matrix\n", "\n", "\n", "# Set parameters\n", "np.random.seed(2020) # set random seed\n", "variance_1 = 1\n", "variance_2 = 1\n", "corr_coef = 0.8\n", "\n", "# Compute covariance matrix\n", "cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n", "\n", "# Generate data with this covariance matrix\n", "X = get_data(cov_matrix)\n", "\n", "# Visualize\n", "with plt.xkcd():\n", " plot_data(X)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "## Interactive Demo 1: Correlation effect on data\n", "\n", "We'll use the function you just completed but now we can change the correlation coefficient via slider. You should get a feel for how changing the correlation coefficient affects the geometry of the simulated data.\n", "\n", "1. What effect do negative correlation coefficient values have?\n", "2. What correlation coefficient results in a circular data cloud?\n", "\n", "\n", "Note that we sort the samples according to neuron 1's firing rate, meaning the plot of neuron 1 firing rate over sample number looks clean and pretty unchanging when compared to neuron 2.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @markdown Execute this cell to enable widget\n", "\n", "def _calculate_cov_matrix(var_1, var_2, corr_coef):\n", "\n", " # Calculate the covariance from the variances and correlation\n", " cov = corr_coef * np.sqrt(var_1 * var_2)\n", "\n", " cov_matrix = np.array([[var_1, cov], [cov, var_2]])\n", "\n", " return cov_matrix\n", "\n", "\n", "@widgets.interact(corr_coef = widgets.FloatSlider(value=.2, min=-1, max=1, step=0.1))\n", "def visualize_correlated_data(corr_coef=0):\n", " variance_1 = 1\n", " variance_2 = 1\n", "\n", " # Compute covariance matrix\n", " cov_matrix = _calculate_cov_matrix(variance_1, variance_2, corr_coef)\n", "\n", " # Generate data with this covariance matrix\n", " X = get_data(cov_matrix)\n", "\n", " # Visualize\n", " plot_data(X)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# to_remove explanation\n", "\"\"\"\n", "1) Negative correlation coefficients reverse the direction of the relationship: now higher neuron 1\n", "activities are associated with lower neuron 2 activities.\n", "\n", "2) A correlation coefficient of 0 (no correlation) results in a circular looking data cloud.\n", "\"\"\";" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Section 2: Define a new orthonormal basis\n", "\n", "*Estimated timing to here from start of tutorial: 20 min*\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Video 3: Orthonormal bases\n", "from ipywidgets import widgets\n", "\n", "out2 = widgets.Output()\n", "with out2:\n", " from IPython.display import IFrame\n", " class BiliVideo(IFrame):\n", " def __init__(self, id, page=1, width=400, height=300, **kwargs):\n", " self.id=id\n", " src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n", " super(BiliVideo, self).__init__(src, width, height, **kwargs)\n", "\n", " video = BiliVideo(id=\"BV1wT4y1E71g\", width=854, height=480, fs=1)\n", " print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n", " display(video)\n", "\n", "out1 = widgets.Output()\n", "with out1:\n", " from IPython.display import YouTubeVideo\n", " video = YouTubeVideo(id=\"PC1RZELnrIg\", width=854, height=480, fs=1, rel=0)\n", " print('Video available at https://youtube.com/watch?v=' + video.id)\n", " display(video)\n", "\n", "out = widgets.Tab([out1, out2])\n", "out.set_title(0, 'Youtube')\n", "out.set_title(1, 'Bilibili')\n", "\n", "display(out)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "This video shows that data can be represented in many ways using different bases. It also explains how to check if your favorite basis is orthonormal.\n", "\n", "
\n", " Click here for text recap of video \n", "\n", "Next, we will define a new orthonormal basis of vectors ${\\bf u} = [u_1,u_2]$ and ${\\bf w} = [w_1,w_2]$. As we learned in the video, two vectors are orthonormal if: \n", "\n", "1. They are orthogonal (i.e., their dot product is zero):\n", "\n", "\\begin{equation}\n", "{\\bf u\\cdot w} = u_1 w_1 + u_2 w_2 = 0\n", "\\end{equation}\n", "\n", "2. They have unit length:\n", "\n", "\\begin{equation}\n", "||{\\bf u}|| = ||{\\bf w} || = 1\n", "\\end{equation}\n", "\n", "
\n", "\n", "In two dimensions, it is easy to make an arbitrary orthonormal basis. All we need is a random vector ${\\bf u}$, which we have normalized. If we now define the second basis vector to be ${\\bf w} = [-u_2,u_1]$, we can check that both conditions are satisfied: \n", "\n", "\\begin{equation}\n", "{\\bf u\\cdot w} = - u_1 u_2 + u_2 u_1 = 0\n", "\\end{equation}\n", "\n", "and \n", "\n", "\\begin{equation}\n", "{|| {\\bf w} ||} = \\sqrt{(-u_2)^2 + u_1^2} = \\sqrt{u_1^2 + u_2^2} = 1,\n", "\\end{equation}\n", "\n", "where we used the fact that ${\\bf u}$ is normalized. So, with an arbitrary input vector, we can define an orthonormal basis, which we will write in matrix by stacking the basis vectors horizontally:\n", "\n", "\\begin{equation}\n", "{{\\bf W} } =\n", "\\begin{pmatrix}\n", " u_1 & w_1 \\\\\n", " u_2 & w_2\n", "\\end{pmatrix}.\n", "\\end{equation}" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "## Coding Exercise 2: Find an orthonormal basis\n", "\n", "In this exercise you will fill in the function below to define an orthonormal basis, given a single arbitrary 2-dimensional vector as an input.\n", "\n", "**Steps**\n", "* Modify the function `define_orthonormal_basis` to first normalize the first basis vector $\\bf u$.\n", "* Then complete the function by finding a basis vector $\\bf w$ that is orthogonal to $\\bf u$.\n", "* Test the function using initial basis vector ${\\bf u} = [3,1]$. Plot the resulting basis vectors on top of the data scatter plot using the function `plot_basis_vectors`. (For the data, use $\\sigma_1^2 =1$, $\\sigma_2^2 =1$, and $\\rho = .8$)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "def define_orthonormal_basis(u):\n", " \"\"\"\n", " Calculates an orthonormal basis given an arbitrary vector u.\n", "\n", " Args:\n", " u (numpy array of floats) : arbitrary 2-dimensional vector used for new\n", " basis\n", "\n", " Returns:\n", " (numpy array of floats) : new orthonormal basis\n", " columns correspond to basis vectors\n", " \"\"\"\n", "\n", " #################################################\n", " ## TODO for students: calculate the orthonormal basis\n", " # Fill out function and remove\n", " raise NotImplementedError(\"Student exercise: implement the orthonormal basis function\")\n", " #################################################\n", "\n", " # Normalize vector u\n", " u = ...\n", "\n", " # Calculate vector w that is orthogonal to w\n", " w = ...\n", "\n", " # Put in matrix form\n", " W = np.column_stack([u, w])\n", "\n", " return W\n", "\n", "\n", "# Set up parameters\n", "np.random.seed(2020) # set random seed\n", "variance_1 = 1\n", "variance_2 = 1\n", "corr_coef = 0.8\n", "u = np.array([3, 1])\n", "\n", "# Compute covariance matrix\n", "cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n", "\n", "# Generate data\n", "X = get_data(cov_matrix)\n", "\n", "# Get orthonomal basis\n", "W = define_orthonormal_basis(u)\n", "\n", "# Visualize\n", "plot_basis_vectors(X, W)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# to_remove solution\n", "\n", "def define_orthonormal_basis(u):\n", " \"\"\"\n", " Calculates an orthonormal basis given an arbitrary vector u.\n", "\n", " Args:\n", " u (numpy array of floats) : arbitrary 2-dimensional vector used for new\n", " basis\n", "\n", " Returns:\n", " (numpy array of floats) : new orthonormal basis\n", " columns correspond to basis vectors\n", " \"\"\"\n", "\n", " # Normalize vector u\n", " u = u / np.sqrt(u[0] ** 2 + u[1] ** 2)\n", "\n", " # Calculate vector w that is orthogonal to w\n", " w = np.array([-u[1], u[0]])\n", "\n", " # Put in matrix form\n", " W = np.column_stack([u, w])\n", "\n", " return W\n", "\n", "\n", "# Set up parameters\n", "np.random.seed(2020) # set random seed\n", "variance_1 = 1\n", "variance_2 = 1\n", "corr_coef = 0.8\n", "u = np.array([3, 1])\n", "\n", "# Compute covariance matrix\n", "cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n", "\n", "# Generate data\n", "X = get_data(cov_matrix)\n", "\n", "# Get orthonomal basis\n", "W = define_orthonormal_basis(u)\n", "\n", "# Visualize\n", "with plt.xkcd():\n", " plot_basis_vectors(X, W)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Section 3: Project data onto new basis\n", "\n", "*Estimated timing to here from start of tutorial: 35 min*" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @title Video 4: Change of basis\n", "from ipywidgets import widgets\n", "\n", "out2 = widgets.Output()\n", "with out2:\n", " from IPython.display import IFrame\n", " class BiliVideo(IFrame):\n", " def __init__(self, id, page=1, width=400, height=300, **kwargs):\n", " self.id=id\n", " src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)\n", " super(BiliVideo, self).__init__(src, width, height, **kwargs)\n", "\n", " video = BiliVideo(id=\"BV1LK411J7NQ\", width=854, height=480, fs=1)\n", " print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))\n", " display(video)\n", "\n", "out1 = widgets.Output()\n", "with out1:\n", " from IPython.display import YouTubeVideo\n", " video = YouTubeVideo(id=\"Mj6BRQPKKUc\", width=854, height=480, fs=1, rel=0)\n", " print('Video available at https://youtube.com/watch?v=' + video.id)\n", " display(video)\n", "\n", "out = widgets.Tab([out1, out2])\n", "out.set_title(0, 'Youtube')\n", "out.set_title(1, 'Bilibili')\n", "\n", "display(out)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "Finally, we will express our data in the new basis that we have just found. Since $\\bf W$ is orthonormal, we can project the data into our new basis using simple matrix multiplication :\n", "\n", "\\begin{equation}\n", "{\\bf Y = X W}.\n", "\\end{equation}\n", "\n", "We will explore the geometry of the transformed data $\\bf Y$ as we vary the choice of basis." ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "## Coding Exercise 3: Change to orthonormal basis\n", "In this exercise you will fill in the function below to change data to an orthonormal basis.\n", "\n", "**Steps**\n", "* Complete the function `change_of_basis` to project the data onto the new basis.\n", "* Plot the projected data using the function `plot_data_new_basis`. \n", "* What happens to the correlation coefficient in the new basis? Does it increase or decrease? \n", "* What happens to variance? \n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "def change_of_basis(X, W):\n", " \"\"\"\n", " Projects data onto new basis W.\n", "\n", " Args:\n", " X (numpy array of floats) : Data matrix each column corresponding to a\n", " different random variable\n", " W (numpy array of floats) : new orthonormal basis columns correspond to\n", " basis vectors\n", "\n", " Returns:\n", " (numpy array of floats) : Data matrix expressed in new basis\n", " \"\"\"\n", "\n", " #################################################\n", " ## TODO for students: project the data onto a new basis W\n", " # Fill out function and remove\n", " raise NotImplementedError(\"Student exercise: implement change of basis\")\n", " #################################################\n", "\n", " # Project data onto new basis described by W\n", " Y = ...\n", "\n", " return Y\n", "\n", "\n", "# Project data to new basis\n", "Y = change_of_basis(X, W)\n", "\n", "# Visualize\n", "plot_data_new_basis(Y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# to_remove solution\n", "\n", "def change_of_basis(X, W):\n", " \"\"\"\n", " Projects data onto new basis W.\n", "\n", " Args:\n", " X (numpy array of floats) : Data matrix each column corresponding to a\n", " different random variable\n", " W (numpy array of floats) : new orthonormal basis columns correspond to\n", " basis vectors\n", "\n", " Returns:\n", " (numpy array of floats) : Data matrix expressed in new basis\n", " \"\"\"\n", "\n", " # Project data onto new basis described by W\n", " Y = X @ W\n", "\n", " return Y\n", "\n", "\n", "# Project data to new basis\n", "Y = change_of_basis(X, W)\n", "\n", "# Visualize\n", "with plt.xkcd():\n", " plot_data_new_basis(Y)" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "## Interactive Demo 3: Play with the basis vectors\n", "To see what happens to the correlation as we change the basis vectors, run the cell below. The parameter $\\theta$ controls the angle of $\\bf u$ in degrees. Use the slider to rotate the basis vectors. \n", "\n", "\n", "\n", "1. What happens to the projected data as you rotate the basis? \n", "2. How does the correlation coefficient change? How does the variance of the projection onto each basis vector change?\n", "3. Are you able to find a basis in which the projected data is **uncorrelated**?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "execution": {} }, "outputs": [], "source": [ "# @markdown Make sure you execute this cell to enable the widget!\n", "\n", "def refresh(theta=0):\n", " u = np.array([1, np.tan(theta * np.pi / 180)])\n", " W = define_orthonormal_basis(u)\n", " Y = change_of_basis(X, W)\n", " plot_basis_vectors(X, W)\n", " plot_data_new_basis(Y)\n", "\n", "\n", "_ = widgets.interact(refresh, theta=(0, 90, 5))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": {} }, "outputs": [], "source": [ "# to_remove explanation\n", "\"\"\"\n", "1) As you rotate the basis vectors, the look of the cloud of projected data changes.\n", "Specifically, the correlations and variances of the projected data change.\n", "\n", "2) As the angle increases, the correlation coefficient decreases, goes to 0, then starts\n", "to become negative. It changes from 0.8 to -.8 when the angle is changed by 90 degrees.\n", "\n", "With theta of 0, the data projected onto the two basis vectors has equal variances of 1.\n", "As theta increases, these variances become unequal: the projected data has larger and larger variance\n", "for basis vector 1 and smaller variance for basis vector 2. Past theta of 45, the trend reverses and\n", "the variances start becoming more similar.\n", "\n", "3) If theta is 45 degrees, the projected data is uncorrelated.\n", "\"\"\";" ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Summary\n", "\n", "*Estimated timing of tutorial: 50 minutes*\n", "\n", "- In this tutorial, we learned that multivariate data can be visualized as a cloud of points in a high-dimensional vector space. The geometry of this cloud is shaped by the covariance matrix.\n", "\n", "- Multivariate data can be represented in a new orthonormal basis using the dot product. These new basis vectors correspond to specific mixtures of the original variables - for example, in neuroscience, they could represent different ratios of activation across a population of neurons.\n", "\n", "- The projected data (after transforming into the new basis) will generally have a different geometry from the original data. In particular, taking basis vectors that are aligned with the spread of cloud of points decorrelates the data.\n", "\n", "* These concepts - covariance, projections, and orthonormal bases - are key for understanding PCA, which will be our focus in the next tutorial." ] }, { "cell_type": "markdown", "metadata": { "execution": {} }, "source": [ "---\n", "# Notation\n", "\n", "\\begin{align}\n", "x_i &\\quad \\text{data point for dimension } i\\\\\n", "\\mu_i &\\quad \\text{mean along dimension } i\\\\\n", "\\sigma_i^2 &\\quad \\text{variance along dimension } i \\\\\n", "\\bf u, \\bf w &\\quad \\text{orthonormal basis vectors}\\\\\n", "\\rho &\\quad \\text{correlation coefficient}\\\\\n", "\\bf \\Sigma &\\quad \\text{covariance matrix}\\\\\n", "\\bf X &\\quad \\text{original data matrix}\\\\\n", "\\bf W &\\quad \\text{projection matrix}\\\\\n", "\\bf Y &\\quad \\text{transformed data}\\\\\n", "\\end{align}" ] } ], "metadata": { "colab": { "collapsed_sections": [], "include_colab_link": true, "name": "W1D4_Tutorial1", "provenance": [], "toc_visible": true }, "kernel": { "display_name": "Python 3", "language": "python", "name": "python3" }, "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.13" } }, "nbformat": 4, "nbformat_minor": 0 }