## Multiple Features

Linear regression with multiple variables is also known as "**multivariate linear regression**".

We now introduce notation for equations where we can have any number of input variables.

- \(x^{(i)}_j\) = value of feature j in the \(i^{th}\) training example
- \(x^{(i)}\) = the column vector of all the feature inputs of the \(i^{th}\) training example
- \(m\) = the number of training examples
- \(n\) = \(∣x^{(i)}∣\) (the number of features)

Now define the multivariable form of the hypothesis function as follows, accomodating these multiple features:

\[h_θ(x)=θ_0+θ_1x_1 + θ_2x_2 + θ_3x_3 +⋯+ θ_nx_n\]

In order to have little intuition about this function, we can think about \(θ_0\) as the basic price of a house, \(θ_1\) as the price per square meter, \(θ_2\) as the price per floor, etc. \(x_1\) will be the number of square meters in the house, \(x_2\) the number of floors, etc.

Using the definition of matrix multiplication, our **multivariable hypothesis function** can be concisely represented as:

\[ h_θ(x)= \begin{bmatrix} θ_0 & \cdots & θ_n \\ \end{bmatrix} \begin{bmatrix} x_0\\ \\ \vdots \\ \\ x_n \\ \end{bmatrix} = θ^{T}x\]

This is a vectorization of our hypothesis function for one training example; see the lessons on vectorization to learn more.

[**Note**: So that we can do matrix operations with theta and x, we will set \(x^{(i)}_0 = 1\), for all values of \(i\). This makes the two vectors \(\theta\) and \(x^{(i)}\) match each other element-wise (that is, have the same number of elements: n+1).]

Now we can collect all *m* training examples each with *n* features and record them in an **n+1 by m** matrix. In this matrix we let the value of the subscript (feature) also represent the row number (except the initial row is the "zeroth" row), and the value of the superscript (the training example) also represent the column number, as shown here: \[X = \begin{bmatrix}
x^{(1)}_0 & x^{(2)}_0 & \cdots & x^{(m)}_0 \\
x^{(1)}_1 & x^{(2)}_1 & \cdots & x^{(m)}_1 \\
& & \vdots & \\
x^{(1)}_n & x^{(2)}_n & \cdots & x^{(m)}_n
\end{bmatrix} =
\begin{bmatrix}
1 & 1 & \cdots & 1 \\
x^{(1)}_1 & x^{(2)}_1 & \cdots & x^{(m)}_1 \\
& & \vdots & \\
x^{(1)}_n & x^{(2)}_n & \cdots & x^{(m)}_n
\end{bmatrix}
\]

Notice above that the first column is the first training example (like the vector above), the second column is the second training example, and so forth.

Now we can define \(h_θ(X)\) as a row vector that gives the value of \(h_θ(x)\) at each of the *m* training examples: \[hθ(X)=\begin{bmatrix}
θ_0x^{(1)}_0+θ_1x^{(1)}_1+...+θ_nx^{(1)}_n & \cdots & θ_0x^{(m)}_0+θ_1x^{(m)}_1+...+θ_nx^{(m)}_n \\
\end{bmatrix}
\]

## Cost function

For the parameter vector \(θ\) (of type \(R^{n+1}\) or in \(R^{(n+1)×1}\)), the cost function is:

\[J(\theta) = \frac{1}{2m}\sum^{m}_{i = 1}(h_\theta(x^{(i)}) - y^{(i)})^2\]

The vectorized version is:

\[J(\theta) = \frac{1}{2m}(X\theta - \overrightarrow{y})^T(X\theta - \overrightarrow{y})\]

Where \(\overrightarrow{y}\) denotes the vector of all *y* values, \(X\) represent a matrix of training examples \(x^{(i)}\) stored **row-wise**.

## Gradient Descent for Multiple Variables

The gradient descent equation itself is generally the same form; we just have to repeat it for our '**n**' features:

**repeat until convergence:{** \[\theta_0 := \theta_0 - \alpha\frac{1}{m}\sum^{1}_{m}(h_\theta(x^{(i)}) - y^{(i)}) x^{(i)}_0\] \[\theta_1 := \theta_1 - \alpha\frac{1}{m}\sum^{1}_{m}(h_\theta(x^{(i)}) - y^{(i)}) x^{(i)}_1\] \[\theta_2 := \theta_2 - \alpha\frac{1}{m}\sum^{1}_{m}(h_\theta(x^{(i)}) - y^{(i)}) x^{(i)}_2\] \[...\] **}**

In other words:

**repeat until convergence:{** \[\theta_j := \theta_j - \alpha\frac{1}{m}\sum^{1}_{m}(h_\theta(x^{(i)}) - y^{(i)}) x^{(i)}_j\] **for \(j\) \(:=\) \(0\)...\(n\)** **}**

## Matrix Notation

The Gradient Descent rule can be expressed as:

\[\theta := \theta - \alpha \bigtriangledown J(\theta)\]

Where \(\bigtriangledown J(\theta)\) is a column vector of the form:

\[\bigtriangledown J(\theta) = \begin{bmatrix} \frac{\partial J(\theta)}{\partial \theta_0}\\ \frac{\partial J(\theta)}{\partial \theta_1}\\ \vdots \\ \frac{\partial J(\theta)}{\partial \theta_n}\\ \end{bmatrix}\]

The j-th component of the gradient is the summation of the product of two terms: \[\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m}\sum^m_{i = 1}(h_\theta(x^{(i)}) - y^{(i)}) x^{(i)}_j\]

Sometimes, the summation of the product of two terms can be expressed as the product of two vectors.

Here, the term \(x^{(i)}_j\) represents the \(m\) elements of the j-th column \(\overrightarrow {x_j}\) (j-th feature \(\overrightarrow {x_j}\)) of the training set \(X\).

The other term \((h_\theta(x^{(i)}) - y^{(i)})\) is the vector of the deviations between the predictions \(h_\theta(x^{(i)})\) and the true values \(y^{(i)}\) . Re-writing \(\frac{\partial J(\theta)}{\partial \theta_j}\) , we have: \[\frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m}\overrightarrow{x_j}^T(X\theta - \overrightarrow{y})\] \[\bigtriangledown J(\theta) = \frac{1}{m}X^T(X\theta - \overrightarrow{y})\]

Finally, the matrix notation (vectorized) of the Gradient Descent rule is: \[\theta := \theta - \frac{\alpha}{m}X^T(X\theta - \overrightarrow{y})\]

## Feature Normalization

We can speed up gradient descent by having each of our input values in roughly the same range. This is because \(\theta\) will descend quickly on small ranges and slowly on large ranges, and so will oscillate inefficiently down to the optimum when the variables are very uneven.

The way to prevent this is to modify the ranges of our input variables so that they are all roughly the same. Ideally: \(-1 \le x_i \le 1\) or \(-0.5 \le x_i \le 0.5\)

These aren't exact requirements; we are only trying to speed things up. The goal is to get all input variables into roughly one of these ranges, give or take a few.

Two techniques to help with this are **feature scaling** and **mean normalization**. * Feature scaling involves dividing the input values by the range (i.e. the maximum value minus the minimum value) of the input variable, resulting in a new range of just 1. * Mean normalization involves subtracting the average value for an input variable from the values for that input variable, resulting in a new average value for the input variable of just zero.

To implement both of these techniques, adjust your input values as shown in this formula: \[x_i := \frac{x_i - \mu_i}{s_i}\]

Where \(\mu_i\) is the **average** of all the values and \(s_i\) is the maximum of the range of values *minus* the minimum or is the *standard deviation*.

**Example**: \(x_i\) is housing prices in range 100-2000. Then, \(x_i := \frac{price - 1000}{1900}\), where 1000 is the average price and 1900 is the maximum (2000) minus the minimum (100).

## Gradient Descent Tips

**Debugging gradient descent** Make a plot with **number of iterations** on the x-axis. Now plot the cost function, \(J(\theta)\) over the number of iterations of gradient descent. If \(J(\theta)\) ever increases, then you probably need to decrease \(\alpha\).

**Automatic convergence test** Declare convergence if \(J(\theta)\) decreases by less than \(\epsilon\) in one iteration, where \(\epsilon\) is some small value such as \(10^{-3}\). However in practice it's difficult to choose this threshold value.

It has been proven that if learning rate \(\alpha\) is sufficiently small, then \(J(\theta)\) will decrease on every iteration. *Andrew Ng* recommends decreasing \(\alpha\) by multiples of 3.

## Features and Polynomial Regression

We can improve our features and the form of our hypothesis function in a couple different ways.

We can **combine multiple features into one**. For example, we can combine \(x_1\) and \(x_2\) into a new feature \(x_3\) by taking \(x_1 \cdot x_2\).

### Polynomial Regression

Our hypothesis function need not be linear (a straight line) if that does not fit the data well.

We can **change the behavior or curve** of our hypothesis function by making it a quadratic, cubic or square root function (or any other form).

For example, if our hypothesis function is \(h_\theta(x) = \theta_0 + \theta_1x_1\) then we can simply **duplicate** the instances of \(x_1\) to get the quadratic function \(h_\theta(x) = \theta_0 + \theta_1x_1 + \theta_2x_1^2\) or the cubic function \(h_\theta(x) = \theta_0 + \theta_1x_1 + \theta_2x_1^2 + \theta_3x_1^3\)

In the cubic version, we have created new features \(x_2\) and \(x_3\) where \(x_2 = x_1^2\) and \(x_3 = x_1^3\).

To make it a square root function, we could do: \(h_\theta(x) = \theta_0 + \theta_1x_1 + \theta_2\sqrt{x_1}\)

One important thing to keep in mind is, if you choose your features this way then **feature scaling** becomes very important.

eg. if \(x_1\) has range 1 - 1000 then \(x_1^2\) range of becomes 1 - 1000000 and that of \(x_1^3\) becomes 1 - 1000000000

## Normal Equation

The "normal equation" is a version of finding the optimum **without iteration**.

The proof for this equation requires knowledge of linear algebra and is fairly involved, so you do not need to worry about the details.

\[\theta = (X^TX)^{-1}X^Ty\]

There is **no need to do feature scaling** with the normal equation.

The following is a comparison of gradient descent and the normal equation: | Gradient Descent | Normal Equation | | :--- | :--- | | Need to choose \(\alpha\) | No need to choose \(\alpha\) | | Needs many iterations | No need to iterate | | Works well when n is large | Slow if n is very large |

With the normal equation, computing the inversion has complexity \(O(n^3)\). So if we have a very large number of features, the normal equation will be slow. In practice, according to *A. Ng*, when **n** exceeds **10,000** it might be a good time to go from a normal solution to an iterative process.

### Normal Equation Demonstration

- \(\theta\) is a \((n+1)\) x \(1\) matrix
- \(X\) is a \(m\) x \((n+1)\) matrix so \(X^T\) is a \((n+1)\) x \(m\) matrix
- \(\overrightarrow{y}\) is a \(m\) x \(1\) vector

\(X\theta = \overrightarrow{y}\) The point is to inverse \(X\) , but as \(X\) is not a square matrix we need to use \(X^T\) to have a square matrix \((X^T)X\theta = (X^T)\overrightarrow{y}\)

Associative matrix multiplication \((X^TX)\theta = X^T\overrightarrow{y}\) Assuming \((X^TX)\) invertible \(\theta = (X^TX)^{-1}X^T\overrightarrow{y}\)

### Normal Equation Noninvertibility

When implementing the normal equation in octave we want to use the `pinv`

function rather than `inv`

.

\(X^TX\) may be **noninvertible**. The common causes are: * Redundant features, where two features are very closely related (i.e. they are linearly dependent) * Too many features (e.g. \(m \le n\)). In this case, delete some features or use "**regularization**" (to be explained in a later lesson).

Solutions to the above problems include deleting a feature that is linearly dependent with another or deleting one or more features when there are too many features.