# Ex 11-1
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
x = np.arange(0, 2.01, 0.01)
y = np.sin((x-2) * np.exp(-x**2)) ** 2
plt.plot(x, y)
plt.title("Ex 11-1")
plt.xlabel("X")
plt.ylabel("Y")
plt.axis([0, 2.1, 0, 1.2])
plt.show()
输出:
# Ex 11-2
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
# Generate a data matrix with 20 ovservations of 10 variables
x = np.random.rand(20, 10)
#Generate a vector with 10 elements
b = np.random.rand(10)
#Generate a error vector with 20 elements,
#which follow Gauss distribution with mu = 0, sigma^2 = 0.04
z = np.random.normal(0, 0.04, 20)
y = x.dot(b) + z
# Least square method to approximate b
apprx_b = np.dot(np.dot(np.linalg.inv(np.dot(x.T, x)), x.T), y)
plt.plot(b, 'ro', apprx_b, 'bx')
plt.legend(["Real", "estimate"])
plt.show()
输出:
# Ex 11-3
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# Generate a vector z following Gauss distribution
z = np.random.normal(size = 10000)
n, bins, patches = plt.hist(z, bins = 25, edgecolor = 'black', \
color = 'blue', density = True)
plt.plot(bins, stats.norm.pdf(bins, loc = 0, scale = 1.0))
plt.text(-3, .25, r'$\mu=0.0,\ \sigma=1.0$')
plt.show()