matplotlib习题答案(仅供参考)

Exercise 11.1: Plotting a function
Plot the function    f(x) = sin2(− 2)ex2    over the interval [02]. Add proper axis labels, a title, etc.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2)
y = np.power(np.sin(x - 2), 2) * np.exp ( - x ** 2)
plt.plot(x, y)
plt.title("11.1")
plt.xlabel("X")
plt.ylabel("Y")
plt.xlim(0,2)
plt.show()
画出来的结果如图所示



Exercise 11.2: Data
Create a data matrix with 20 observations of 10 variables. Generate a vector with parameters. Then generate the response vector Xb+where is a vector with standard normally distributed variables. Now (by only using y and X), find an estimator for b, by solving = arg min Xb − y2.    Plot the true parameters and estimated parameters ˆb. See Figure for an example plot.

关于最小二乘解的解法,参加下图,转自知乎~


import matplotlib.pyplot as plt
import numpy as np
import numpy.matlib as npm
import numpy.linalg

#X = np.random.randn(20, 10)
#b = np.random.randn(1, 10)
#z = np.random.randn(20, 1)
X = npm.randn(20, 10)
b = npm.randn(10, 1) 
z = npm.randn(20, 1) 
y = X * b + z

x = np.linspace(0, 9, 10)
paramb, = plt.plot(x, b, 'rx', label = 'True coefficients')
B = np.linalg.solve(X.T * X, X.T* y)
#B = np.linalg.inv(X.T * X) * X.T * y
#B = np.linalg.pinv(X) * y
print(b)
print(B)
paramB, = plt.plot(x, B, 'bo', label = 'Estimated coefficients')
plt.ylabel('value')
plt.xlabel('index')
plt.title('Figure 1')
plt.legend(handles=[paramb, paramB])
plt.show()

得到的参数图如下所示,



Exercise 11.3: Histogram and density estimation
Generate a vector of 10000 observations from your favorite exotic distribution. Then make a plot that shows a histogram of (with 25 bins), along with an estimate for the density, using a Gaussian kernel density estimator (see scipy.stats). See Figure for an example plot.

from scipy import stats
import numpy as np
import matplotlib.pyplot as plt

A = np.random.normal(size = 10000)
n, bins, patches = plt.hist(A, bins = 25, edgecolor='black', density=1)
plt.plot(bins, stats.norm.pdf(bins))
plt.title('$\mu=0$, $\sigma=1$')
plt.show()

画出来的图片如下所示,




猜你喜欢

转载自blog.csdn.net/weixin_38224302/article/details/80501139