1、简单的梯度下降算法
'''
简单的梯度下降算法
'''
import numpy
as np
import matplotlib
.pyplot
as plt
def func(x
):
return np
.square
(x
)
def dfunc(x
):
return 2*x
def GD(x_start
,df
,epochs
,lr
):
'''
梯度下降法:给定起始值和目标函数的一阶导函数,求epochs次迭代中x的更新值
:param x_start: x的起始点
:param df:目标函数的一阶导
:param epochs:迭代周期
:param lr:学习率
:return:x在每次迭代后的位置(包含起始点),epochs长度+1
'''
xs
= np
.zeros
(epochs
+ 1)
x
= x_start
xs
[0] = x
for i
in range(epochs
):
dx
= df
(x
)
v
= - dx
* lr
x
+= v
xs
[i
+1] = x
return xs
def demo_GD():
line_x
= np
.linspace
(-5,5,100)
line_y
= func
(line_x
)
x_start
= -5
epochs
= 5
lr
= 0.9
'''
当lr=0.1时,拟合效果最好,随着lr的增大,拟合越来也差
'''
x
= GD
(x_start
,dfunc
,epochs
,lr
=lr
)
color
= 'r'
plt
.plot
(line_x
,line_y
,color
='blue')
plt
.plot
(x
,func
(x
),color
=color
,label
='lr={}'.format(lr
))
plt
.scatter
(x
,func
(x
),color
=color
)
plt
.legend
()
plt
.show
()
demo_GD
()
'''
给定数据集dataSet,每一行代表一组数据记录,每组数据记录中,第一个值为房屋面积(单位:平方英尺),
第二个值为房屋中的房间数,第三个值为房价(单位:千美元),
试用梯度下降法,构造损失函数,在函数gradientDescent中实现房价price关于房屋面积area和房间数rooms的线性回归,
返回值为线性方程price=θ0+θ1∗area+θ2∗rooms中系数θi(i=0,1,2)的列表
多变量的梯度下降问题
'''
import numpy
as np
import matplotlib
.pyplot
as plt
import pandas
as pd
def gradientDescent(rooms
, price
, area
):
"""
梯度下降法。给定起始点与目标函数的一阶导数,求在epochs次迭代中theta0,theta1,theta2的更新值
param theta0
"""
theta
= [1,1,1]
learn_rate
= 0.0000000001
predit_y
= 0
loss
= []
epochs
= 5000
for j
in range(epochs
):
theta0
, theta1
, theta2
= 0, 0, 0
loss_t
= 0
for i
in range(5):
predit_y
= theta
[0] + theta
[1] * area
[i
] + theta
[2] * rooms
[i
]
theta0
= theta0
+ (predit_y
- price
[i
]) * 1
theta1
= theta1
+ (predit_y
- price
[i
]) * area
[i
]
theta2
= theta2
+ (predit_y
- price
[i
]) * rooms
[i
]
loss_t
= loss_t
+ ((predit_y
- price
[i
]) ** 2) / 2
loss
.append
(loss_t
/ 5)
theta0
= theta0
/ 5
theta1
= theta1
/ 5
theta2
= theta2
/ 5
theta
[0] = theta
[0] - theta0
* learn_rate
theta
[1] = theta
[1] - theta1
* learn_rate
theta
[2] = theta
[2] - theta2
* learn_rate
plt
.plot
(loss
, c
='b')
plt
.show
()
print(theta
)
return theta
def demo_GD():
price
= [400, 330, 369, 342, 540]
rooms
= [3, 3, 3, 2, 4]
area
= [2104, 1600, 2400, 1416, 3000]
gradientDescent
(rooms
, price
, area
)
demo_GD
()
转载请注明原文地址: https://mac.8miu.com/read-501784.html