机器学习作业 5 - 偏差和方差

import numpy as np
import scipy.io as sio
import scipy.optimize as opt
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def load_data():"""for ex5d['X'] shape = (12, 1)pandas has trouble taking this 2d ndarray to construct a dataframe, so I ravelthe results"""d = sio.loadmat('ex5data1.mat')return map(np.ravel, [d['X'], d['y'], d['Xval'], d['yval'], d['Xtest'], d['ytest']])
X, y, Xval, yval, Xtest, ytest = load_data()
df = pd.DataFrame({'water_level':X, 'flow':y})sns.lmplot('water_level', 'flow', data=df, fit_reg=False, size=7)
plt.show()X, Xval, Xtest = [np.insert(x.reshape(x.shape[0], 1), 0, np.ones(x.shape[0]), axis=1) for x in (X, Xval, Xtest)]

代价函数

def cost(theta, X, y):"""X: R(m*n), m records, n featuresy: R(m)theta : R(n), linear regression parameters"""m = X.shape[0]inner = X @ theta - y  # R(m*1)# 1*m @ m*1 = 1*1 in matrix multiplication# but you know numpy didn't do transpose in 1d array, so here is just a# vector inner product to itselvessquare_sum = inner.T @ innercost = square_sum / (2 * m)return cost
theta = np.ones(X.shape[1])
cost(theta, X, y)

梯度

def gradient(theta, X, y):m = X.shape[0]inner = X.T @ (X @ theta - y)  # (m,n).T @ (m, 1) -> (n, 1)return inner / mgradient(theta, X, y)

正则化梯度

def regularized_gradient(theta, X, y, l=1):m = X.shape[0]regularized_term = theta.copy()  # same shape as thetaregularized_term[0] = 0  # don't regularize intercept thetaregularized_term = (l / m) * regularized_termreturn gradient(theta, X, y) + regularized_term
regularized_gradient(theta, X, y)

拟合数据
(正则化项 λ=0\lambda=0λ=0)

def linear_regression_np(X, y, l=1):"""linear regressionargs:X: feature matrix, (m, n+1) # with incercept x0=1y: target vector, (m, )l: lambda constant for regularizationreturn: trained parameters"""# init thetatheta = np.ones(X.shape[1])# train itres = opt.minimize(fun=regularized_cost,x0=theta,args=(X, y, l),method='TNC',jac=regularized_gradient,options={'disp': True})return res
def regularized_cost(theta, X, y, l=1):m = X.shape[0]regularized_term = (l / (2 * m)) * np.power(theta[1:], 2).sum()return cost(theta, X, y) + regularized_term
theta = np.ones(X.shape[0])final_theta = linear_regression_np(X, y, l=0).get('x')
b = final_theta[0] # intercept
m = final_theta[1] # slopeplt.scatter(X[:,1], y, label="Training data")
plt.plot(X[:, 1], X[:, 1]*m + b, label="Prediction")
plt.legend(loc=2)
plt.show()
training_cost, cv_cost = [], []
1.使用训练集的子集来拟合应模型2.在计算训练代价和交叉验证代价时,没有用正则化3.记住使用相同的训练集子集来计算训练代价
m = X.shape[0]
for i in range(1, m+1):
#     print('i={}'.format(i))res = linear_regression_np(X[:i, :], y[:i], l=0)tc = regularized_cost(res.x, X[:i, :], y[:i], l=0)cv = regularized_cost(res.x, Xval, yval, l=0)
#     print('tc={}, cv={}'.format(tc, cv))training_cost.append(tc)cv_cost.append(cv)
plt.plot(np.arange(1, m+1), training_cost, label='training cost')
plt.plot(np.arange(1, m+1), cv_cost, label='cv cost')
plt.legend(loc=1)
plt.show()

这个模型拟合不太好, 欠拟合了

创建多项式特征

def prepare_poly_data(*args, power):"""args: keep feeding in X, Xval, or Xtestwill return in the same order"""def prepare(x):# expand featuredf = poly_features(x, power=power)# normalizationndarr = normalize_feature(df).as_matrix()# add intercept termreturn np.insert(ndarr, 0, np.ones(ndarr.shape[0]), axis=1)return [prepare(x) for x in args]
def poly_features(x, power, as_ndarray=False):data = {'f{}'.format(i): np.power(x, i) for i in range(1, power + 1)}df = pd.DataFrame(data)return df.as_matrix() if as_ndarray else df
X, y, Xval, yval, Xtest, ytest = load_data()poly_features(X, power=3)

准备多项式回归数据

  1. 扩展特征到 8阶,或者你需要的阶数
  2. 使用 归一化 来合并 xnx^nxn
  3. don’t forget intercept term
def normalize_feature(df):"""Applies function along input axis(default 0) of DataFrame."""return df.apply(lambda column: (column - column.mean()) / column.std())
X_poly, Xval_poly, Xtest_poly= prepare_poly_data(X, Xval, Xtest, power=8)
X_poly[:3, :]

画出学习曲线
(> 首先,我们没有使用正则化,所以 λ=0\lambda=0λ=0)

def plot_learning_curve(X, y, Xval, yval, l=0):training_cost, cv_cost = [], []m = X.shape[0]for i in range(1, m + 1):# regularization applies here for fitting parametersres = linear_regression_np(X[:i, :], y[:i], l=l)# remember, when you compute the cost here, you are computing# non-regularized cost. Regularization is used to fit parameters onlytc = cost(res.x, X[:i, :], y[:i])cv = cost(res.x, Xval, yval)training_cost.append(tc)cv_cost.append(cv)plt.plot(np.arange(1, m + 1), training_cost, label='training cost')plt.plot(np.arange(1, m + 1), cv_cost, label='cv cost')plt.legend(loc=1)
plot_learning_curve(X_poly, y, Xval_poly, yval, l=0)
plt.show()
#你可以看到训练的代价太低了,不真实. 这是 **过拟合**了

try λ=1\lambda=1λ=1

# try $\lambda=1$
plot_learning_curve(X_poly, y, Xval_poly, yval, l=1)
plt.show()
#训练代价增加了些,不再是0了。也就是说我们减轻**过拟合**

try λ=100\lambda=100λ=100

plot_learning_curve(X_poly, y, Xval_poly, yval, l=100)
plt.show()
#太多正则化了.  变成 **欠拟合**状态

找到最佳的 λ\lambdaλ

l_candidate = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10]
training_cost, cv_cost = [], []
for l in l_candidate:res = linear_regression_np(X_poly, y, l)tc = cost(res.x, X_poly, y)cv = cost(res.x, Xval_poly, yval)training_cost.append(tc)cv_cost.append(cv)
plt.plot(l_candidate, training_cost, label='training')
plt.plot(l_candidate, cv_cost, label='cross validation')
plt.legend(loc=2)plt.xlabel('lambda')plt.ylabel('cost')
plt.show()
l_candidate[np.argmin(cv_cost)]for l in l_candidate:theta = linear_regression_np(X_poly, y, l).xprint('test cost(l={}) = {}'.format(l, cost(theta, Xtest_poly, ytest)))#调参后, $\lambda = 0.3$ 是最优选择,这个时候测试代价最小

吴恩达机器学习作业5.偏差和方差相关推荐

  1. 吴恩达机器学习作业5——偏差与方差

    在前半部分的练习中,你将实现正则化线性回归,以预测水库中的水位变化,从而预测大坝流出的水量.在下半部分中,您将通过一些调试学习算法的诊断,并检查偏差 v.s. 方差的影响. import numpy ...

  2. 吴恩达机器学习作业ex2-python实现

    系列文章目录 吴恩达机器学习作业ex1-python实现 吴恩达机器学习作业ex2-python实现 吴恩达机器学习作业ex3-python实现 作业说明及数据集 链接:https://pan.bai ...

  3. k均值算法python实现(吴恩达机器学习作业)

    k均值算法python实现(吴恩达机器学习作业) 题目要求 数据集 读取mat文件 K-means 实现 结果 问题 题目要求 采用K均值算法对样本进行聚类. 编写K均值算法源代码,对ex7data2 ...

  4. 第一章-机器学习简介 深度之眼_吴恩达机器学习作业训练营

    目录 专栏简介: 一,机器学习简介 1.1 机器学习定义 1.1 机器学习的重要性 1.2 应用领域 二.监督学习 三.无监督学习 四.总结 专栏简介: 本栏主要内容为吴恩达机器学习公开课的学习笔记, ...

  5. 吴恩达机器学习作业7 - K-means和PCA主成分分析(Python实现)

    吴恩达机器学习作业7 - K-means和PCA主成分分析(Python实现) Introduction 在本实验中,将实现K-means聚类算法,并将其应用于图像压缩.在第二部分实验中,将使用主成分 ...

  6. 吴恩达机器学习作业Python实现(五):偏差和方差

    吴恩达机器学习系列作业目录 在本练习中,您将实现正则化的线性回归和多项式回归,并使用它来研究具有不同偏差-方差属性的模型 1 Regularized Linear Regression 正则线性回归 ...

  7. 吴恩达机器学习作业Python实现(八):异常检测和推荐系统

    吴恩达机器学习系列作业目录 1 Anomaly detection 这部分,您将实现一个异常检测算法来检测服务器计算机中的异常行为.他的特征是测量每个服务器的响应速度(mb/s)和延迟(ms).当你的 ...

  8. 吴恩达机器学习作业Python实现(七):K-means和PCA主成分分析

    吴恩达机器学习系列作业目录 1 K-means Clustering 在这个练习中,您将实现K-means算法并将其用于图像压缩.通过减少图像中出现的颜色的数量,只剩下那些在图像中最常见的颜色. 1. ...

  9. 吴恩达机器学习作业Python实现(六):SVM支持向量机

    吴恩达机器学习系列作业目录 1 Support Vector Machines 1.1 Example Dataset 1 %matplotlib inline import numpy as np ...

最新文章

  1. 发现一个windows7(32bit或64bit)DirectUI的bug
  2. 用 Dagger 2 实现依赖注入
  3. 图解TCP四次握手断开连接
  4. jQuery LigerUI 使用教程表格篇(1)
  5. 拿什么来拯救你,电视!
  6. Mac上设置共享视频音乐或照片
  7. java专用英语词典软件_英语词典app哪个好 5款好用的英语词典app推荐
  8. mro python_Python之super与MRO
  9. 五年程序员一般多少工资?网友:能活下来我都觉得是庆幸的!
  10. NXP MIMXRT1052CVL5B + 正点原子 + MCUXpresso IDE 开发环境搭建
  11. ERROR: Cannot uninstall ‘PyYAML‘. It is a distutils installed project and thus we cannot...
  12. [读后感]从Code Review 谈如何做技术
  13. 区块链溯源系统开发:为何百度、阿里纷纷押注区块链溯源
  14. Echarts柱状图柱子点击事件
  15. 利用USB接口转串口芯片,做一个简单的闪光灯
  16. 生成在线图片地址,用于测试
  17. 什么是系统漏洞,该如何处理?
  18. 【C++】构建一个正方形类
  19. 内网穿透-利用frp进行远程桌面控制(window服务端,window客户端)
  20. 优秀课件笔记之人力资源开发与管理导论

热门文章

  1. WebSphere Message Boker 中调用jar包
  2. 关于sap的日期,时间
  3. train_val.prototxt文件和deploy.prototxt文件开头的区别
  4. MySQL索引背后的数据结构及算法原理(employees实例)
  5. 数据库连接池的作用及c3p0的详解(转载他人的--合理掌握学习方式)
  6. Mysql Explain用法pdf
  7. mysqlinsert触发器的创建
  8. vijos训练之——星辰大海中闪烁的趣题
  9. centos x86-64位版本 想安装qq for linux
  10. 動態設定GridView的列寬