11.1
代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100)
y = (np.sin(x-2) ** 2)*np.exp(-x**2)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('ex11.1')
plt.show()
结果:
11.2
代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
X = np.random.randn(20, 10)
z = np.random.randn(20, 1)
b = np.random.randn(10, 1)
y = np.dot(X, b) + z
def err(b, X, y):
b = b.reshape(10, 1)
return (np.dot(X, b)-y).reshape(-1)
b_ = leastsq(err, b, args = (X,y))[0]
x = np.arange(0,10)
l1 = plt.plot(x, b, 'x')
l2 = plt.plot(x, b_, '.')
plt.legend(['True coefficients', 'Estimated coefficients'])
plt.xlabel('index')
plt.ylabel('value')
plt.title('Parameter plot')
plt.show()
结果:
先生成几个变量,然后调用最小二乘函数(可以看到题目中的等式刚好是文档中说明的函数)
文档:https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html
11.3
代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
z = np.random.normal(0, 4, size = 10000)
kde = stats.gaussian_kde(z)
x = np.linspace(-10, 10, 200)
kdepdf = kde.evaluate(x)
plt.hist(z, bins = 25, density = True, color = 'b')
plt.plot(x, kdepdf, color = 'r')
plt.title('ex11.3')
plt.show()
结果:
文档说明:https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.gaussian_kde.html