高级编程技术(Python)作业14

Exercises for Matplotlib
Exercise 11.1
Solution:

import matplotlib.pyplot as plt
import numpy as np


fig, ax = plt.subplots(1, 1, figsize=(5, 4))

x = np.linspace(0, 2, 1000)

y = np.power(np.sin(x-2), 2) * np.power(np.e, -np.power(x, 2))
# y = (np.sin(x-2) ** 2) * (np.e ** (-x ** 2))
ax.plot(x, y)
ax.set_xlim((0, 2))
ax.set_ylim((0, 1))
ax.set_xlabel("x-axis")
ax.set_ylabel("y-axis")
ax.set_title("Figure for Exercise 11.1")

plt.show()

Output:
Figure for 11.1
Exercise 11.2
Figure 1

Solution:

import matplotlib.pyplot as plt
import numpy as np


X = np.random.rand(20, 10)
b = np.random.rand(10, 1)
z = np.random.standard_normal((20, 1))
y = X @ b + z

_b = np.linalg.lstsq(X, y, rcond=None)[0]

index = np.linspace(0, 9, 10)
fig, ax = plt.subplots()
plt.axhline(0, 0, 9, c='grey', alpha=0.2)
true_b, = ax.plot(index, b, 'bo')
est_b, = ax.plot(index, _b, 'rx')
plt.legend([true_b, est_b], ['True coefficients', 'Estimated coefficients'])
ax.set_xlabel('index')
ax.set_ylabel('value')
ax.set_xlim((0, 9))
ax.set_ylim((-2.0, 2.0))
ax.set_title('Figure for Exercise 11.3')
plt.show()

Output:
Figure for Exercise 11.2
注释:
这个题目的意思就是用最小二乘法求出一个新的向量_b和之前的向量b进行比较,最小二乘法在numpy里面是有实现的,我花费了大量时间自己去写最小二乘法效果并不是很好,查阅了资料发现自己完全是在浪费时间。。
稍微介绍一下最小二乘函数:
numpy.linalg.lstsq()的第一个参数就是题目中的X,第二个参数就是题目中的y,rcond是用于设置特征值的取值范围的,不想改变特征值就让其设置为None。
返回的值总共有四个,第一个就是所求出来的新的向量_b,于是我们在中括号[0]调用它
题目中的图例中的图案显示了两次,虽然我觉得可能是印刷问题,但是我也没有找到能跟它一样显示两次的方法。

Exercise 11.3
Figure 2

Solution:

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np


data = np.random.standard_normal((10000, ))
bin_num = 25
n, bins, patches = plt.hist(data, bin_num, normed=1, facecolor='blue')
# add a 'best fit' line
y = mlab.normpdf(bins, 0, 1)
plt.plot(bins, y, c='red', ls="--")
plt.title("Figure for Exercise 11.3")
plt.show()

Output:
Figure for Exercise 11.3
注释:
此处使用mlab库为我们的图片绘制出一条标准正态分布的曲线,mlab库有着大量的和matlab语法相似的语句可以供我们使用。
在plt.hist()中的normed一定要设置为1令密度函数面积之和为1,这样才能正确画出上面所说的那条标准正态函数的曲线。虽然我查阅了网络上说normed的默认值就是1,但是在我没有设置的时候曲线并不能正确绘制。
并且在绘制这条曲线的时候计算机将会给出以下警告:

UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
  warnings.warn("The 'normed' kwarg is deprecated, and has been "

暂时不是很明白这个警告的意思。

猜你喜欢

转载自blog.csdn.net/weixin_38311046/article/details/80474553