在完成作业之前,先引入需要用到的库
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
题目1:
代码:
x = np.linspace(0,10,1000)
y = np.power(np.sin(x - 2),2) * np.exp(-1 * x * x)
plt.plot(x,y,'r-',label = '$sin2(x-2)e-x2$')
plt.xlim((0,2))
plt.xlabel('my x label')
plt.ylabel('my y label')
plt.title('my func')
plt.legend()
plt.show()
运行结果:
题目2:
代码:
X = np.random.randint(0, 100, size=(20,20))
b = np.random.randint(10, size=(20, 1))
z = [list(np.random.normal(0, 1, 1)) for _ in range(20)]
y = X.dot(b) + z
Q, R = np.linalg.qr(X)
bn = np.linalg.inv(R).dot(Q.T).dot(y)
plt.plot(b,'o')
plt.plot(bn,'or')
plt.title('Parameter plot')
plt.legend(['b','b^'])
plt.show()
这道题直接对欧几里得范数求解,但其实转化成欧几里得范数的平方求解会更加的简单,因为可以通过对X矩阵进行QR分解来解决问题。
运行结果:
题目3:
代码:
x = np.random.randn(1000)
bars = np.linspace(-4,4,100)
#fig,(ax1,ax2) = subplot(1,2,figsize = (5,4))
plt.hist(x,bins = 25,density = 1,color = 'b')
kernel = stats.gaussian_kde(x)
kde = kernel.evaluate(bars)
plt.plot(bars,kde,label = 'kde', color = 'r')
plt.title('Gaussian kernel estimator')
plt.show()
运行结果: