Exercise 11.1: Plotting a function
Plot the function y=sin2(x−2)e−x2 y = s i n 2 ( x − 2 ) e − x 2 over the interval [0, 2]. Add proper axis labels, a title, etc.
编写代码如下:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True) #show grid
def plot_a_fun():
x = np.linspace(0, 2, 100)
print(x)
y1 = np.sin(x - 2) ** 2
y2 = np.exp(-(x ** 2))
y = y1 * y2 #get y value
plt.plot(x, y, label='$y=sin^2(x-2)e^{-x^2}$')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend() #show legend
plt.show()
plot_a_fun()
运行结果如下:
Exercise 11.2: Data
Create a data matrix X with 20 observations of 10 variables. Generate a vector b with parameters Then generate the response vector y=Xb+z y = X b + z where z is a vector with standard normally distributed variables. Now (by only using y and X), find an estimator for b, by solving
Plot the true parameters b and estimated parameters b. See Figure 1 for an example plot.
编写代码如下:
def least_square():
X = np.random.random((20, 10)) * 10 #create X, b, z
b = np.random.random(10) * 6 - 3
z = np.random.randn(20)
y = X.dot(b) + z #create y
b1 = np.linalg.lstsq(X, y, rcond=-1)[0] #get least square solution of Xb = y
index = np.linspace(0, 9, 10)
plt.plot(index, b, 'r*', label="True coefficients")
plt.plot(index, b1, 'bo', label='Estimated coefficients')
plt.hlines(0, 0, 9, colors='k', linestyles='solid') #show middle line
plt.tight_layout()
plt.legend()
plt.savefig('p2.png')
plt.show()
least_square()
运行结果如下:
Exercise 11.3: Histogram and density estimation
Generate a vector z of 10000 observations from your favorite exotic distribution. Then make a plot that shows a histogram of z (with 25 bins), along with an estimate for the density, using a Gaussian kernel density estimator (see scipy.stats). See Figure 2 for an example plot.
编写代码如下:
def density_estimation():
x = np.random.normal(60, 10, 10000)
sns.distplot(x, bins=25, kde=True) #kde=True -- using Gaussian kernel density estimator
plt.savefig('p3.png')
plt.show()
density_estimation()
运行结果如下: