吴恩达机器学习课程-作业5-Bias vs Variance(python实现)

Machine Learning(Andrew) ex4-Regularized Linear Regression and Bias v.s. Variance

椰汁笔记

Regularized Linear Regression

  • 1.1 Visualizing the dataset

对于一个机器学习的数据,通常会被分为三部分训练集、交叉验证集和测试集。训练集用于训练参数,交叉验证集用于选择模型参数,测试集用于评价模型。
这里的作业数据,已经给我们划分好了

    data = sio.loadmat("ex5data1.mat")
    X = data["X"]
    y = data["y"]
    Xval = data["Xval"]
    yval = data["yval"]
    Xtest = data["Xtest"]
    ytest = data["ytest"]

我们使用线性回归拟合的是训练集数据,因此可视化只用可视化训练集的数据

    plt.subplot(2, 2, 1)
    plt.scatter(X, y, marker='x', c='r')
    plt.xlabel("Change in water level (x)")
    plt.ylabel("Water flowing out of the dam (y)")
    plt.title("linear regression")
    plt.xlim((-50, 40))
    plt.ylim((-10, 40))
    plt.show()

数据看起来并不是那么符合线性规律hhh,感觉有点二次函数那味
在这里插入图片描述

  • 1.2 Regularized linear regression cost function
    线性回归在作业1中已经用到了,那里没有正规化,可能导致随着特征的增多出现过拟合现象。
    J ( θ ) = 1 2 m ( ∑ i = 1 m h θ ( x ( i ) − y ( i ) ) 2 ) + λ 2 m ( ∑ j = 1 n θ j 2 ) \mathit{J}(\theta) = \frac{1}{2m} (\sum_{i=1}^{m}h_\theta(x^{(i)}-y^{(i)})^{2})+\frac{\lambda}{2m}(\sum_{j=1}^{n}\theta_j^2) J(θ)=2m1(i=1mhθ(x(i)y(i))2)+2mλ(j=1nθj2)
    直接在之前的损失值计算中加入惩罚项,注意不惩罚theta0
def cost(theta, X, y, l):
    m = X.shape[0]
    part1 = np.mean(np.power(X.dot(theta) - y.ravel(), 2)) / 2
    part2 = (l / (2 * m)) * np.sum(np.delete(theta * theta, 0, axis=0))
    return part1 + part2

将theta全部设置为1,lambda设置为1,进行测试

    theta = np.ones((2,))
    X = np.insert(X, 0, 1, axis=1)
    print(cost(theta, X, y, 1))#303.9931922202643
  • 1.3 Regularized linear regression gradient

∂ J ( θ ) ∂ θ 0 = 1 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) x j ( i ) , j = 0 ∂ J (

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值