Plot the function
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,2,30)
y = (np.sin(x-2)**2)*np.exp(-(x**2))
plt.xlabel('x')
plt.ylabel('y')
plt.title('$x=f(x)=\sin^2(x-2)e^{-x^2}$')
plt.plot(x,y)
plt.show()
Create a data matrix X X with 20 observations of 10 variables. Generate a vector b b with parameters Then
generate the response vector y=Xb+z y = X b + z where z z is a vector with standard normally distributed variables.
Now (by only using y y and X X ), find an estimator for b b , by solving
scipy
的最小二乘函数 leastsq
计算最小二乘解 b^ b ^ import numpy as np
import matplotlib.pyplot as plt
X = (np.random.random([20,10])-0.5)*2 #生成(20,10)的随机数矩阵,范围在(-1,1)
b = (np.random.random([10])-0.5)*4 #生成(10,)的随机数向量,矩阵相乘会自动变为纵向量
z = np.random.randn(20) #生成(20,)的服从标准正态分布的向量
y = np.dot(X,b)+z #计算得到(20,)的向量
res = np.linalg.lstsq(X,y)[0] #计算线性方程组的最小二乘解的基本方法,X和y组成观察值,返回系数向量b
x = range(0,10)
plt.ylim(-2.5,2.5)
plt.xlim(-0.5,9.5)
plt.scatter(x,res,label='Estimated coefficients')
plt.scatter(x,b,marker='x',label=('True coefficients'))
plt.legend()
plt.hlines(0,-0.5,9.5) #水平分割线
plt.xticks(range(0,10))
plt.plot()
Generate a vector z z of 10000 observations from your favorite exotic distribution. Then make a plot that
shows a histogram of z 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.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
data = np.random.binomial(100,0.2,10000)
x = np.linspace(0,100,100)
kernel = stats.gaussian_kde(data)
kde = kernel.evaluate(x)
plt.hist(kernel.dataset[0],normed='True',bins=25)
plt.plot(x,kde)
plt.show()