Exercise 1: Plotting a function
题意
题解
numpy.linspace 生成一段区间内均匀分布的点。用这个函数生成横坐标。
numpy 提供了很多数学函数,这里能用到的有 numpy.sin, numpy.power, numpy.exp, numpy.negative。
matplotlib.pyplot 提供了绘制图像的函数 plot,也提供了设置横坐标名、纵坐标名、标题的函数 xlabel, ylabel, title。
from numpy import linspace, power, sin, negative, exp from matplotlib import pyplot x = linspace(0, 2, 100) y = power(sin(x - 2), 2) * exp(negative(power(x, 2))) pyplot.plot(x, y) pyplot.ylabel('y') pyplot.xlabel('x') pyplot.title('y = $[sin^2(x-2)]e^{-x^2}$') pyplot.show()
Exercise 2: Data
题意
题解
10个变量,每个变量有20个观测值,X 是一个 20 * 10 的矩阵,b 就应该是一个 10 * 1 的矩阵,z 是一个 20 * 1的矩阵。
numpy.linalg.lstsq 函数能够得到最小二乘解。
简单起见,X ,b ,z 都随机生成。
from numpy import linalg, random, linspace, dot from matplotlib import pyplot X = random.randn(20, 10) b = random.random((10, 1)) * 2 - 1 z = random.randn(20, 1) y = dot(X, b) + z b_est, residuals, rank, s = linalg.lstsq(X, y, None) x = linspace(0, 9, 10) pyplot.plot(x, b, 'rx', label='True coefficients') pyplot.plot(x, b_est, 'bo', label='Estimated coefficients') pyplot.xlabel('index') pyplot.ylabel('value') pyplot.legend() # 设置横纵坐标显示范围 pyplot.xlim((-1, 10)) pyplot.ylim((-1, 1)) # 设置横坐标刻度 pyplot.gca().set_xticks(x) pyplot.show()
Exercise 3: Histogram and density estimation
题意
题解
没搞懂 scipy.stats 怎么用,于是用另一个库 seaborn,seaborn.distplot 可以绘制要求的图像。
from numpy import random from matplotlib import pyplot import seaborn z = random.randn(10000) ax = seaborn.distplot(z, bins=25, kde=True) pyplot.show()