Exercise 11.1: Plotting a function
Plot the function
代码:
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,2,500)
y=pow(np.sin(x-2),2)*np.exp(-np.power(x,2))
plt.plot(x,y)
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
plt.title("$f(x)=sin^2(x-2)*exp(-x^2)$")
plt.show()
结果:
Exercise 11.2: Data
Create a data matrix X with 20 observations of 10 variables.
代码:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import leastsq
def func(p, x):
return np.matmul(x, p)
def error(p, x, y):
return func(p, x) - y
p0 = np.random.random(10, )
X = np.random.random((20, 10))
b = np.array([10,40,30,20,50,60,95,80,70,100])
z = np.random.standard_normal(20, )
y = np.matmul(X, b) + z
Para = leastsq(error, p0, args=(X, y))
x=np.linspace(1,10,10)
plt.plot(x,b,'.',label='True cofficients')
plt.plot(x,Para[0],'x',label='Estimated coefficients')
plt.xlabel('$index$')
plt.ylabel('value')
plt.legend(loc='lower right')
plt.show()
print("X:\n", X)
print("b:\n", b)
print("z:\n", z)
结果:
对参数拟合效果非常好
Exercise 11.3: Histogram and density estimation
代码:
from scipy.stats.kde import gaussian_kde
from scipy.stats import norm
from numpy import linspace
import matplotlib.pyplot as plt
samp = norm.rvs(size=10000)
my_pdf = gaussian_kde(samp)
x = linspace(-5,5,100)
plt.plot(x,my_pdf(x,),)
plt.hist(samp,density=1,alpha=.3,bins=25)
plt.show()
结果: