当前位置:
首页 >
4.7 程序示例--算法诊断-机器学习笔记-斯坦福吴恩达教授
发布时间:2025/4/5
27
豆豆
生活随笔
收集整理的这篇文章主要介绍了
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 代价函数-机器学习笔记-斯坦福吴