
上QQ阅读APP看书,第一时间看更新
Getting ready
The data for Loss, theta0, theta1, and theta (optimal values of theta0 and theta1 that give the lowest error) are taken from one of the regression problems for plotting the contour plot. If theta0 and theta1 are vectors of size 1 x n, then the Loss will be in the form of an n x n matrix.
Import the required libraries. We will introduce one more library for color mapping from Matplotlib:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm
We also need to understand the concept of a mesh grid, since the contour, surface, and stream plots also use this concept:
- A mesh grid is a grid in a geometric space, derived from two vectors. Each data item in the vectors acts as a coordinate, and a combination of coordinates from the two vectors form points in a 2D geometric space. The area spread by all possible combinations of these vector coordinates is defined in the form of a mesh grid, for example:
- x = [-3.0, 0., 3.0] and y = [-2.0, 2.0]. Vector x has three data points and vector y has two. Hence, we will have total of six points (3 * 2) in 2D geometric space, and those six points are (-3.0, -2), (-3.0, 2.0), (0., -2.0), (0., 2.0), (3.0, -2.0), and (3.0, 2.0). Now, these six points and 12 data items (6 * 2) are again represented as two matrices x and y, where the following applies:
- X = [[-3.0, 0., 3.0], [-3.0, 0., 3.0]], a 2 x 3 matrix (the number of rows is equal to the length of Y), and Y = [[-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0]] a 3 x 2 matrix (the number of rows is equal to the length of X). NumPy has a function, np.meshgrid(x, y), used to create these X and Y matrices using x and y vectors. This is what we will use for all our requirements.
- x = [-3.0, 0., 3.0] and y = [-2.0, 2.0]. Vector x has three data points and vector y has two. Hence, we will have total of six points (3 * 2) in 2D geometric space, and those six points are (-3.0, -2), (-3.0, 2.0), (0., -2.0), (0., 2.0), (3.0, -2.0), and (3.0, 2.0). Now, these six points and 12 data items (6 * 2) are again represented as two matrices x and y, where the following applies: