(《机器学习系统设计》第一章)
一、学习简单的Numpy、Scipy用法
Numpy:数组维数转换reshape()、对数组操作能传递到每一个元素、索引np.array()、修剪函数clip()、清洗~np.isnan()
Scipy工具包:
二、练习第一个(极小的)的机器学习应用
1.读取数据(一个月的web请求统计信息)
import scipy as sp
data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")
print(data[:10])
验证输出:
[[ 1.00000000e+00 2.27200000e+03]
[ 2.00000000e+00 nan]
[ 3.00000000e+00 1.38600000e+03]
[ 4.00000000e+00 1.36500000e+03]
[ 5.00000000e+00 1.48800000e+03]
[ 6.00000000e+00 1.33700000e+03]
[ 7.00000000e+00 1.88300000e+03]
[ 8.00000000e+00 2.28300000e+03]
[ 9.00000000e+00 1.33500000e+03]
[ 1.00000000e+01 1.02500000e+03]]
2.预处理和清洗数据
分为两个向量:(更多功能:索引(indexing)、切割(slicing)、迭代(iterating))
x = data[:,0]
y = data[:,1]
用~在逻辑上对数组取反,清洗掉无用项:
x = x[~sp.isnan(y)]
y = y[~sp.isnan(y)]
3.将数据用Matplotlib在散点图上展示:
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.title("Web Traffic over the last month")
plt.xlabel("Time")
plt.ylabel("Hits/hour")
plt.xticks([w*7*24 for w in range(10)],
['week %i'%w for w in range(10)])
plt.autoscale(tight=True)
plt.grid()
plt.show()
4.明确一下任务:
- 找到有噪数据背后真正模型
- 使用该模型预测未来
def error(f, x, y):
return sp.sum((f(x)-y)**2)
6.构建第一个模型:直线
fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full=True)
ployfit()返回参数,即fp1,res为残差
>>> print("Model parameters: %s" % fp1)
Model parameters: [ 2.59619213 989.02487106]
>>> print(residuals)
[ 3.17389767e+08]
所以,直线函数:f(x) = 2.59619213 * x + 989.02487106
然后依据这些参数创建模型函数
>>> f1 = sp.poly1d(fp1)
>>> print(error(f1, x, y))
317389767.34
绘图:
fx = sp.linspace(0,x[-1], 1000)
plt.plot(fx, f1(fx), linewidth=4)
plt.legend(["d=%i" % f1.order], loc="upper left")
plt.scatter(x,y)
plt.title("web traffic over the last month")
plt.xlabel("Time")
plt.ylabel("Hitshour")
plt.xticks([w * 7 * 24 for w in range(10)],
['week %i'%w for w in range(10)])
plt.autoscale(tight=True)
plt.grid()
plt.show()
print(data)
8.分别用2、3、10、100阶来构建模型,并计算误差:
二阶代码:
>>> f2p = sp.polyfit(x,y,2)
>>> print(f2p)
[ 1.05322215e-02 -5.26545650e+00 1.97476082e+03]
>>> f2 = sp.poly1d(f2p)
>>> print(error(f2, x, y))
179983507.878
从误差error中可以发现结束越高,误差越小。但观察10阶和100阶的图像可以发现震荡剧烈,即发生了“过拟合”。
然后在利用2、3阶对边界预测时效果非常差,因此需要从其他角度理解数据。
9.尝试训练出两条直线,以3.5周为拐点
inflection = 3.5 * 7 * 24
xa = x[:inflection]
ya = y[:inflection]
xb = x[inflection:]
yb = y[inflection:]
fa = sp.poly1d(sp.polyfit(xa, ya, 1))
fb = sp.poly1d(sp.polyfit(xb, yb, 1))
fa_error = error(fa, xa, ya)
fb_error = error(fb, xb, yb)
print("Error inflection=%d" % (fa_error + fb_error))
当1、2、3、10、53相比较时可看出高阶阶效果仍不好(图片来自网络),2阶预测效果最佳
10.训练与测试