matplotlib的入门练习题

时间:2023-02-22 23:58:48

Exercise 11.1: Plotting a function

Plot the function f ( x ) = s i n 2 ( x 2 ) e x 2 over the interval [0,2]. Add proper axis labels, a title, etc.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
X = np.random.rand(20, 10) * 10
b = np.random.rand(10)
z = np.random.normal(size=(20,))
y = X.dot(b) + z
b_ = np.array(np.linalg.lstsq(X,y, rcond=-1)[0])

plt.plot(b, Marker='x', LineStyle='none', label='b')
plt.plot(b_, Marker='o', LineStyle='none', label=r'$\hat{b}$')
plt.legend()
plt.show()

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 where z is a vector with standard normally distributed variables.
Now (by only using y and X), find an estimator for b, by solving

(1) b ^ = arg min b     X b y 2
Plot the true parameters b and estimated parameters b ^ . See Figure 1 for an example plot.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
X = np.random.rand(20, 10) * 10
b = np.random.rand(10)
z = np.random.normal(size=(20,))
y = X.dot(b) + z
b_ = np.array(np.linalg.lstsq(X,y, rcond=-1)[0])

plt.scatter(b, label='b')

plt.scatter(b_, label=r'$\hat{b}$')
plt.legend()
plt.show()

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.

z = np.random.normal(size=(10000,))
sns.distplot(z, bins=25, kde=True)
plt.show()