李宏毅机器学习——回归

一、步骤

1. 构造损失函数:评估模型的好坏

2. 梯度下降:筛选出最好的模型

(1)初始化w0和b
(2)更新w和b,根据偏导和学习率

局部最优or全局最优?
- 线性回归的损失函数是凹形曲线
- 局部最优就是全局最优
- 但是在其他模型中需要考虑局部最优和全局最优的区别

二、优化过度——过拟合

(一)什么是复杂的模型?

  • 自变量过多
  • 用自变量的高次方形式拟合
  • 某些自变量的权重过大

Q:形式复杂的曲线是非线性模型么?
A:还是线性模型。整体化变量后,本质就是线性模型。

(二)怎样解决过拟合?——正则化

通过限制过大的w,使function更加平滑,来控制模型的复杂度,防止过拟合。但是也不能过度限制,这样会让模型失去解释能力。

三、模型复现

import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl

# matplotlib没有中文字体,动态解决
plt.rcParams['font.sans-serif'] = ['Simhei']  # 显示中文
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
#x和y的数据
x_data = [338., 333., 328., 207., 226., 25., 179., 60., 208., 606.]
y_data = [640., 633., 619., 393., 428., 27., 193., 66., 226., 1591.]
x_d = np.asarray(x_data)
y_d = np.asarray(y_data)
#w和b的数据
x = np.arange(-200, -100, 1)#w,100个
y = np.arange(-5, 5, 0.1)#b,100个
Z = np.zeros((len(x), len(y)))
X, Y = np.meshgrid(x, y) # 网格点坐标矩阵:meshgrid吐出结果:y为行,x为列
# loss
for i in range(len(x)):
    for j in range(len(y)):
        b = x[i]
        w = y[j]
        Z[j][i] = 0  
        for n in range(len(x_data)): #第n个样本
            Z[j][i] += (y_data[n] - b - w * x_data[n]) ** 2
        Z[j][i] /= len(x_data) #平均
# linear regression
#初始化
b=-2
w=0.01
lr = 0.000005 # 学习率
iteration = 1400000 # 迭代次数
#记录b和w
b_history = [b]
w_history = [w]
loss_history = []
import time
start = time.time()
#迭代更新
for i in range(iteration):
    m = float(len(x_d)) #样本量
    y_hat = w * x_d  +b 
    loss = np.dot(y_d - y_hat, y_d - y_hat) / m  #对每个样本而言,点积就是相乘
    grad_b = -2.0 * np.sum(y_d - y_hat) / m   #梯度
    grad_w = -2.0 * np.dot(y_d - y_hat, x_d) / m
    # update param
    b -= lr * grad_b
    w -= lr * grad_w

    b_history.append(b)
    w_history.append(w)
    loss_history.append(loss)
    if i % 10000 == 0:
        print("Step %i, w: %0.4f, b: %.4f, Loss: %.4f" % (i, w, b, loss)) #每迭代一万次print一次结果
end = time.time()
print("大约需要时间:",end-start)
# plot the figure
plt.subplot(1, 2, 1)
C = plt.contourf(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))  # 填充等高线
# plt.clabel(C, inline=True, fontsize=5)
plt.plot([-188.4], [2.67], 'x', ms=12, mew=3, color="orange")
plt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')
plt.xlim(-200, -100)
plt.ylim(-5, 5)
plt.xlabel(r'$b$')
plt.ylabel(r'$w$')
plt.title("线性回归")

plt.subplot(1, 2, 2)
loss = np.asarray(loss_history[2:iteration])
plt.plot(np.arange(2, iteration), loss)
plt.title("损失")
plt.xlabel('step')
plt.ylabel('loss')
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值