Exercise 11.1: Plotting a function
import matplotlib.pyplot as plt
import numpy
x = numpy.linspace(0, 2, 10000)
y = [(numpy.sin((i - 2) * numpy.exp(- i ** 2))) ** 2 for i in x]
plt.plot(x, y)
plt.title('Plotting a function')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
效果如图:
Exercise 11.2: Data
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gausshyper
X = []
for i in range(0, 10):
x = np.random.normal(size=20)
X.append(x)
X = np.mat(X)
z = np.random.normal(size=10)
y1 = []
y2 = []
for i in range(0, 20):
b = np.random.normal(size=20)
y2.append(np.argmin(b))
Xb = np.dot(X, b.reshape(20, 1)).reshape(1, 10)
y1.append(np.argmin(Xb))
x = [i for i in range(0, 20)]
fig, ax1= plt.subplots(1, 1)
p1 = ax1.scatter(x, y1, c='r', marker='o')
p2 = ax1.scatter(x, y2, c='b', marker='v')
plt.legend([p1, p2], ['estimated', 'true'], loc='upper right', scatterpoints=1)
plt.show()
效果如图:
Exercise 11.3: Histogram and density estimation
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gausshyper
fig, ax = plt.subplots(1, 1)
a, b, c, z = 13.8, 3.12, 2.51, 5.18
mean, var, skew, kurt = gausshyper.stats(a, b, c, z, moments='mvsk')
x = np.linspace(gausshyper.ppf(0.01, a, b, c, z), gausshyper.ppf(0.99, a, b, c, z), 100)
ax.plot(x, gausshyper.pdf(x, a, b, c, z), 'r-', lw=5, alpha=0.6, label='gausshyper pdf')
rv = gausshyper(a, b, c, z)
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
vals = gausshyper.ppf([0.001, 0.5, 0.999], a, b, c, z)
np.allclose([0.001, 0.5, 0.999], gausshyper.cdf(vals, a, b, c, z))
r = gausshyper.rvs(a, b, c, z, size=10000)
ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
ax.legend(loc='best', frameon=False)
plt.show()
效果如图: