" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recap of linear regression\n", "To refresh your memory on linear regression, we'll walk you through a recap of the technique's most important concepts.\n", "We are going to work through a simple example. \n", "\n", "In the code below, `y` will denote our *dependent variable* (the variable we try to model/explain) and `X` will denote our *independent variable(s)* (the variables we're using to try to explain `y`). Throughout the entire tutorial will use `X` to refer to our matrix of independent variables (also called \"predictors\" or \"regressors\", or simply \"design matrix\") and use `y` to refer to our dependent variable (also sometimes called \"target\").\n", "\n", "Moreover, the independent variables are often grouped in a single matrix (a 2D array) — which is sometimes called the \"design matrix\" (because it 'designs' the way we want to model our dependent variable). As stated before, in this tutorial we store our design matrix - the set of our independent variables - in the variable `X` (or slight variations on that, like `X_new` or something). Importantly, it is often assumed (e.g. by statistics functions/software) that the design matrix takes the shape of $N\\ \\mathrm{(observations)} \\times P\\ \\mathrm{(predictors)}$. So, the rows refer to the sampled observations (also often called \"samples\", \"instances\", or simply \"data points\"). The columns refer to the separate independent variables that we use to model the dependent variable. For the dependent variable, it is often assumed that this is a single row-vector of shape $N \\times 1$.\n", "\n", "### Notation\n", "Next, let's define some more conventions in notation. We will denote the total number of observations with **$N$**. Moreover, we'll denote **$i$** as the index of samples. To give an example, the formula below gives you the sum of our target variable:\n", "\n", "\\begin{align}\n", "\\mathrm{sum}(\\mathbf{y}) = \\sum_{i=1}^{N} y_{i} \n", "\\end{align}\n", "\n", "Lastly, we denote the total number of predictors **$P$** and **$j$** as the index of our predictors. So, for example, if we wanted to sum over our predictors for a given sample **$i$**, we'd write: \n", "\n", "\\begin{align}\n", "\\mathrm{sum}(\\mathbf{X}_{i}) = \\sum_{j=1}^{P} \\mathbf{X}_{ij} \n", "\\end{align}\n", "\n", "To practice with this notation, let's do a ToDo!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# First some imports\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n",
" **ToDo** (1 point): From the variable `arr` below (an array of shape $100 \\times 25$), calculate the mean over all samples ($N$) for the predictor at index $j = 4$ (i.e., the fourth predictor). Store the result in a variable named `mean_predictor_4`.\n",
"\n",
"Remember: Python has 0-based indexing!\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "e6e8219b9f1a5308ac940727da7319ff",
"grade": false,
"grade_id": "cell-45f6664c7adfb7ab",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"\"\"\" Implement the ToDo below. \"\"\"\n",
"\n",
"np.random.seed(42)\n",
"arr = np.random.normal(0, 1, size=(100, 25))\n",
"# Implement your ToDo here\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "0cbf99cb0c38fd738493e99a70f7cbaf",
"grade": true,
"grade_id": "cell-3677a8cfce19363f",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_mean_predictor_4\n",
"test_mean_predictor_4(mean_predictor_4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's look at an example. Throughout the example below, we will gradually explain the components of linear regression. For the example, we will use randomly generated data to create a dependent variable with 30 observations (\"samples\"; $N = 30$) and a single independent variable ($P = 1$) with, of course, also 30 observations. So both the independent and dependent variable are of shape $30 \\times 1$. Alright, let's get started!\n",
"\n",
"For our example let's create some randomly generated data. As discussed, we'll create two variables (of shape $30\\times 1$), which have a prespecified correlation of 0.8 (normally, you don't know this before doing the analysis of course, but we specify it here for the sake of the example). \n",
"\n",
"We'll denote our independent variable `X` and our dependent variable `y`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.random.seed(1)\n",
"\n",
"prespecified_covariance = np.array([[1, .8],\n",
" [.8, 1]])\n",
"\n",
"data = np.random.multivariate_normal(mean=[3, 7], cov=prespecified_covariance, size=30)\n",
"\n",
"\"\"\" By default, when you slice out a single column (or row), numpy returns\n",
"an array of shape (some_number,) instead of (some_number, 1). However, for our\n",
"examples, we often actually want shape (some_number, 1) so essentially we want to \n",
"\"add\" an extra axis. This is done by the np.newaxis command. Mess around with\n",
"it yourself to see how it works! \"\"\"\n",
"\n",
"X = data[:, 0, np.newaxis] # Here, we slice the first column (0) and immediately add a new axis!\n",
"y = data[:, 1, np.newaxis] # same here\n",
"\n",
"print('The shape of X is: %s' % (X.shape,))\n",
"print('The shape of y is: %s' % (y.shape,))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Modeling the intercept (offset)\n",
"As you probably were told in your previous statistics classes, you should always \"model the intercept\" when running any (regression) model. Technically, the intercept models some of the signal using a constant term. The parameter corresponding to the intercept (as calculated by the linear regression model), then, refers to *the average value of your $y$ variable when all predictors in $X$ are 0*. So, conceptually, the intercept models the mean when of the dependent variable when controlling for our (other) predictors.\n",
"\n",
"To \"model the intercept\", you should add an extra \"constant predictor\" to your design matrix (`X`). This \"constant predictor\" means simply an array of shape $N \\times 1$ with a constant value, usually all ones. (You'll figure out *why* you should do this later in the tutorial.)\n",
"\n",
"Remember from week 1 how to create an array with ones? We can just use `np.ones(shape_of_desired_array)`!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n_obs = y.size\n",
"intercept = np.ones((n_obs, 1)) # creates intercept of shape (N, 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we want to add it to our design matrix (`X`). We can do this using the numpy function `np.hstack` (which is short for \"horizontal stack\", i.e. \"stacking columns horizontally\"). This function takes a tuple with arrays which show have the same amount of rows (for our data: both have 30 rows) and returns the a new array in which the arrays from the tuple are stacked (stacked shape should be $30 \\times 2$):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tuple_with_arrays = (intercept, X)\n",
"X_with_icept = np.hstack(tuple_with_arrays)\n",
"\n",
"# Note: you could also simply do ...\n",
"# X_with_icept = np.hstack((np.ones((y.size, 1)), X))\n",
"# ... but arguably this is less 'readable' than the implementation above\n",
"print(\"Shape of X is now: %s\" % (X_with_icept.shape,))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a look at the X matrix (\"design matrix\") we have now. As you'll see, we have two columns: the first one is our intercept-predictor, and the second one is our 'regular' predictor."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(X_with_icept)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's take a look at the data. We'll create a scatter-plot for this (we'll leave out the intercept):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(10, 10))\n",
"plt.scatter(X_with_icept[:, 1], y)\n",
"plt.xlabel('X', fontsize=25)\n",
"plt.ylabel('y', fontsize=25)\n",
"plt.xlim((0, 5))\n",
"plt.ylim((0, 10))\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Parameters in linear regression\n",
"As you can see, there seems to be some positive linear relationship between $X$ (just the independent variable without the intercept) and $y$. In other words, an increase in $X$ will lead to an increase in $y$. But, at this moment, *how much exactly* $y$ changes for a increase in $X$ is unknown. By doing a linear regression with $X$ as our predictor of $y$, we can quantify this! \n",
"\n",
"The parameter, i.e. the \"thing\" that quantifies the influence of $X$ on $y$, calculated by this model is often called the **beta-parameter(s)** (but sometimes they're denoted as theta, or any other greek symbol/letter). The beta-parameter quantifies exactly how much $y$ changes if you increase $X$ by 1. Or, in other words, it quantifies how much influence $X$ has on $y$. In a formula ($\\delta$ stands for \"change in\")\\*: \n",
"\n",
"\\begin{align}\n",
"\\beta_{j} = \\frac{\\delta y}{\\delta X_{j}} \n",
"\\end{align}\n",
"\n",
"As you probably realize, each predictor in $X$ (i.e., $X_{j}$) has a parameter ($\\beta_{j}$) that quantifies how much influence that predictor has on our target variable ($y$). This includes the intercept, our vector of ones (which is in textbooks often denoted by $\\beta_{0}$; they often don't write out $\\beta_{0}X_{0}$ because, if a vector of ones is used, $\\beta_{0}\\cdot 1$ simplifies to $\\beta_{0}$).\n",
"\n",
"Thus, linear regression describes a model in which a set of beta-parameters are calculated to characterize the influence of each predictor in $X$ on $y$, that together explain $y$ as well as possible (but the model is usually not perfect, so there will be some *error*, or \"unexplained variance\", denoted by $\\epsilon$). As such, we can formulate the linear regression model as follows:\n",
"\n",
"\\begin{align}\n",
"y = \\beta_{0} + X_{1}\\beta_{1} + X_{2}\\beta_{2} ... + X_{P}\\beta_{P} + \\epsilon\n",
"\\end{align}\n",
"\n",
"which is often written out as (and is equivalent to the formula above):\n",
"\n",
"\\begin{align}\n",
"y = \\sum_{j=1}^{P}X_{j}\\beta_{j} + \\epsilon\n",
"\\end{align}\n",
"\n",
"Here, $\\epsilon$ is the variance of $y$ that cannot be explained by our predictors (i.e, the *error*). "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But how does linear regression estimate the beta-parameters? The method most often used is called **'ordinary least squares'** (OLS; or just 'least squares'). This method tries to find a \"weight(s)\" for the independent variable(s) such that when you multiply the weight(s) with the independent variable(s), it produces an estimate of $y$ (often denoted as $\\hat{y}$, or \"y-hat\") that is as 'close' to the true $y$ as possible. In other words, least squares tries to 'choose' the beta-parameter(s) ($\\hat{\\beta}$) such that the difference between $X$ multiplied with the beta(s) (i.e. our best guess of $y$, denoted as $\\hat{y}$) and the true $y$ is minimized\\*. \n",
"\n",
"Let's just formalize this formula for the 'best estimate of $y$' (i.e. $\\hat{y}$):\n",
"\n",
"\\begin{align}\n",
"\\hat{y}_{i} = \\sum_{j=1}^{P}X_{ij}\\hat{\\beta}_{j} \n",
"\\end{align}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before we're going into the estimation of these beta-parameters, let's practice with calculating $\\hat{y}$!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (1 point): Below, we've defined a design matrix with two predictors (`this_X`) and an array with beta-estimates (`these_betas`; just pretend that these betas were estimated by us beforehand). Now, given this data, can you calculate the predicted $y$-values (i.e., $\\hat{y}$)? Store these predicted $y$-values in an array named `this_y_hat`.\n",
"\n",
"Hint: your `this_y_hat` array should be of shape `(100,)`.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "0884febedb80f4b41cbb9951de0e0a74",
"grade": false,
"grade_id": "cell-2198797049cfec1b",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Just generate some random normal data with mean 0, std 1, and shape 100x2 (NxP)\n",
"this_X = np.random.normal(0, 1, (100, 2))\n",
"these_betas = np.array([5, 3])\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "b4fe6a29bce46a5c1de629a10da5aeb8",
"grade": true,
"grade_id": "cell-ec4e8c1e74771f3d",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo'''\n",
"from niedu.tests.nii.week_2 import test_X_times_betas\n",
"test_X_times_betas(this_X, these_betas, this_y_hat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Refresher: matrix multiplication\n",
"In the GLM (and statistics in general), you'll very likely come across concepts and operations from linear (matrix) algebra, such as matrix multiplication and the matrix inverse. In week 1, we briefly discussed how matrix/vector multiplication can be done with Python/numpy: using the `.dot` numpy attribute or with the `@` operator. In this course, you'll encounter several matrix operations as part of the GLM. In fact, we can implement the operation from the previous ToDo (calculating $\\hat{y}$) using matrix multiplication as well.\n",
"\n",
"See the figure below for a visual explanation of matrix multiplication:\n",
"![dot_prod](https://hadrienj.github.io/assets/images/2.2/dot-product.png)\n",
"*Image by Hadrien Jean ([link](https://hadrienj.github.io/assets/images/2.2/dot-product.png))*\n",
"\n",
"If your understanding of matrix algebra, and especially matrix multiplication, is still somewhat rusty, check out [this video](https://www.youtube.com/watch?v=fkZj8QoYjq8) by Jeanette Mumford. Now, suppose that the left matrix in the above figure represents our matrix $\\mathbf{X}$ and that the right vector represents our estimated parameters $\\hat{\\beta}$. Now, we can calculate $\\hat{y}$ as the matrix operator $X\\hat{\\beta}$:\n",
"\n",
"\\begin{align}\n",
"\\hat{y} = \n",
" \\begin{bmatrix}\n",
" X_{1,1} & X_{1,2} \\\\\n",
" X_{2, 1} & X_{2, 2} \\\\\n",
" \\vdots & \\vdots \\\\\n",
" X_{N, 1} & X_{N, 2}\n",
" \\end{bmatrix} \n",
" \\begin{bmatrix}\n",
" \\hat{\\beta}_{1} \\\\\n",
" \\hat{\\beta}_{2}\n",
" \\end{bmatrix}\n",
"\\end{align}\n",
"\n",
"Let's check this in code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"this_y_hat_dot = this_X @ these_betas # this_X.dot(these_betas) is also correct\n",
"print(this_y_hat_dot)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In other words, the non-matrix algebra notation ...\n",
"\n",
"\\begin{align}\n",
"\\hat{y}_{i} = \\sum_{j=1}^{P}X_{ij}\\hat{\\beta}_{j} \n",
"\\end{align}\n",
"\n",
"... is exactly the same as the the following matrix algebra notation:\n",
"\n",
"\\begin{align}\n",
"\\hat{y}_{i} = \\mathbf{X}_{i}\\mathbf{\\hat{\\beta}} \n",
"\\end{align}\n",
"\n",
"You can usually recognize the implementations in formulas using algebra by the use of bold variables (such as $\\mathbf{X}$, which denote matrices) here above.\n",
"\n",
"*You will calculate `y_hat` quite a lot throughout this lab; please use the matrix algebra method to calculate `y_hat`, because this will likely prevent errors in the future!* So, use this ...\n",
"\n",
"```python\n",
"y_hat = X @ betas\n",
"```\n",
"\n",
"instead of ...\n",
"\n",
"```python\n",
"y_hat = X[:, 0] * betas[0] + X[:, 1] * betas[1]\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fitting OLS models\n",
"Thus far, we've ignored how OLS actually calculates (or \"fits\") the unknown parameters $\\beta$. Roughly speaking, OLS finds parameters that minimize the *sum of squared errors* (hence the name '[ordinary] least squares'!):\n",
"\n",
"\\begin{align}\n",
"\\min_{\\beta} \\sum_{i=1}^{N}(y_{i} - X_{i}\\hat{\\beta})^2 \n",
"\\end{align}\n",
"\n",
"This formula basically formalizes the approach of OLS \"find the beta(s) that minimize the difference of my prediction of $y$ (calculated as $X \\cdot \\beta$) and the true $y$\". Now, this still begs the question, *how does OLS estimate these parameters?* It turns out there is an \"analytical solution\" to this problem, i.e., there is a way to compute beta estimates that are guaranteed (given some assumptions) to give the parameters that minimize the summed squared error. This solution involves a little matrix algebra and is usually formulated as a series of matrix operations:\n",
"\n",
"\\begin{align}\n",
"\\hat{\\beta} = (\\mathbf{X}^{T}\\mathbf{X})^{-1}\\mathbf{X}^{T}y\n",
"\\end{align}\n",
"\n",
"(For the mathematically inclined, see [this](https://economictheoryblog.com/2015/02/19/ols_estimator/) or [this](https://socialstatisticsfun.wordpress.com/2012/12/18/deriving-the-ols-estimator-continued/) blog for the derivation of the OLS solution.) In this formula, $\\mathbf{X}^{T}$ refers to the transpose of the design matrix $\\mathbf{X}$.\n",
"\n",
"We don't expect you to understand every aspect of this formula, but you should understand the objective of least squares (minimizing the difference between $\\hat{y}$ and true $y$) and what role the beta-parameters play in this process (i.e. a kind of weighting factor of the predictors).\n",
"\n",
"Let's look at how we'd implement the OLS solution in code. We'll use the `@` operator for matrix multiplication and the `inv` function from the `numpy.linalg` module for the matrix inversion (i.e., the $(X^{T}X)^{-1}$ part)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from numpy.linalg import inv\n",
"\n",
"est_betas = inv(X_with_icept.T @ X_with_icept) @ X_with_icept.T @ y\n",
"\n",
"print(\"Shape of estimated betas: %s\" % (est_betas.shape,))\n",
"print(est_betas)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\"What? Why are there two beta-parameters?\", you might think. This is of course because you also use the intercept as a predictor, which also has an associated beta-value (weighting factor). Here, the first beta refers to the intercept of the model (because it's the first column in the design-matrix)! The second beta refers to our 'original' predictor. Thus, the model found by least squares for our generated data is (i.e. that leads to our best estimate of $y$, i.e. $\\hat{y}$:\n",
"\n",
"\\begin{align}\n",
"\\hat{y} = X_{1} \\cdot 4.259 + X_{2} \\cdot 0.882 \n",
"\\end{align}\n",
"\n",
"And since our intercept (here $X_{1}$) is a vector of ones, the formula simplifies to:\n",
"\n",
"\\begin{align}\n",
"\\hat{y} = 4.259 + X_{2} \\cdot 0.882\n",
"\\end{align}\n",
"\n",
"Now, let's calculate our predicted value of $y$ ($\\hat{y}$) by implementing the above formula by multiplying our betas with the corresponding predictors (intercept and original predictor). Here, because we have two predictors, we simply add the two \"`predictor * beta`\" terms to get the final $\\hat{y}$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"y_hat = X_with_icept[:, 0] * est_betas[0] + X_with_icept[:, 1] * est_betas[1]\n",
"print('The predicted y-values are: \\n\\n%r' % y_hat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's plot the predicted $y$ values ($\\hat{y}$) against the true $y$ values ($y$)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(10, 10))\n",
"plt.scatter(X, y)\n",
"plt.xlabel('X', fontsize=25)\n",
"plt.ylabel('y', fontsize=25)\n",
"x_lim = (0, 5)\n",
"plt.xlim(x_lim)\n",
"plt.ylim((0, 10))\n",
"y_hat = X_with_icept @ est_betas # using the matrix algebra approach!\n",
"plt.scatter(X, y_hat, c='tab:orange')\n",
"plt.legend(['True y', 'Predicted y'])\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Actually, let's just plot the predicted y-values as a line (effectively interpolating between adjacent predictions) - this gives us the linear regression plot as you've probably seen many times in your statistics classes!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(10, 10))\n",
"plt.scatter(X, y)\n",
"plt.xlabel('X', fontsize=25)\n",
"plt.ylabel('y', fontsize=25)\n",
"plt.xlim(x_lim)\n",
"plt.ylim((0, 10))\n",
"y_min_pred = est_betas[0] + est_betas[1] * x_lim[0]\n",
"y_max_pred = est_betas[0] + est_betas[1] * x_lim[1]\n",
"plt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='tab:orange', lw=3)\n",
"plt.legend(['Predicted y', 'True y'])\n",
"plt.title('Linear regression of X onto y')\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Residuals and model fit\n",
"Alright, so now we have established the beta-values that lead to the best prediction of $y$ - in other words, the best fit of our model. But how do we quantify the fit of our model? One way is to look at the difference between $\\hat{y}$ and y, which is often referred to as the model's **residuals**. This difference between $\\hat{y}$ and $y$ - the residuals - is the exact same thing as the $\\epsilon$ in the linear regression model, i.e. the **error** of the model. Thus, for a particular dependent variable $y$, the residuals ($\\epsilon$) of a particular fitted model with parameters $\\hat{\\beta}$ are computed as: \n",
"\n",
"\\begin{align}\n",
"\\epsilon = y - \\mathbf{X}\\hat{\\beta} \n",
"\\end{align}\n",
"\n",
"To visualize the residuals (plotted as red dashed lines):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(10, 10))\n",
"plt.scatter(X, y)\n",
"plt.xlabel('X')\n",
"plt.ylabel('y')\n",
"plt.xlim(x_lim)\n",
"plt.ylim((0, 10))\n",
"y_min_pred = est_betas[0] + est_betas[1] * x_lim[0]\n",
"y_max_pred = est_betas[0] + est_betas[1] * x_lim[1]\n",
"plt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='orange', lw=3)\n",
"plt.title('Linear regression of X onto y')\n",
"\n",
"for i in range(y.size):\n",
" plt.plot((X[i], X[i]), (y_hat[i], y[i]), linestyle='--', c='red', lw=2)\n",
"\n",
"\n",
"from matplotlib.lines import Line2D\n",
"custom_lines = [\n",
" Line2D([0], [0], color='tab:blue', marker='o', ls='None', lw=2),\n",
" Line2D([0], [0], color='tab:orange', lw=2),\n",
" Line2D([0], [0], color='r', ls='--', lw=2)\n",
"]\n",
"\n",
"plt.legend(custom_lines, ['True y', 'Predicted y', 'Residuals'])\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In fact, the model fit is often summarized as the **mean of the squared residuals** (also called the 'mean squared error' or MSE), which is thus simply the (length of the) red lines squared and averaged. In other words, the MSE refers to the average squared difference between our predicted $y$ and the true $y$\\*:\n",
"\n",
"\\begin{align}\n",
"\\mathrm{MSE} = \\frac{1}{N}\\sum_{i=1}^{N} (y_{i} - \\hat{y}_{i})^2\n",
"\\end{align}\n",
"\n",
"\\* The \"$\\frac{1}{N}\\sum_{i=1}^{N}$\" is just a different (but equally correct) way of writing \"the average of all residuals from sample 1 to sample N\"."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (1 point): Calculate the MSE for our previous model predictions (`y_hat`) based on our linear regression model predicting `y` from `X_with_intercept`. *Do not use a for-loop for this.* You know how to do this without a loop, using vectorized numpy array operations. Store the result in a variable named `mse`.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "67977f56a02dbe3af7aff2d32eaf8952",
"grade": false,
"grade_id": "cell-534d470bbac52f30",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Implement your ToDo here\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "60ce231eb028faba829111b152d6e077",
"grade": true,
"grade_id": "cell-455ec59f2dc6ecba",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_mse_calculation\n",
"test_mse_calculation(mse, y, y_hat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another metric for model fit in linear regression is \"R-squared\" ($R²$). R-squared is calculated as follows:\n",
"\n",
"\\begin{align}\n",
"R^2 = 1 - \\frac{\\sum_{i=1}^{N}(y_{i} - \\hat{y}_{i})^2}{\\sum_{i=1}^{N}(y_{i} - \\bar{y})^2}\n",
"\\end{align}\n",
"\n",
"where $\\bar{y}$ represents the mean of $y$. As you can see, the formula for R-squared consists of two parts: the numerator ($\\sum_{i=1}^{N}(y_{i} - \\hat{y}_{i})^2$) and the denominator ($\\sum_{i=1}^{N}(y_{i} - \\bar{y}_{i})^2$). The denominator represents the *total* amount of squared error of the actual values ($y$) relative to the mean ($\\bar{y}$). The numerator represents the *reduced* squared errors when incorporating knowledge from our (weighted) independent variables ($X_{i}\\hat{\\beta}$). So, in a way you can interpret R-squared as *how much better my model is including `X` versus a model that only uses the mean*. Another conventional interpretation of R-squared is the proportion of variance our predictors ($X$) together can explain of our target ($y$).\n",
"\n",
"As expected, the code is quite straightforward:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"numerator = np.sum((y - y_hat) ** 2) # remember, y_hat equals X * beta\n",
"denominator = np.sum((y - np.mean(y)) ** 2)\n",
"r_squared = 1 - numerator / denominator\n",
"\n",
"print('The R² value is: %.3f' % r_squared)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (1 point): Below, we've defined a design matrix (`X_test`, including an intercept) and a dependent variable (`y_test`). Run a linear regression model and calculate R-squared. Store the R-squared value (which should be a single number, a float) in a variable named `r_squared_test`.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "334e09868e02324cdf74732c2fa4cdfd",
"grade": false,
"grade_id": "cell-bf0783eac54257c5",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"data_tmp = np.load('data_todo_rsquared.npz')\n",
"X_test, y_test = data_tmp['X'], data_tmp['y']\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "677c507187d828d382c6e44deab96e23",
"grade": true,
"grade_id": "cell-87d0abded46476f5",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo '''\n",
"from niedu.tests.nii.week_2 import test_rsquared_todo\n",
"test_rsquared_todo(X_test, y_test, r_squared_test) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToThink** (1 point): As discussed earlier, it's important to model the intercept in regression models. This is because it often greatly *improves model fit*! In this ToThink, you have to explain *why* modelling the intercept (usually) improves model fit. \n",
"\n",
"To give you some clues, we re-did the linear regression computation from above, but now without the intercept in the design matrix. We plotted the data (`X_no_icept`, `y`) and the model fit to get some intuition about the use of an intercept in models. \n",
"\n",
"In the text-cell below the plot, explain (concisely!) why modelling the intercept (usually) improves model fit (this is manually graded, so no test-cell).\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_no_icept = X_with_icept[:, 1, np.newaxis]\n",
"beta_no_icept = inv(X_no_icept.T @ X_no_icept) @ X_no_icept.T @ y\n",
"y_hat_no_icept = beta_no_icept * X_no_icept\n",
"\n",
"plt.figure(figsize=(10, 10))\n",
"plt.scatter(X, y, zorder=2)\n",
"plt.xlabel('X', fontsize=25)\n",
"plt.ylabel('y', fontsize=25)\n",
"plt.xlim((0, 5))\n",
"plt.ylim((0, 10))\n",
"y_min_pred = beta_no_icept[0] * x_lim[0]\n",
"y_max_pred = beta_no_icept[0] * x_lim[1]\n",
"plt.plot(x_lim, [y_min_pred, y_max_pred], ls='-', c='orange')\n",
"plt.grid()\n",
"plt.title('Linear regression of X (without intercept!) onto y', fontsize=20)\n",
"\n",
"for i in range(y.size):\n",
" plt.plot((X[i], X[i]), (y_hat_no_icept[i], y[i]), 'r--', lw=2, zorder=1)\n",
"\n",
"plt.legend(custom_lines, ['True y', 'Predicted y', 'Residuals'])\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "4e8eaef61444d991da7f59cf6ccd6bbe",
"grade": true,
"grade_id": "cell-43ceb28b46b3b2a4",
"locked": false,
"points": 1,
"schema_version": 3,
"solution": true
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Summary: linear regression\n",
"Alright, hopefully this short recap on linear regression has refreshed your knowledge and understanding of important concepts such as predictors/design matrix ($X$), target ($y$), least squares, beta-parameters, intercept, $\\hat{y}$, residuals, MSE, and $R^2$. \n",
"\n",
"In sum, for a linear regression analysis you need some predictors ($X$) to model some target ($y$). You perform ordinary least squares to find the beta-parameters that minimize the sum of squared residuals. To assess model fit, you can look at the mean squared error (average mis-prediction) or $R^2$ (total explained variance).\n",
"\n",
"If you understand the above sentence, you're good to go! Before we go on to the real interesting stuff (modelling fMRI data with linear regression), let's test how well you understand linear regression so far."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToDo** (2 points):\n",
" \n",
"Now, you're going to implement your own linear regression on a new set of variables, but with a twist: you're going to use 5 predictors this time - we've generated the data for you already. You'll notice that the code isn't much different from when you'd implement linear regression for just a single predictor (+ intercept). In the end, you should have calculated MSE and $R^2$, which should be stored in variables named `mse_todo` and `r2_todo` respectively.\n",
"\n",
"*Note, though, that it **isn't** possible to plot the data (either X, y, or y_hat) because we have more than one predictor now; X is 5-dimensional (6-dimensional if you include the intercept) - and it's impossible to plot data in 5 dimensions!*\n",
"\n",
"To give you some handles on how to approach the problem, you can follow these steps:\n",
"\n",
"1. Check the shape of your data: is the shape of X `(N, P)`? is the shape of y `(N, 1)`?\n",
"2. Add an intercept to the model, use: `np.hstack`;\n",
"3. Calculate the beta-parameters using the formula you learned about earlier;\n",
"4. Evaluate the model fit by calculating the MSE and R-squared;\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Here, we load the data\n",
"data = np.load('ToDo.npz')\n",
"X, y = data['X'], data['y']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "eb2adf0198b90e300bd21981bcc7fd95",
"grade": false,
"grade_id": "cell-d88aff30bb2fb99d",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# 1. Check the shape of X and y\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "d71d3dd3d8b21b69b760eff45da6f111",
"grade": false,
"grade_id": "cell-e02db27cc512640b",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# 2. Add the intercept (perhaps define N first, so that your code will be more clear?) using np.hstack()\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "8422af2dd6e7670066ea0a531a98b10f",
"grade": false,
"grade_id": "cell-313a0b82249b1339",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# 3. Calculate the betas using the formula you know\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "98591e7da41ac9d8efbc5906a2f04650",
"grade": false,
"grade_id": "cell-ca51c941cd8d72b9",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# 4. Calculate the MSE (store it in a variable named mse_todo)\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "c135334706c3844a5433f84c5b577090",
"grade": false,
"grade_id": "cell-678de257a9e9a522",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# 5. Calculate R-squared (store it in a variable named r2_todo)\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "81d6aa47b7a2efe9cf282beb3ca54450",
"grade": true,
"grade_id": "cell-5615044ac45c3484",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the ToDo above, MSE part. '''\n",
"np.testing.assert_almost_equal(mse_todo, 0.656, decimal=3)\n",
"print(\"Well done!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "eb4dc952c0738c1c1af08a46b3b47b8b",
"grade": true,
"grade_id": "cell-788a29e701e25989",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the ToDo above, R2-part part. '''\n",
"np.testing.assert_almost_equal(r2_todo, 0.3409, decimal=4)\n",
"print(\"Well done!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToThink** (1 point): Let's check whether you understand what a particular beta-parameter means.\n",
"\n",
"- Some of the betas are negative (i.e., $\\hat{\\beta}< 0$); what does this tell you about the effect of that particular condition/predictor? (.5 point; first text-cell)\n",
"- The intercept-parameter (i.e., $\\beta_{0}$) should be about 6.6. What does this value tell us about the signal?\n",
"\n",
"Write your answers in the two text-cells below.\n",
"

"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "738bfb4e8bf96c9f4197fcd5c16537e4",
"grade": true,
"grade_id": "cell-af5b5c3207473231",
"locked": false,
"points": 0.5,
"schema_version": 3,
"solution": true
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "6b939574772d4f5d7205ed25e8b7ce3c",
"grade": true,
"grade_id": "cell-73045c24b787e8b3",
"locked": false,
"points": 0.5,
"schema_version": 3,
"solution": true
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you've finished the ToDo exercise and you're confident that you understand linear regression, you're ready to start with the fun part: applying the GLM to fMRI data!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## GLM in fMRI analyses\n",
"Univariate fMRI analyses basically use the same linear regression model as we've explained above to model the activation of voxels (with some minor additions) based on some design-matrix.\n",
"\n",
"### The target\n",
"However, compared to \"regular\" data, one major difference is that *the dependent variable ($y$) in fMRI analyses is timeseries data*, which means that the observations of the dependent variable (activation of voxels) vary across time. \n",
"\n",
"How does such a time-series data look like? Let's look at a (simulated) time-series from a single voxel:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# import some stuff if you haven't done that already\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from numpy.linalg import inv\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"voxel_signal = np.load('example_voxel_signal.npy')\n",
"plt.figure(figsize=(25, 5))\n",
"plt.plot(voxel_signal, 'o')\n",
"plt.xlabel('Time points (volumes)', fontsize=20)\n",
"plt.ylabel('Activity (arbitrary units)', fontsize=20)\n",
"x_lim, y_lim = (0, 400), (990, 1020)\n",
"plt.xlim(x_lim)\n",
"plt.ylim(y_lim)\n",
"plt.title('Example of voxel signal', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, the voxel timeseries (i.e. activation over time; often called 'signal') is our dependent variable ($y$). Thus, the different time points (with corresponding activity values) make up our observations/samples!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToThink** (0 points): Suppose that the TR (\"time to repetition\", i.e. how long it takes to measure each volume) of our acquisition was 2 seconds, can you deduce the duration of the experiment (in seconds) from the plot above? (Not graded, so you don't have to write anything down!)\n",
"

"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, in the plot above, the data points represent the activity (in arbitrary units) of a single voxel across time (measured in volumes). This visualization of the time-series data as discrete measurements is not really intuitive. Usually, we plot the data as continuous line over time (but always remember: fMRI data is a discretely sampled signal -- *not* a continuous one). Let's plot it as a line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(25, 5))\n",
"plt.plot(voxel_signal)\n",
"plt.xlabel('Time points (volumes)', fontsize=20)\n",
"plt.ylabel('Activity (arbitrary units)', fontsize=20)\n",
"plt.xlim(x_lim)\n",
"plt.ylim(y_lim)\n",
"plt.title('Example of voxel signal', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alright, this looks better. Now, let's look at our potential predictors ($X$)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The predictors, or: what should we use to model our target?\n",
"\n",
"#### Defining independent variables\n",
"So, we know what our target is (the time-series data), but what do we use to model/explain our signal? Well, in most neuroimaging research, your predictors are defined by your experimental design! In other words, your predictors consist of *whatever you think influenced your signal*.\n",
"\n",
"This probably sounds nonsensical, which is likely caused by the fact that we derive our independent variables (predictors) in most (observational) psychological research differently. This is because in (observational) psychological studies *both the independent variables and the dependent variables are __measured__*. In other words, our predictors are just other variables that you measured in your study. \n",
"\n",
"In neuroimaging research, however, we often derive our predictors not from measures variables but from properties of the particular experiment that we use in the MRI-scanner (or during EEG/MEG acquisiton, for that matter). In other words, we can use any property of the experiment that we believe explains our signal.\n",
"\n",
"Alright, probably still sounds vague. Let's imagine a (hypothetical) experiment in which we show subjects images of either circles or squares during fMRI acquisition lasting 800 seconds, as depicted in the image below:\n",
"\n",
"![img](https://docs.google.com/drawings/d/e/2PACX-1vQwC4chpnzsDEzKhrKH_WHhMX7vJswY4H0pkyIxdlxI_I2GG5e8i6lsiWUO0SUk7NBgdV-vXD5PIleJ/pub?w=950&h=397)\n",
"\n",
"Note that the interstimulus interval (ISI, i.e., the time between consecutive stimuli) of 50 seconds, here, is quite unrealistic; often, fMRI experiments have a much shorter ISI (e.g., around 3 seconds). Here, we will use an hypothetical experiment with an ISI of 50 seconds because that simplifies things a bit and will make figures easier to interpret.\n",
"\n",
"Anyway, let's talk about what predictors we could use given our experimental paradigm. One straighforward suggestion about properties that influence our signal is that our signal is influenced by the stimuli we show the participant during the experiment. As such, we could construct a predictor that predicts some response in the signal when a stimulus (here: a square or a circle) is present, and no response when a stimulus is absent.\n",
"\n",
"Fortunately, we kept track of the onsets (in seconds!) of our stimuli during the experiment:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"onsets_squares = np.array([10, 110, 210, 310, 410, 510, 610, 710], dtype=int)\n",
"onsets_circles = np.array([60, 160, 260, 360, 460, 560, 660, 760], dtype=int)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In other words, the first circle-stimulus was presented at 60 seconds after the scan started and the last square-stimulus was presented 710 seconds after the can started.\n",
"\n",
"For now, we'll ignore the difference between square-stimuli and circle-stimuli by creating a predictor that lumps the onsets of these two types of stimuli together in one array. This predictor thus reflects the hypothesis that the signal is affected by the presence of a stimulus (regardless of whether this was a square or a circle). (Later in the tutorial, we'll explain how to *compare* the effects of different conditions.)\n",
"\n",
"We'll call this predictor simply `onsets_all`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"onsets_all = np.concatenate((onsets_squares, onsets_circles))\n",
"print(onsets_all)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we need to do one last thing: convert the `onsets_all` vector into a proper predictor. Right now, the variable contains only the onsets, but a predictor should be an array with the same shape as the target.\n",
"\n",
"Given that our predictor should represent the hypothesis that the signal responds to the presence of a stimulus (and doesn't respond when a stimulus is absent), we can construct our predictor as a vector of all zeros, except at indices corresponding to the onsets of our stimuli, where the value is 1.\n",
"\n",
"We do this below:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"predictor_all = np.zeros(800) # because the experiment lasted 800 seconds\n",
"predictor_all[onsets_all] = 1 # set the predictor at the indices to 1\n",
"\n",
"print(\"Shape of predictor: %s\" % (predictor_all.shape,))\n",
"print(\"\\nContents of our predictor array:\\n%r\" % predictor_all.T)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can even plot it in a similar way as we did with the voxel signal:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(25, 5))\n",
"plt.plot(predictor_all, marker='o')\n",
"plt.xlabel('Time points (seconds)', fontsize=20)\n",
"plt.ylabel('Activity (arbitrary units)', fontsize=20)\n",
"plt.xlim(0, 800)\n",
"plt.ylim(-.5, 1.5)\n",
"plt.title('Example of stimulus predictor', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Resampling\n",
"However, if you look back at the plot of the voxel signal, you might notice that there is a problem in our stimulus-predictor - it seems to be on a different timescale than the signal. And that's true! The signal from the voxel is measured in volumes (in total 400, with a TR of 2 seconds) while the stimulus-onsets are defined in seconds (ranging from 10 to 760)!\n",
"\n",
"This \"issue\" can be solved by downsampling our predictor to the time resolution of our signal, i.e., one datapoint every two seconds (given that our TR is 2 seconds). In the plot below, we show you with dashed red lines which datapoints would constitute our predictor *after* downsampling (we only show the first 100 seconds for clarity)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(25, 5))\n",
"plt.plot(predictor_all, marker='o')\n",
"plt.xlabel('Time points (seconds)', fontsize=20)\n",
"plt.ylabel('Activity (arbitrary units)', fontsize=20)\n",
"plt.xlim(0, 200)\n",
"plt.ylim(-.5, 1.5)\n",
"plt.title('How to downsample the predictor', fontsize=25)\n",
"plt.grid()\n",
"\n",
"for t in np.arange(0, 200, 2):\n",
" plt.axvline(t, ls='--', c='r')\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Resampling in Python can be done using the `interp1d` function from the `scipy.interpolate` package. It works by first creating a mapping between the *scale* of the original array and the *values* of the original array, and then converting the original array to a *different scale*. We'll show you how this would be done with our `predictor_all` array. \n",
"\n",
"```python\n",
"resampler = interp1d(original_scale, original_array, kind='linear') # interp1d returns a (new) function\n",
"downsampled_array = resampler(desired_scale) \n",
"```\n",
"\n",
"Note that when creating the mapping by calling `interp1d`, the function returns a *new function*, which we store in a variable called `resampler`. Now, we can call with new function with our desired scale for our array, which will result the original array downsampled at the desired scale (note that this works exactly the same for *up*sampling). Also note that we we use specifically \"linear\" resampling (by using `kind='linear'`). In practice, most neuroimaging packages use non-linear resampling/interpolation when downsampling predictors, but the details of different kinds of resampling are beyond the scope of this course. \n",
"\n",
"Anyway, let's try this on our predictor by resampling it from the original scale (0-800 seconds) to the scale of our signal (i.e., at 0, 2, 4, 8 ... 800 seconds, assuming a TR of 2 seconds). Note the function `np.arange`, which can be used to create evenly spaced arrays (with `np.arange(start, stop, step)`):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.interpolate import interp1d\n",
"original_scale = np.arange(0, 800, 1) # from 0 to 800 seconds\n",
"print(\"Original scale has %i datapoints (0-800, in seconds)\" % original_scale.size)\n",
"resampler = interp1d(original_scale, predictor_all)\n",
"\n",
"desired_scale = np.arange(0, 800, 2)\n",
"print(\"Desired scale has %i datapoints (0, 2, 4, ... 800, in volumes)\" % desired_scale.size)\n",
"predictor_all_ds = resampler(desired_scale)\n",
"\n",
"print(\"Downsampled predictor has %i datapoints (in volumes)\" % predictor_all_ds.size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That seemed to have worked! Let's print it to be sure:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(predictor_all_ds)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Awesome! Now, we have a predictor ($X$) and a target ($y$) of the same shape, so we can apply linear regression! But before we do this, let's plot the predictor and the signal in the same plot:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(25, 10))\n",
"plt.plot(voxel_signal)\n",
"plt.plot(predictor_all_ds + voxel_signal.mean(), lw=3)\n",
"plt.xlim(x_lim)\n",
"plt.ylim(y_lim)\n",
"plt.xlabel('Time (in volumes)', fontsize=20)\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"plt.legend(['Voxel timeseries', 'Predictor'], fontsize=15, loc='upper right', frameon=False)\n",
"plt.title(\"Signal and the associated stimulus predictor\", fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Often, the design matrix is actually specified with higher precision (e.g., on the scale of milliseconds) than we did in the previous example (i.e., seconds) to accomodate onsets that are not \"locked\" to full seconds (e.g., $t=10$, $t=60$, but never $t=10.296$). We'll come back to this issue later in the tutorial.\n",
"\n",
"But first, let's practice!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (2 points): We'll start by adding an intercept to `predictor_all_ds` for you, creating a new variable called `X_simple`. Now, run linear regression on the `voxel_signal` data and save the beta-parameters in a new variable named `betas_simple`. Finally, calculate MSE and $R^ 2$ for this model and store these values in new variables named `mse_simple` and `r2_simple`.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "b6d4d47c9a1bab26c74cc2693b334da4",
"grade": false,
"grade_id": "cell-233e9ed44a5cb7ac",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"if predictor_all_ds.ndim == 1: # do not remove this! This adds a singleton dimension, such that you can call np.hstack on it\n",
" predictor_all_ds = predictor_all_ds[:, np.newaxis]\n",
"\n",
"icept = np.ones((predictor_all_ds.size, 1))\n",
"X_simple = np.hstack((icept, predictor_all_ds))\n",
"\n",
"# Start your ToDo here\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "bbc472e1edc352cae76a8aae130683a3",
"grade": true,
"grade_id": "cell-0473fc36010aae22",
"locked": true,
"points": 2,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_regression_signal_simple\n",
"\n",
"if 'X_simple' not in dir():\n",
" raise ValueError(\"Could not find a variable named 'X_simple'; did you name it correctly?\")\n",
"\n",
"if 'betas_simple' not in dir():\n",
" raise ValueError(\"Could not find a variable named 'betas_simple'; did you name it correctly?\")\n",
"\n",
"if 'mse_simple' not in dir():\n",
" raise ValueError(\"Could not find a variable named 'mse_simple'; did you name it correctly?\")\n",
"\n",
"if 'r2_simple' not in dir():\n",
" raise ValueError(\"Could not find a variable named 'r2_simple'; did you name it correctly?\")\n",
"\n",
"test_regression_signal_simple(mse_simple, r2_simple, predictor_all_ds, voxel_signal)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you've done the ToDo correctly, you should have found the the following beta-parameters: 1000.657 for the intercept and 1.023 for our stimulus-predictor. This means that our linear regression model for that voxel is as follows:\n",
"\n",
"\\begin{align}\n",
"y_{voxel} = \\beta_{intercept} + X_{stim}\\beta_{stim} + \\epsilon = 1000.647 + X_{stim}1.023 + \\epsilon\n",
"\\end{align}\n",
"\n",
"This simply means that for a unit increase in $X$ (i.e., $X = 0 \\rightarrow X = 1$), $y$ increases with 1.023. In other words, on average the signal is 1.023 higher when a stimulus is present compared to when a stimulus is absent!\n",
"\n",
"To aid interpretation, let's plot the signal ($y$) and the predicted signal ($\\hat{y} = \\beta X$) in the same plot."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from niedu.utils.nii import plot_signal_and_predicted_signal \n",
"# You may ignore the red text (a warning caused by some outdated code in some\n",
"# of the underlying packages we use)\n",
"plot_signal_and_predicted_signal(voxel_signal, predictor_all_ds, x_lim, y_lim)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The orange line represents the predicted signal, which is based on the original predictor ($X$) multiplied (or \"scaled\") by the associated beta-parameters ($\\beta$). Graphically, you can interpret the beta-parameter of the stimulus-predictor ($\\beta_{stim}$) as the maximum height of the peaks in the orange line\\* and the beta-parameter of the intercept ($\\beta_{intercept}$) as the difference from the flat portion of the orange line and 0 (i.e. the \"offset\" of the signal).\n",
"\n",
"---\n",
"\\* This holds true only when the maximum value of the original predictor is 1 (which is true in our case)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's zoom in on a portion of the data to show this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from niedu.utils.nii import plot_signal_and_predicted_signal_zoom\n",
"plot_signal_and_predicted_signal_zoom(voxel_signal, predictor_all_ds, x_lim=(20, 60), y_lim=(995, 1010))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Anyway, there seems to be an effect on voxel activity when we show a stimulus — an increase of 1.023 in the signal on average (about 0.1% percent signal change) — but you've also seen that the model fit is quite bad ($R^2 = 0.004$, about 0.4% explained variance) ...\n",
"\n",
"What is happening here? Is our voxel just super noisy? Or is something wrong with our model? We'll talk about this in the next section!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Using the BOLD response in GLM models\n",
"Let's go back to our original idea behind the predictor we created. We assumed that in order to model activity in response to our stimuli, our predictor should capture an increase/decrease in activity *at the moment of stimulus onset*. But this is, given our knowledge of the BOLD-response, kind of unrealistic to assume: it is impossible to measure instantaneous changes in neural activity in response to stimuli or tasks with fMRI, *because the BOLD-response is quite slow and usually peaks around 5-7 seconds **after** the 'true' neuronal activity (i.e. at cellular level)*. \n",
"\n",
"In the above model, we have not incorporated either the lag (i.e. ~6 seconds) or the shape of the BOLD-response: we simply modelled activity as an instantaneous response to a stimulus event. \n",
"\n",
"You can imagine that if you incorporate this knowledge about the BOLD-response into our model, the fit will likely get better! In this section, we'll investigate different ways to incorporate knowledge of the BOLD-response in our predictors."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### The canonical HRF\n",
"The easiest and most often-used approach to incorporating knowledge about the BOLD-response in univariate analyses of fMRI data is to assume that each voxel responds to a stimulus in a fixed way. In other words, that voxels always respond (activate/deactivate) to a stimulus in the same manner. This is known as using a \"canonical haemodynamic response function (HRF)\". Basically, an HRF is a formalization of how we think the a voxel is going to respond to a stimulus. A *canonical* HRF is the implementation of an HRF in which you use the same HRF for each voxel, participant, and condition. There are other implementations of HRFs (apart from the canonical), in which you can adjust the exact shape of the HRF based on the data you have; examples of these HRFs are *temporal basis sets* and *finite impulse reponse models* (FIR), which we'll discuss later.\n",
"\n",
"There are different types of (canonical) HRFs; each models the assumed shape of the BOLD-response slightly differently. For this course, we'll use the most often used canonical HRF: the double-gamma HRF, which is a combination of two different gamma functions (one modelling the overshoot and one modelling the post-stimulus undershoot).\n",
"\n",
"We'll use the \"double gamma\" HRF implementation of the [nilearn](https://nilearn.github.io) Python package. They provide different \"versions\" of the HRF (which differ slightly in their shape); we'll use the \"Glover\" version, which is based on a double-[gamma function](https://en.wikipedia.org/wiki/Gamma_function): `glover_hrf`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nilearn.glm.first_level.hemodynamic_models import glover_hrf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This function takes a couple of arguments (the most important being: TR, oversampling factor, and length of the HRF in seconds), and returns a double gamma HRF. It is important to make sure that your HRF is on the same timescale as our design (predictors). In the previous section, we made sure we defined our predict at the time scale of seconds first before downsampling it to a time resolution of 2 seconds (i.e., the TR). \n",
"\n",
"Thus, given a TR of 2, we can use a \"oversampling factor\" of 2 to get the HRF on the timescale of seconds:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"TR = 2\n",
"osf = 2\n",
"length_hrf = 32 # sec\n",
"\n",
"canonical_hrf = glover_hrf(tr=TR, oversampling=osf, time_length=length_hrf, onset=0)\n",
"canonical_hrf /= canonical_hrf.max()\n",
"print(\"Size of canonical hrf variable: %i\" % canonical_hrf.size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, the length of the `canonical_hrf` variable is 32 (seconds). Now, let's plot it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"t = np.arange(0, canonical_hrf.size)\n",
"\n",
"plt.figure(figsize=(12, 5))\n",
"plt.plot(t, canonical_hrf)\n",
"plt.xlabel('Time (in seconds!) after stimulus onset', fontsize=15)\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.title('Double gamma HRF', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Convolution\n",
"The figure of the HRF shows how we'd expect that an idealized (noiseless) response to a single event would look like. But how should we incorporate this HRF into our model? Traditionally, this is done using a mathematical operation called **convolution**. Basically, it \"slides\" the HRF across our 0-1 coded stimulus-vector from left to right and elementwise multiplies the HRF with the stimulus-vector. This is often denoted as:\n",
"\n",
"\\begin{align}\n",
"X_{\\mathrm{conv}} = \\mathrm{HRF} * X_{\\mathrm{original}}\n",
"\\end{align}\n",
"\n",
"in which $*$ is the symbol for convolution, $X_{\\mathrm{original}}$ is the original stimulus-vector, and $X_{\\mathrm{conv}}$ the result of the convolution.\n",
"\n",
"Let's plot an example to make it clearer. Suppose we have an onset-vector of length 100 (i.e., the experiment was 100 seconds long) with three stimulus presentations: at $t = 10$, $t = 40$, and $t = 70$. The stimulus-vector (upper plot), double-gamma HRF (right plot), and the result of the convolution of the stimulus-vector and the HRF (lower plot) looks as follows:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"random_stimulus_onsets = [10, 40, 70]\n",
"random_stim_vector = np.zeros(100)\n",
"random_stim_vector[random_stimulus_onsets] = 1\n",
"\n",
"plt.figure(figsize=(15, 6))\n",
"plt.subplot2grid((3, 3), (0, 0), colspan=2)\n",
"plt.plot(random_stim_vector)\n",
"plt.xlim((0, 100))\n",
"plt.ylim((0, 1))\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.xlabel('Time (seconds)', fontsize=15)\n",
"plt.title('Stimulus events', fontsize=20)\n",
"plt.grid()\n",
"\n",
"plt.subplot2grid((3, 3), (0, 2), rowspan=2)\n",
"plt.plot(canonical_hrf)\n",
"plt.title('HRF', fontsize=20)\n",
"plt.xlim(0, 24)\n",
"plt.xlabel(\"Time (seconds)\", fontsize=15)\n",
"plt.grid()\n",
"\n",
"convolved_stim_vector = np.convolve(random_stim_vector, canonical_hrf, 'full')\n",
"plt.subplot2grid((3, 3), (1, 0), colspan=2)\n",
"plt.plot(convolved_stim_vector)\n",
"plt.title('Convolved stimulus-vector', fontsize=20)\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.xlabel('Time (seconds)', fontsize=15)\n",
"plt.xlim(0, 100)\n",
"plt.tight_layout()\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The result — the convolved stimulus-vector — is basically the output of a the multiplication of the HRF and the stimulus-events when you would \"slide\" the HRF across the stimulus vector. As you can see, the convolved stimulus-vector correctly shows the to-be-expected lag and shape of the BOLD-response! Given that this new predictor incorporates this knowledge of the to-be expected response, it will probably model the activity of our voxel way better. Note that the temporal resolution of your convolved regressor is necessary limited by the resolution of your data (i.e. the TR of your fMRI acquisition). That's why the convolved regressor doesn't look as \"smooth\" as the HRF. \n",
"\n",
"As you can see in the code for the plot above, numpy provides us with a function to convolve two arrays:\n",
"\n",
"```python\n",
"np.convolve(array_1, array_2)\n",
"```\n",
"\n",
"Now, we can convolve the HRF with out stimulus-predictor. Importantly, we want to do this convolution operation in the resolution of our onsets (here: seconds), not in the resolution of our signal (TR) (the reason for this is explained clearly in Jeanette Mumford's [video on the HRF](https://www.youtube.com/watch?v=5JNX34gYG7Q).)\n",
"Therefore, we need to perform the convolution on the variable `predictor_all` (*not* the downsampled variable: `predictor_all_ds`)!\n",
"\n",
"We'll do this below (we'll reuse the `canonical_hrf` variable defined earlier):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"'''We need to \"squeeze\" out the extra singleton axis, because that's\n",
"what the np.convolve function expects, i.e., arrays of shape (N,) and NOT (N, 1)\n",
"To go from (N, 1) --> (N,) we'll use the squeeze() method'''\n",
"predictor_conv = np.convolve(predictor_all.squeeze(), canonical_hrf)\n",
"\n",
"print(\"The shape of the convolved predictor after convolution: %s\" % (predictor_conv.shape,))\n",
"\n",
"# After convolution, we also neem to \"trim\" off some excess values from\n",
"# the convolved signal (the reason for this is not important to understand)\n",
"predictor_conv = predictor_conv[:predictor_all.size]\n",
"\n",
"print(\"After trimming, the shape is: %s\" % (predictor_conv.shape,))\n",
"\n",
"# And we have to add a new axis again to go from shape (N,) to (N, 1),\n",
"# which is important for stacking the intercept, later\n",
"predictor_conv = predictor_conv[:, np.newaxis]\n",
"\n",
"print(\"Shape after adding the new axis: %s\" % (predictor_conv.shape,))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It's a bit of a hassle (squeezing out the singleton axis, trimming, adding the axis back ...), but now we have a predictor which includes information about the expected HRF!\n",
"\n",
"Let's look at the predictor before and after convolution in the same plot:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(25, 5))\n",
"plt.plot(predictor_all)\n",
"plt.plot(predictor_conv)\n",
"plt.xlim(-1, 800)\n",
"plt.title(\"Predictor before and after convolution\", fontsize=25)\n",
"plt.xlabel(\"Time (seconds!)\", fontsize=20)\n",
"plt.ylabel(\"Activity (A.U.)\", fontsize=20)\n",
"plt.legend(['Before', 'After'], loc='upper right', fontsize=15)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Linear scaling\n",
"Great! Our predictor now includes the expected 'lag' and shape of the HRF, and we can start analyzing our signal with our new convolved predictor! But before we'll do this, there is one more concept that we'll demonstrate. Remember the concept of **linear scaling** of the BOLD-response? This property of the BOLD-response states that it will linearly scale with the input it is given.\n",
"\n",
"Let's see how that works:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(15, 5))\n",
"\n",
"N = 40\n",
"one_stim = np.zeros(N)\n",
"one_stim[5] = 1\n",
"one_stim_conv = np.convolve(one_stim, canonical_hrf)[:N]\n",
"two_stim = np.zeros(N)\n",
"two_stim[[5, 6]] = 1\n",
"two_stim_conv = np.convolve(two_stim, canonical_hrf)[:N]\n",
"three_stim = np.zeros(N)\n",
"three_stim[[5, 6, 7]] = 1\n",
"three_stim_conv = np.convolve(three_stim, canonical_hrf)[:N]\n",
"\n",
"plt.subplot2grid((2, 3), (0, 0))\n",
"for ons in np.where(one_stim)[0]:\n",
" plt.plot([ons, ons], [0, 1])\n",
"\n",
"plt.xlim(0, N)\n",
"plt.title(\"One stimulus\", fontsize=25)\n",
"plt.grid()\n",
"\n",
"plt.subplot2grid((2, 3), (0, 1))\n",
"for ons in np.where(two_stim)[0]:\n",
" plt.plot([ons, ons], [0, 1], c='tab:orange')\n",
"\n",
"plt.xlim(0, N)\n",
"plt.title(\"Two stimuli\", fontsize=25)\n",
"plt.grid()\n",
"\n",
"plt.subplot2grid((2, 3), (0, 2))\n",
"for ons in np.where(three_stim)[0]:\n",
" plt.plot([ons, ons], [0, 1], c='tab:green')\n",
"\n",
"plt.xlim(0, N) \n",
"plt.title(\"Three stimuli\", fontsize=25)\n",
"plt.grid()\n",
"\n",
"plt.subplot2grid((2, 3), (1, 0), colspan=3)\n",
"plt.plot(one_stim_conv)\n",
"plt.plot(two_stim_conv)\n",
"plt.plot(three_stim_conv)\n",
"plt.legend(['One stim', 'Two stim', 'Three stim'])\n",
"plt.title('Linear scaling of HRF', fontsize=25)\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"plt.xlabel('Time (TR)', fontsize=20)\n",
"plt.xlim(0, N)\n",
"plt.grid()\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Also, in our random stimulus-vector above (and also in the example we showed earlier) we assumed that each image was only showed briefly (i.e. we only modelled the onset) - but what if a stimulus (or task) may take longer, say, 15 seconds? Let's see what happens."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"random_stimulus_onsets2 = list(range(10, 25)) + list(range(40, 55)) + list(range(70, 85))\n",
"random_stim_vector2 = np.zeros(100)\n",
"\n",
"random_stim_vector2[random_stimulus_onsets2] = 1\n",
"\n",
"plt.figure(figsize=(15, 6))\n",
"plt.subplot(2, 1, 1)\n",
"plt.grid()\n",
"plt.plot(random_stim_vector2, c='tab:blue')\n",
"\n",
"plt.xlim((0, 100))\n",
"plt.ylim((-.5, 1.2))\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"\n",
"plt.title('Stimulus events', fontsize=25)\n",
"\n",
"convolved_stim_vector2 = np.convolve(random_stim_vector2, canonical_hrf)[:random_stim_vector2.size]\n",
"plt.subplot(2, 1, 2)\n",
"plt.plot(convolved_stim_vector2)\n",
"plt.title('Convolved stimulus-vector', fontsize=25)\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"plt.xlabel('Time (seconds)', fontsize=20)\n",
"plt.grid()\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, convolution takes care to model the shape of the BOLD-response according to how long you specify the stimulus to take! "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToThink** (1 point): Given the properties of the BOLD-response (and assuming linear-time invariance is not violated), would you expect the same or a different BOLD-response in response to 3 consecutive stimuli (of the same condition) of half a second second each (which follow each other immediately, i.e. without interstimulus interval) versus 1 stimulus of 1.5 seconds? Why? (Write your answer in the text-cell below)\n",
"

"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "30dcf244e44a54a5cd2ef92f1e074b81",
"grade": true,
"grade_id": "cell-ff75fe1cb96158af",
"locked": false,
"points": 1,
"schema_version": 3,
"solution": true
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Actually, convolution can model *any* sequence of stimulus events, even stimuli with random onsets - just look at the plot below!\n",
"\n",
"(you can execute this cell below multiple times to see different random regressor shapes!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"random_stimulus_onsets3 = np.random.randint(0, 100, 25)\n",
"random_stim_vector3 = np.zeros(100)\n",
"random_stim_vector3[random_stimulus_onsets3] = 1\n",
"\n",
"plt.figure(figsize=(15, 6))\n",
"plt.subplot(2, 1, 1)\n",
"\n",
"plt.axhline(0)\n",
"for i, event in enumerate(random_stim_vector3):\n",
" if event != 0.0:\n",
" plt.plot((i, i), (0, 1), 'k-', c='tab:blue')\n",
"\n",
"plt.xlim((0, 100))\n",
"plt.ylim((-0.1, 1.1))\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"plt.title('Stimulus events', fontsize=25)\n",
"plt.grid()\n",
"\n",
"convolved_stim_vector3 = np.convolve(random_stim_vector3 * .5, canonical_hrf, 'full')[:random_stim_vector3.size]\n",
"plt.subplot(2, 1, 2)\n",
"plt.plot(convolved_stim_vector3)\n",
"plt.xlim(0, 100)\n",
"plt.title('Convolved stimulus-vector', fontsize=25)\n",
"plt.ylabel('Activity (A.U.)', fontsize=20)\n",
"plt.xlabel('Time (seconds)', fontsize=20)\n",
"plt.grid()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (1 point): Let's assume that we did an experiment in which participants were presented with a visual stimulus lasting 20 seconds six times over the course of an experiment of 3 minutes (starting at $t=0$, $t=30$, ... , $t=150$ sec). Create a stimulus predictor (on the timescale of seconds), store this in a variable named `todo_pred`, and then convolve this predictor with the `canonical_hrf` variable. Make sure to trim the convolved predictor, and store the result in a variable named `todo_pred_conv`.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "db5e5da95dbab7776d6271848539c6b5",
"grade": false,
"grade_id": "cell-27c3dcd912a42207",
"locked": false,
"schema_version": 3,
"solution": true,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Implement your ToDo here\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "d27060719333c6803d52adedd6aa445b",
"grade": true,
"grade_id": "cell-c66689a77bde7c06",
"locked": true,
"points": 2,
"schema_version": 3,
"solution": false,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo'''\n",
"try:\n",
" assert(todo_pred.size == 180)\n",
"except AssertionError as e:\n",
" print(\"The predictor is not the right length!\")\n",
" raise(e)\n",
"\n",
"try:\n",
" assert(np.sum(todo_pred) == 120)\n",
"except AssertionError as e:\n",
" print(\"Are you sure your stimulus events last 20 seconds?\")\n",
" raise(e)\n",
" \n",
"try:\n",
" assert(todo_pred_conv.size == 180)\n",
"except AssertionError as e:\n",
" print(\"Did you trim the convolved predictor?\")\n",
" raise(e)\n",
"\n",
"try:\n",
" np.testing.assert_almost_equal(np.sum(todo_pred_conv), 482.6069, decimal=4)\n",
"except AssertionError as e:\n",
" print(\"Did you convolve the predictor with the canonical HRF?\")\n",
" raise(e)\n",
" \n",
"print(\"Well done!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, in summary, convolving the stimulus-onsets (and their duration) with the HRF gives us (probably) a better predictor of the voxel signal than just the stimulus-onset, because (1) it models the lag of the BOLD-response and (2) models the shape of the BOLD-response (accounting for the linear scaling principle). \n",
"\n",
"#### Resampling revisited\n",
"Now, we're *almost* ready to start analyzing our signal with the convolved predictor! The problem, at this moment, however is that the convolved predictor and the signal are on different scales!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Size convolved predictor: %i\" % predictor_conv.size)\n",
"print(\"Size voxel signal: %i\" % voxel_signal.size)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use resampling to find the data points of the convolved HRF predictor that correspond to the onset of the volumes of our voxel signal. Importantly, we have to \"squeeze out\" the singleton dimension before downsampling the predictor (otherwise it'll give an error). Then, we can plot the convolved predictor and the signal in the same figure (because now they are defined on the same timescale!):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"original_scale = np.arange(0, 800)\n",
"resampler = interp1d(original_scale, np.squeeze(predictor_conv))\n",
"\n",
"desired_scale = np.arange(0, 800, 2)\n",
"predictor_conv_ds = resampler(desired_scale)\n",
"\n",
"plt.figure(figsize=(15, 5))\n",
"plt.plot(predictor_conv_ds + voxel_signal.mean())\n",
"plt.plot(voxel_signal)\n",
"plt.grid()\n",
"plt.title('Downsampled/convolved predictor + signal', fontsize=20)\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.xlabel('Time (seconds)', fontsize=15)\n",
"plt.legend(['Predictor', 'Signal'])\n",
"plt.xlim(x_lim)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Initial upsampling of predictors\n",
"In the previous examples, the resampling process came down to selecting every other datapoint (at $t=0$, $t=2$, $t=4$, ..., $t=798$), because our onsets were all \"locked\" to \"round\" seconds (e.g., $t=10$, $t=60$, but never $t=10.29$ or something). Very often, however, stimuli (or whatever you're using to construct your predictors) are not locked to \"round\" seconds. How would you then initially create a predictor? One way is to do so is to create your stimulus predictor on a more precise timescale, such as on hundredths of seconds (i.e., with a precision of 0.01 seconds). In other words, we oversample the predictor with a factor 100. Then, we can set the indices in this oversampled predictor to our onsets with a higher precision (e.g., for a particular onset at 5.12 seconds, we can set the predictor at index 512 to 1).\n",
"\n",
"Let's do this below for some hypothetical onsets logged with millisecond precision for an experiment lasting 50 seconds:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"onsets2 = np.array([3.62, 16.26, 34.12, 42.98]) # in seconds\n",
"duration = 50 # duration experiment in seconds\n",
"osf = 100 # osf = OverSampling Factor\n",
"\n",
"pred2 = np.zeros(duration * osf)\n",
"print(\"Size of oversampled (factor: 1000) predictor: %i\" % pred2.size)\n",
"\n",
"onsets2_in_msec = (onsets2 * osf).astype(int) # we convert it to int, because floats (even when it's 5.0) cannot be used as indices\n",
"pred2[onsets2_in_msec] = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, to convolve this signal, we should also define our HRF with a higher temporal precision (i.e., hundredths of seconds). Notice that the HRF is also a lot smoother when defined it on a timescale of seconds."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"osf = 100 * TR\n",
"hrf_ms = glover_hrf(tr=TR, oversampling=osf, time_length=32)\n",
"hrf_ms /= hrf_ms.max() # scale such that max = 1\n",
"\n",
"t = np.arange(0, hrf_ms.size)\n",
"\n",
"plt.figure(figsize=(12, 5))\n",
"plt.plot(t, hrf_ms)\n",
"plt.xlabel('Time (in tens of milliseconds!) after stimulus onset', fontsize=15)\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.title('Double gamma HRF', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's convolve our predictor with the HRF again:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pred2_conv = np.convolve(pred2, hrf_ms)[:pred2.size]\n",
"\n",
"plt.figure(figsize=(15, 5))\n",
"plt.plot(pred2_conv)\n",
"plt.xlabel('Time (in hundreths of seconds!) after stimulus onset', fontsize=15)\n",
"plt.ylabel('Activity (A.U.)', fontsize=15)\n",
"plt.title('High precision convolved predictor', fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now the only thing that we have to do is to downsample the convolved predictor!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (1 point): Assuming that the described experiment had a TR of 1.25 seconds and 40 volumes, downsample the convolved predictor (`pred2_conv`) to the timescale of the hypothetical signal (i.e., resample the predictor to the timepoints $t=0, t=1.25, t=2.5, ... , t=48.75$). Call this downsampled predictor `pred2_conv_ds`.\n",
"\n",
"Tip: think about the original scale (msec) and the desired scale (steps of 1.25 sec) of your predictor.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "2e51ce3a247f9ae56309c37e0525db30",
"grade": false,
"grade_id": "cell-4e0915e6b91db082",
"locked": false,
"schema_version": 3,
"solution": true,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Implement your ToDo here\n",
"original_scale = np.arange(0, duration, 0.01) # in steps of 0.01 seconds, i.e., hundredths of seconds\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "8dfddfdbbb686d0f800098367b64b1b4",
"grade": true,
"grade_id": "cell-58ba86ba75a3063c",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo '''\n",
"\n",
"try:\n",
" assert(pred2_conv_ds.size == 40)\n",
"except AssertionError as e:\n",
" print(\"Downsampled predictor is not the right size!\")\n",
" raise(e)\n",
"\n",
"try:\n",
" np.testing.assert_almost_equal(pred2_conv_ds.sum(), 12.4886, decimal=4)\n",
"except AssertionError as e:\n",
" print(\"Downsampling went wrong!\")\n",
" raise(e)\n",
"\n",
"print(\"Well done!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Fitting an HRF-informed model\n",
"Finally ... we're ready to see whether the HRF-based predictor *actually* models our original voxel signal (`voxel_signal`, from earlier in the tutorial) more accurately! Let's create a proper design-matrix ($X$) by stacking an intercept with the stimulus-regressor, perform the regression analysis, and check out the results (by plotting the predicted signal against the true signal). For comparison, we'll also plot the original (unconvolved) model as well!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if predictor_conv_ds.ndim == 1:\n",
" # Add back a singleton axis (which was removed before downsampling)\n",
" # otherwise stacking will give an error\n",
" predictor_conv_ds = predictor_conv_ds[:, np.newaxis]\n",
"\n",
"intercept = np.ones((predictor_conv_ds.size, 1))\n",
"X_conv = np.hstack((intercept, predictor_conv_ds))\n",
"betas_conv = inv(X_conv.T @ X_conv) @ X_conv.T @ voxel_signal\n",
"\n",
"plt.figure(figsize=(15, 8))\n",
"\n",
"plt.subplot(2, 1, 1)\n",
"plt.plot(voxel_signal)\n",
"plt.plot(X_conv @ betas_conv, lw=2)\n",
"plt.xlim(x_lim)\n",
"plt.ylabel(\"Activity (A.U.)\", fontsize=20)\n",
"plt.title(\"Model fit with *convolved* regressor\", fontsize=25)\n",
"plt.legend(['True signal', 'Predicted signal'], fontsize=12, loc='upper right')\n",
"plt.grid()\n",
"\n",
"plt.subplot(2, 1, 2)\n",
"plt.plot(voxel_signal)\n",
"betas_simple = np.array([1000.64701684, 1.02307437])\n",
"plt.plot(X_simple @ betas_simple, lw=2)\n",
"plt.xlim(x_lim)\n",
"plt.ylabel(\"Activity (A.U.)\", fontsize=20)\n",
"plt.title(\"Model fit with original (*unconvolved*) regressor\", fontsize=25)\n",
"plt.legend(['True signal', 'Predicted signal'], fontsize=12, loc='upper right')\n",
"plt.xlabel(\"Time (volumes)\", fontsize=20)\n",
"plt.grid()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wow, that looks much better! First, let's inspect the beta-parameters:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('The beta-parameter of our stimulus-predictor is now: %.3f' % betas_conv[1])\n",
"print('... which is %.3f times larger than the beta of our original '\n",
" 'beta (based on the unconvolved predictors)!' % (betas_conv[1] / betas_simple[1]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like we did before, we'll zoom in and show you how the estimated beta-parameters relate tho the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_signal_and_predicted_signal_zoom(voxel_signal, predictor_conv_ds, x_lim=(25, 65), y_lim=(995, 1010))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alright, so we seem to measure a way larger effect of our stimulus on the voxel activity, but is the model fit actually also better? Let's find out."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from numpy.linalg import lstsq # numpy implementation of OLS, because we're lazy\n",
"\n",
"y_hat_conv = X_conv @ betas_conv\n",
"y_hat_orig = X_simple @ lstsq(X_simple, voxel_signal, rcond=None)[0]\n",
"\n",
"MSE_conv = ((y_hat_conv - voxel_signal) ** 2).mean()\n",
"MSE_orig = ((y_hat_orig - voxel_signal) ** 2).mean()\n",
"\n",
"print(\"MSE of model with convolution is %.3f while the MSE of the model without convolution is %.3f.\" %\n",
" (MSE_conv, MSE_orig))\n",
"\n",
"R2_conv = 1 - (np.sum((voxel_signal - y_hat_conv) ** 2) / np.sum((voxel_signal - voxel_signal.mean()) ** 2))\n",
"R2_orig = 1 - (np.sum((voxel_signal - y_hat_orig) ** 2) / np.sum((voxel_signal - voxel_signal.mean()) ** 2))\n",
"\n",
"print(\"R-squared of model with convolution is %.5f and without convolution it is %.5f.\" % \n",
" (R2_conv, R2_orig))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the model fit metrics above, we can safely conclude that (at least for this voxel), a design ($X$) in which we include information about the expected lag/shape of the HRF is *way* better than a 'HRF-naive' design (i.e. an unconvolved design). "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToDo** (2 points):\n",
" \n",
"So far, our examples were based on the stimulus-onsets of the two conditions (circles and squares) lumped together. This tested the hypothesis of our voxel responded to *any kind* of stimulus -- regardless of the condition (squares/circles) of the stimulus. Usually, however, you want to estimate the betas for each condition separately (i.e., how much each condition on average activates a voxel) and test the influence of each condition on the voxel separately (but estimated in the same model)! This is what you're going to do in this ToDo.\n",
"\n",
"We provide you with the predictors for circles (`predictor_circles`) and for squares (`predictor_squares`) below. You have to do the following:\n",
"\n",
"- convolve each predictor with the double-gamma HRF (use `canonical_hrf`) separately (don't forget to squeeze, trim, and add the axis back)\n",
"- downsample the convolved predictors\n",
"- stack an intercept and the two predictors **in a single design-matrix** ($X$) -- use `np.hstack((intercept, pred1, pred2))` for this\n",
"- calculate the beta-parameters (estimated in a single model!)\n",
"- calculate MSE (store this in the variable `mse_new`) and $R^2$ (store this in the variable `r2_new`)\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "2d59ecfdaf711e03ad589675ba9cf591",
"grade": false,
"grade_id": "cell-cbce5e40f56cd9fb",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"predictor_circles = np.zeros((800, 1))\n",
"predictor_circles[onsets_circles] = 1\n",
"\n",
"predictor_squares = np.zeros((800, 1))\n",
"predictor_squares[onsets_squares] = 1\n",
"\n",
"# Implement your solution below\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "4a02ec68d82ce1d2c7824f97f2dd19d7",
"grade": true,
"grade_id": "cell-aa40b69dd78784d6",
"locked": true,
"points": 2,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the ToDo above (but only if the variables are named correctly). '''\n",
"\n",
"if 'mse_new' not in dir():\n",
" raise ValueError(\"Could not find the variable 'mse_new'! Did you spell it correctly?\")\n",
"\n",
"if 'r2_new' not in dir():\n",
" raise ValueError(\"Could not find the variable 'r2_new'! Did you spell it correctly?\")\n",
"\n",
"np.testing.assert_almost_equal(mse_new, 7.1633, decimal=4)\n",
"np.testing.assert_almost_equal(r2_new, 0.3091, decimal=4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToThink** (1 point): If you've done the above ToDo correctly, you should have found that the model fit of the design-matrix with the circles and squares predictors separately (as you did in the ToDo) leads to a (somewhat) better model fit (lower MSE/higher $R^2$) than the design-matrix with the conditions lumped together in a single predictor (as we did earlier).\n",
"\n",
"Argue why you think this may be the case here.\n",
"

"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "9b1e4ac312be4b983e749720699453f1",
"grade": true,
"grade_id": "cell-da9147c0b9f28d16",
"locked": false,
"points": 1,
"schema_version": 3,
"solution": true
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Temporal basis functions\n",
"Most studies use a canonical HRF to convolve with their predictors. However, remember that using a canonical HRF assumes that the particular shape of that HRF will be appropriate for each voxel, each condition, and each subject in your study. This is quite a strong assumption. In fact, studies have shown that the exact shape of the HRF often differs between voxels, conditions, and subjects (as is explained in detail by the [video on basis sets](https://www.youtube.com/watch?v=YfeMIcDWwko&index=21&list=PLcvMDPDk-dSmTBejANv7kY2mFo1ni_gkA) by Tor Wager).\n",
"\n",
"In fact, this might also be the case in our data! If you've done the ToDo correctly, you might have seen that the predictions ($\\hat{y}$) seem to \"peak\" too late for the circle-stimuli ... In fact, let's plot the data ($y$) and the prediction (based on the previously defined stimulus predictor, i.e., the circles and squares in a single predictor):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_signal_and_predicted_signal_zoom(voxel_signal, X_conv, x_lim=(15, 55), y_lim=(990, 1015), plot_params=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, what should be do about this? Well, one solution is to use *temporal basis functions* (also called *temporal basis sets*). Temporal basis functions model the HRF as *a combination of (hemodynamic response) functions*. \n",
"\n",
"In practice, this amounts to convolving your predictor with not one, but multiple HRFs. This results in multiple predictors per stimulus-condition! Each HRF measures a \"part\" (or property) of the total HRF. Together, these predictors aim to estimate the complete HRF for a given stimulus-vector (condition). \n",
"\n",
"We're going to use *double-gamma basis functions* as an example of a temporal basis set (but there are other sets, like the (*single-gamme basis set*, *sine basis set* and *finite impulse response* set). In this particular basis set, the original double-gamma HRF is used in combination with its first derivative (often called the 'temporal derivative'). (Sometimes, the second derivative, also called the \"dispersion derivative\", is also added. We leave this out for simplicity here.)\n",
"\n",
"Suppose we have only one stimulus condition. Then, the signal ($\\mathbf{y}$) is not modelled by only one convolved predictor ($X_{\\mathrm{stim}}$) but by two predictors: a predictor convolved with the original HRF ($X_{\\mathrm{orig}}$) and a predictor convolved with the temporal derivative of the HRF ($X_{\\mathrm{temp}}$). Formally:\n",
"\n",
"\\begin{align}\n",
"y = \\beta_{0} + \\mathbf{X}_{\\mathrm{orig}}\\beta_{1} + \\mathbf{X}_{\\mathrm{temp}}\\beta_{2} + \\epsilon\n",
"\\end{align}\n",
"\n",
"Alright, but how do we compute this temporal derivative and how does this look like? Again, we can use a function from the [nilearn](https://nilearn.github.io) package: `glover_time_derivative`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nilearn.glm.first_level.hemodynamic_models import glover_time_derivative\n",
"\n",
"tderiv_hrf = glover_time_derivative(tr=2, oversampling=2)\n",
"tderiv_hrf /= tderiv_hrf.max()\n",
"\n",
"plt.figure(figsize=(20, 5))\n",
"plt.subplot(1, 3, 1)\n",
"plt.plot(canonical_hrf, lw=3)\n",
"plt.ylim(-0.8, 1.1)\n",
"plt.ylabel(\"Activity (A.U.)\", fontsize=20)\n",
"plt.xlabel(\"Time (seconds)\", fontsize=20)\n",
"plt.title(\"Original HRF\", fontsize=25)\n",
"plt.grid()\n",
"\n",
"plt.subplot(1, 3, 2)\n",
"plt.plot(tderiv_hrf, c='tab:orange', lw=3)\n",
"plt.ylim(-0.8, 1.1)\n",
"plt.xlabel(\"Time (seconds)\", fontsize=20)\n",
"plt.title(\"First (temporal) derivative\", fontsize=25)\n",
"\n",
"plt.tight_layout()\n",
"plt.grid()\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The cool thing about this double-gamma basis set is that the derivatives can (to a certain extent) correct for slight deviations in the lag and shape of the HRF based on the data! Specifically, the first (temporal) derivative can correct for slight differences in lag (compared to the canonical single-gamma HRF) and the second (dispersion) derivative can correct for slight difference in the width (or \"dispersion\") of the HRF (compared to the canonical single-gamma HRF). \n",
"\n",
"\"How does this 'correction' work, then?\", you might ask. Well, think about it this way: the original (canonical) HRF measures the increase/decrease — or amplitude — of the BOLD-response. In a similar way, the temporal derivative measures the *onset* — or lag — of the BOLD-response. (And if you use the dispersion derivative: this would measure the *width* of the BOLD-response.) \n",
"\n",
"When we use our two predictors (one convolved with the canonical HRF, one with the temporal derivative) in a linear regression model, the model will assign each predictor (each part of the HRF) a beta-weight, as you know. These beta-weights are chosen such that model the data — some response of the voxel to a stimulus — as well as possible. Basically, assigning a (relatively) high (positive or negative) beta-weight to the predictor convolved with the temporal derivative will \"shift\" the HRF (increases/decreases the onset of the HRF).\n",
"\n",
"Alright, let's visualize this. Suppose we have a voxel that we know does not conform to the specific assumptions about lag (onset) of the canonical (double-gamma) HRF. Specifically, we see that the canonical HRF peaks too early.\n",
"We'll show below that it suboptimally explains this voxel:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from niedu.utils.nii import simulate_signal\n",
"\n",
"# tbs = temporal basis set\n",
"y_tbs, X_tbs = simulate_signal(\n",
" onsets=[10],\n",
" conditions=['stim'],\n",
" duration=100,\n",
" TR=1,\n",
" icept=0,\n",
" params_canon=[10],\n",
" params_deriv1=[-8],\n",
" std_noise=2,\n",
" rnd_seed=10,\n",
" plot=False\n",
")\n",
"\n",
"X_canon_only = X_tbs[:, :-1] # remove temporal derivative for now\n",
"\n",
"# Do regression \n",
"beta_canon = inv(X_canon_only.T @ X_canon_only) @ X_canon_only.T @ y_tbs\n",
"yhat_canon = X_canon_only @ beta_canon\n",
"\n",
"# Plot the data and the prediction (y_hat)\n",
"plt.figure(figsize=(15, 5))\n",
"plt.plot(y_tbs)\n",
"plt.plot(yhat_canon)\n",
"plt.xlim(0, 98)\n",
"plt.xlabel(\"Time (seconds)\", fontsize=20)\n",
"plt.ylabel(\"Activation (A.U.)\", fontsize=20)\n",
"plt.annotate('', xy=(10, 3), xytext=(10, 0.2),\n",
" arrowprops=dict(arrowstyle='<-', lw=2))\n",
"plt.text(10, 3.1, 'Stim\\nonset', horizontalalignment='center', fontsize=15)\n",
"plt.legend(['signal', 'predicted signal'], fontsize=15)\n",
"plt.title(\"Prediction with canonical HRF only\", fontsize=25)\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, the predicted signal (orange line) misses the peak of the BOLD-response. Now, let's see what happens if we add the temporal derivative to the model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Do regression with HRF + temp deriv HRF\n",
"beta_td = inv(X_tbs.T @ X_tbs) @ X_tbs.T @ y_tbs\n",
"yhat_td = X_tbs @ beta_td\n",
"\n",
"# Plot model with temp deriv HRF\n",
"plt.figure(figsize=(15, 5))\n",
"plt.plot(y_tbs)\n",
"plt.plot(yhat_td)\n",
"plt.xlim(0, 98)\n",
"plt.ylabel(\"Activation (A.U.)\", fontsize=20)\n",
"plt.annotate('', xy=(10, 3), xytext=(10, 0.2),\n",
" arrowprops=dict(arrowstyle='<-', lw=2))\n",
"plt.text(10, 3.1, 'Stim\\nonset', horizontalalignment='center', fontsize=15)\n",
"plt.title(\"Prediction with canonical HRF + temporal deriv\", fontsize=25)\n",
"plt.xlabel(\"Time (seconds)\", fontsize=20)\n",
"\n",
"plt.grid()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see, the prediction improves quite a bit when including the temporal derivative! But how should we interpret the beta-parameters? Well, usually people don't really interpret the temporal (and dispersion derivative) HRFs (unless they're interested in lag/width of the HRF), because most researchers are interesting in the activation/deactivation (the amplitude) of voxels in response to a stimulus, which corresponds to the beta-parameters associated with the canonical HRF. So, basically, the temporal (and dispersion) derivative(s) are only used to \"correct\" for deviations in terms of lag/shape from the canonical HRF!\n",
"\n",
"So, should you then always use a (gamma) basis set? People are quite divided on the topic of whether to use basis sets or a canonical HRF. In our experience, derivatives (e.g. in the gamma basis sets) offer little improvement over a canonical HRF in simple group-level analyses (in which you average over many participants; the topic of week 5/6!), but it doesn't hurt either (given that you have \"enough\" degrees of freedom)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **ToDo** (optional; 0 points): For gamma-based basis sets, the different components correlate with each other (especially the canonical HRF and its dispersion derivative). As such, these two predictors will \"compete\" for explained variance, which affects their parameter estimates and associated statistics. Because people are often only interested in the amplitude component of our basis set, they sometimes \"orthogonalize\" the HRF derivatives with respect to the canonical HRF predictor. Orthogonalization is a process in which a predictor is \"decorrelated\" from another (set of) predictors(s) (for more details on orthogonalization, see this excellent article). Orthogonalization amounts to regressing out the to-be-orthogalized predictor from the other predictor(s).\n",
"\n",
"In this ToDo, try orthogonalizing the canonical HRF predictor with respect to its temporal derivative. Using the variable `Xc` below (which contains just two predictors: the canonical HRF predictor and the temporal derivative predictor). Make sure to *replace* the temporal derivative predictor (i.e., second column) with the predictor with the variance related to the canonical HRF removed).\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "f74eed34b4cdb74efb3c9337ec57fd79",
"grade": false,
"grade_id": "cell-62ecf15e43102e4e",
"locked": false,
"schema_version": 3,
"solution": true,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Implement your ToDo here. '''\n",
"# First column: canonical HRF predictor, second column: temp. deriv predictor\n",
"Xc = X_tbs[:, 1:].copy()\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "871d83a99265e19c2016d074116a21ac",
"grade": true,
"grade_id": "cell-44d9654d6dc22086",
"locked": true,
"points": 0,
"schema_version": 3,
"solution": false,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_orthogonalization\n",
"test_orthogonalization(X_tbs, Xc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToDo** (5 points):\n",
" \n",
"Reanalyze the voxel signal with the separate conditions (like the last ToDo), but this time with a both the canonical HRF (`canonical_hrf`) and the associated temporal derivative (you can use the variable `tderiv_hrf`)! Calculate the beta-parameters for the voxel signal (i.e., the variable `voxel_signal`), MSE, and $R^2$. Store the MSE in a variable named `mse_gbf` and $R^2$ in a variable named `r2_gbf`. \n",
"\n",
"Please implement this assignment in \"steps\", such that we can test intermediate output:\n",
"1. Convolve the circle predictor (`predictor_circles`) and the squares predictor (`predictor_squares`) with the two HRF basis functions (canonical, temporal deriv.) separately, giving you 4 predictors, stack them together and add an intercept (make sure the intercept is the first column). Then, downsample your design matrix to the scale of you voxel signal. Store your downsampled design matrix in a variable named `X_gbf`; Note: the order of the columns should be: intercept, circles (canonical), circles (temp. deriv.), squares (canonical), squares (temp. deriv.). If you don't do this, automatic grading will fail and you won't get any points; (2 points)\n",
"2. Run linear regression (your DV is the variable `voxel_signal`) and store your betas in a variable named `betas_gbf`; (1 point)\n",
"3. Calculate R-squared and store it in a variable named `r2_gbf`; (1 point)\n",
"4. Calculate MSE and store it in a variable named `mse_gbf`; (1 point)\n",
"\n",
"Some tips:\n",
"- you can use the definitions of the HRFs from earlier (`canonical_hrf` and `tderiv_hrf`)\n",
"- make sure that your design-matrix has, eventually, 5 columns (intercept + 2 predictors x 2 conditions)\n",
"- don't forget to downsample your design matrix\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "127713d4d04b85ec21e0768fcd3966ee",
"grade": false,
"grade_id": "cell-aa9bd92a4d2e001f",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Step 1: convolve the predictors (don't forget to trim and downsample)!\n",
"# Hint: print the shape of your predictors after convolving, trimming, and downsampling - \n",
"# does this shape correspond to the number of datapoints of the experiment?\n",
"\n",
"# We have created the binary predictors for you already\n",
"predictor_circles = np.zeros(800)\n",
"predictor_circles[onsets_circles] = 1\n",
"\n",
"predictor_squares = np.zeros(800)\n",
"predictor_squares[onsets_squares] = 1\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "a8f1d95d7c01c028b2d1a89e21b56978",
"grade": true,
"grade_id": "cell-5eb3caddda7a3efd",
"locked": true,
"points": 2,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"\n",
"if 'X_gbf' not in dir():\n",
" msg = \"Could not find the variable 'X_gbf'; did you name it correctly?\"\n",
" raise ValueError(msg)\n",
"\n",
"try:\n",
" np.testing.assert_array_equal(X_gbf[:, 0], np.ones(X_gbf.shape[0]))\n",
"except AssertionError as e:\n",
" print(\"First column is not an intercept (vector of ones)!\")\n",
" raise(e)\n",
"\n",
"if X_gbf.shape[0] != 400:\n",
" msg = 'You probably forgot to trim and/or downsample ...'\n",
" raise ValueError(msg)\n",
"\n",
"from niedu.tests.nii.week_2 import test_canon_and_tderiv_design\n",
"test_canon_and_tderiv_design(predictor_circles, predictor_squares, canonical_hrf, tderiv_hrf, X_gbf)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "bdb7e66dad4ef64818900170ff51c25d",
"grade": false,
"grade_id": "cell-442653834fb15a12",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Step 2: run linear regression\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "5b421f148d4f0d72a42bb952432377c6",
"grade": true,
"grade_id": "cell-d6b3c4f4c4782bc4",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above steps. '''\n",
"from niedu.tests.nii.week_2 import test_canon_and_tderiv_glm\n",
"test_canon_and_tderiv_glm(X_gbf, voxel_signal, betas_gbf)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "0eeb7c8ea8f98aad475e7a015a6dbd62",
"grade": false,
"grade_id": "cell-8540ca90e7909c8c",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Step 3: calculate R-squared (and store it in a variable named r2_gbf)\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "77edaa7c8da5a51a04633e84dbd1985e",
"grade": true,
"grade_id": "cell-3499aa72400037eb",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_canon_and_tderiv_r2\n",
"test_canon_and_tderiv_r2(X_gbf, betas_gbf, voxel_signal, r2_gbf)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "9566534148c6b289e8ca12861c808058",
"grade": false,
"grade_id": "cell-2a274c1398b18d18",
"locked": false,
"schema_version": 3,
"solution": true
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"# Step 4: calculate MSE (and store it in a variable named mse_gbf)\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "4bfafa08146f7a7143bc1d3f726d34d3",
"grade": true,
"grade_id": "cell-3ce97583cc3720c2",
"locked": true,
"points": 1,
"schema_version": 3,
"solution": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"from niedu.tests.nii.week_2 import test_canon_and_tderiv_mse\n",
"test_canon_and_tderiv_mse(X_gbf, betas_gbf, voxel_signal, mse_gbf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From what we've showed so far, hopefully, you noticed that how linear regression is applied to model a voxel signal is not that much different from 'regular' data, except for the convolution/HRF part. At this moment, you already know 95% of how univariate analysis works! There are, however, still a couple of concepts we need to address, which we'll do next week: statistical inference of model parameters."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**ToDo** (3 points)\n",
"\n",
"For the last ToDo, let's do a short \"puzzle\". Below, we'll load a function, called `black_box`, that implements a linear regression model with the following functional form:\n",
"\n",
"\\begin{align}\n",
"y = \\beta_{0} + x_{1}\\beta_{1} + x_{2}\\beta_{2} + x_{3}\\beta_{3} \n",
"\\end{align}\n",
"\n",
"As you can see, it has four parameters (no error term!): $\\beta_{0}$ represents the intercept here and $\\beta_{1}$ up to $\\beta_{4}$ represent the parameters of the model's single predictors ($x_{1}$ up to $x_{3}$). The function `black_box` takes three inputs: `x1`, `x2`, and `x3`. The function outputs a (deterministic) value for $y$. So, you could use (\"query\") the function like this:\n",
"\n",
"`y_output = black_box(x1=10, x2=5, x3=2)`\n",
" \n",
"Now, your assignment is to, experimentally, figure out (\"reverse engineer\") the model's parameters $\\beta_{0}$, $\\beta_{1}$, $\\beta_{2}$, and $\\beta_{3}$. In other words, run the function with some inputs values and check the corresponding outputs. From those combinations of inputs and outputs, you can reconstruct the four different parameters. Once you figure out these betas, store them in the variables `beta_0`, `beta_1`, `beta_2`, and `beta_3`.\n",
"\n",
"Also, explain — concisely — how you figured out the answer in the text cell below the test-cell.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "3be5bc8702594d9e7da73c66e1b981d2",
"grade": false,
"grade_id": "cell-052c02873cce930f",
"locked": false,
"schema_version": 3,
"solution": true,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"from niedu.tests.nii.week_2 import black_box\n",
"# Implement your todo here!\n",
"\n",
"# YOUR CODE HERE\n",
"raise NotImplementedError()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"deletable": false,
"editable": false,
"nbgrader": {
"cell_type": "code",
"checksum": "297357c96c208b898040faa807ffa70f",
"grade": true,
"grade_id": "cell-fff9d4fa60b85aef",
"locked": true,
"points": 3,
"schema_version": 3,
"solution": false,
"task": false
},
"tags": [
"raises-exception",
"remove-output"
]
},
"outputs": [],
"source": [
"''' Tests the above ToDo. '''\n",
"for b in ['0', '1', '2', '3']:\n",
" \n",
" if not 'beta_%s' % b in dir():\n",
" raise ValueError(\"You didn't define the variable beta_%s.\" % b)\n",
"\n",
"from niedu.tests.nii.week_2 import test_black_box\n",
"test_black_box(beta_0, beta_1, beta_2, beta_3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"nbgrader": {
"cell_type": "markdown",
"checksum": "dba47eefb6f47462251c9336bae820fc",
"grade": true,
"grade_id": "cell-4ae7d1e241db3432",
"locked": false,
"points": 1,
"schema_version": 3,
"solution": true,
"task": false
}
},
"source": [
"YOUR ANSWER HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" **Tip!**\n",
" Before handing in your notebooks, we recommend restarting your kernel (*Kernel* → *Restart & Clear Ouput*) and running all your cells again (manually, or by *Cell* → *Run all*). By running all your cells one by one (from \"top\" to \"bottom\" of the notebook), you may spot potential errors that are caused by accidentally overwriting your variables or running your cells out of order (e.g., defining the variable 'x' in cell 28 which you then use in cell 15).\n",
"

"
]
}
],
"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.8.5"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": true,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 1
}