李宏毅机器学习笔记——01.回归(Regression)—Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lens___/article/details/83926508

传送门:

上一节:李宏毅机器学习笔记——01.回归(Regression)

下一节:李宏毅机器学习笔记——02.Where does the error come from ?


我们在前一节学的回归(Regression),知道怎么用梯度下降(Gradient Descent)来找出Regression model 的参数,接下来举个例子,实际在做回归的时候会碰到什么样的困难。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x_data = [338.,333.,328.,207.,226.,25.,179.,60.,208.,606.]
y_data = [640.,633.,619.,393.,428.,27.,193.,66.,226.,1591.]
#y_data = b + w * x_data

 假设x_data 、y_data 都有10笔数据,它们之间的关系是:y_data = b + w * x_data , b 和w 都是参数,我们用梯度下降将b 和w 找出来

x = np.arange(-200, -100, 1) # bias
y = np.arange(-5, 5, 0.1) # weight
Z = np.zeros((len(x), len(y)))
X,Y = np.meshgrid(x, y)
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)):
            Z[j][i] = Z[j][i] + (y_data[n] - b - w*x_data[n])**2
        Z[j][i] = Z[j][i]/len(x_data)

np.zeros生成一个(100,100)用0填充的数组,

np.meshgrid将x,y进行扩展,生成X,Y两个新的二维数组,

最后计算出损失函数(Loss function)

# yadata = b + w*xdata
b = -120 # intial b
w = -4 # intial w
lr = 0.0000001     # learning rate,通过调节不同的lr参数可以获得不同的曲线长度
iteration = 100000

# store initial values for plotting.
b_history = [b]
w_history = [w]

# iterations
for i in range(iteration):
 
    b_grad = 0.0
    w_grad = 0.0
    for n in range(len(x_data)):
        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0
        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]

    # update parameters
    b = b - lr*b_grad
    w = w - lr*w_grad

    # store parameters for plotting
    b_history.append(b)
    w_history.append(w)

# plot the figure
plt.contourf(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))
plt.plot([-188.4], [2.67], 'x', ms=12, marker=6, color='orange')   # ms和marker分别代表指定点的长度和宽度
# 李宏毅课程原代码为markeredeweight=3,无法运行,改为了marker=6。
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$', fontsize=16)
plt.ylabel(r'$w$', fontsize=16)
plt.show()

先给b、w初始值,一个很小的学习率,迭代次数为100000

在每一个迭代里面,计算出b、w对Loss的偏微分,算出之后,乘上学习率分别更新b跟w,反复迭代多次,就可以找出b和w。

这是我们得到的结果,图上的颜色代表了不同的参数下,我们会得到的Loss,纵轴代表W的变化,横轴代表b的变化,不同的W、不同的b我们得到不同的颜色,也就是不同的Loss,Loss最低的点在图上三角形的位置,初始的b、w在(-120,-4)的位置,在做梯度下降的时候,就从这个位置开始update参数

但是过了100000次update之后得到的值离最佳解仍然非常的遥远,显然是学习率不够大,把学习率调大一点

lr = 0.000001  #比之前增加10倍

这是学习率调大10倍后的结果,离最佳解稍微进了一点,不过这边有一个剧烈的振荡的现象发生

lr = 0.00001  #再设大10倍

学习率太大,参数更新之后就飞到图外面了,怎么办呢?

放大招了!

我们要给b跟w客制化(自定义)的学习率(learning rate),它们两的学习率要是不一样


# yadata = b + w*xdata
b = -120 # intial b
w = -4 # intial w
lr = 1     # learning rate,通过调节不同的lr参数可以获得不同的曲线长度
iteration = 100000

# store initial values for plotting.
b_history = [b]
w_history = [w]

lr_b = 0
lr_w = 0

# iterations
for i in range(iteration):
 
    b_grad = 0.0
    w_grad = 0.0
    for n in range(len(x_data)):
        b_grad = b_grad - 2.0*(y_data[n] - b - w*x_data[n])*1.0
        w_grad = w_grad - 2.0*(y_data[n] - b - w*x_data[n])*x_data[n]
        
    lr_b = lr_b + b_grad ** 2
    lr_w = lr_w + w_grad ** 2

    # update parameters
    b = b - lr/np.sqrt(lr_b) * b_grad
    w = w - lr/np.sqrt(lr_w) * w_grad

    # store parameters for plotting
    b_history.append(b)
    w_history.append(w)

# plot the figure
plt.contourf(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))
plt.plot([-188.4], [2.67], 'x', ms=12, marker=6, color='orange')
# ms和marker分别代表指定点的长度和宽度
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$', fontsize=16)
plt.ylabel(r'$w$', fontsize=16)
plt.show()

原来b和w的偏微分都是直接乘上学习率,是固定的,现在把它除掉不同的值,所以现在会有不同的学习率,学习率就随便设,设个1就好

发现有了新的学习率以后,从初始的值到终点,我们就很顺利的在10w次update参数之内走到终点了。

传送门:

上一节:李宏毅机器学习笔记——01.回归(Regression)

下一节:李宏毅机器学习笔记——02.Where does the error come from ?

猜你喜欢

转载自blog.csdn.net/lens___/article/details/83926508
今日推荐