(《機器學習系統設計》第一章)
一、學習簡單的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.訓練與測試