當前位置:
首頁 >
4.7 程序示例--算法诊断-机器学习笔记-斯坦福吴恩达教授
發布時間:2025/4/5
24
豆豆
生活随笔
收集整理的這篇文章主要介紹了
4.7 程序示例--算法诊断-机器学习笔记-斯坦福吴恩达教授
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序示例–算法診斷
我們手頭有一份大壩水的流量與水位關系的數據,首先我們將其劃分為訓練集、交叉驗證集和測試集:
# coding: utf-8 # algorithm_analysis/diagnose.py """算法診斷 """ import linear_regression import numpy as np from scipy.io import loadmat import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeaturesdata = loadmat('data/water.mat') ##### # 數據集劃分 ##### # 訓練集 X = np.mat(data['X']) # 為X添加偏置 X = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) y = np.mat(data['y']) # 交叉驗證集 Xval = np.mat(data['Xval']) Xval = np.concatenate((np.ones((Xval.shape[0], 1)), Xval), axis=1) yval = np.mat(data['yval']) # 測試集 Xtest = np.mat(data['Xtest']) Xtest = np.concatenate((np.ones((Xtest.shape[0], 1)), Xtest), axis=1) ytest = np.mat(data['ytest'])接著,我們會使用訓練集來獲得線性回歸的擬合曲線,并且觀測隨樣本大小 mmm 變化的學習曲線:
# algorithm_analysis/diagnose.py def diagnoseLR():"""線性回歸診斷"""initTheta = np.mat(np.ones((X.shape[1], 1)))result, timeConsumed = linear_regression.gradient(X, y, rate=0.001, maxLoop=5000, epsilon=0.1, initTheta=initTheta)theta, errors = result# 繪制擬合成果Xmin = X[:, 1].min()Xmax = X[:, 1].max()ymax = y[:, 0].max()ymin = y[:, 0].min()fitX = np.mat(np.linspace(Xmin, Xmax, 20).reshape(-1, 1))fitX = np.concatenate((np.ones((fitX.shape[0], 1)), fitX), axis=1)h = fitX * thetaplt.xlim(Xmin, Xmax)plt.ylim(ymin, ymax)# 繪制訓練樣本plt.scatter(X[:, 1].flatten().A[0], y[:, 0].flatten().A[0],marker='x',color='r', linewidth=2)# 繪制擬合曲線plt.plot(fitX[:, 1], h, color='b')plt.xlabel('Change in water level(x)')plt.ylabel('Water flowing out of the dam(y)')plt.show()# 繪制隨樣本規模學習曲線m, n = X.shapetrainErrors = np.zeros((1,m))valErrors = np.zeros((1,m))for i in range(m):Xtrain = X[0:i+1]ytrain = y[0:i+1]res, timeConsumed = linear_regression.gradient(Xtrain, ytrain, rate=0.001, maxLoop=5000, epsilon=0.1)theta, errors = restrainErrors[0,i] = errors[-1]valErrors[0,i] = linear_regression.J(theta, Xval, yval)plt.plot(np.arange(1,m+1).ravel(), trainErrors.ravel(), color='b', label='Training Error')plt.plot(np.arange(1,m+1).ravel(), valErrors.ravel(), color='g', label='Validation Error')plt.title('Learning curve for linear regression')plt.xlabel('Number of training examples')plt.ylabel('Error')plt.legend()plt.show()
通過觀測學習曲線,我們估計算法出現了**高偏差(High Bias)**情況,因此,我們通過多項式回歸來提高擬合精度:
由于多項式回歸可能引起過擬合問題,因此我們還考慮了正規化,并且獲得了隨不同的正規化參數 λλλ 變化的學習曲線:
借此知道了在 λλλ=0.001 的時候,交叉驗證集誤差最小,此時我們繪制擬合曲線:
總結
以上是生活随笔為你收集整理的4.7 程序示例--算法诊断-机器学习笔记-斯坦福吴恩达教授的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4.6 大数据集-机器学习笔记-斯坦福吴
- 下一篇: 5.1 代价函数-机器学习笔记-斯坦福吴