鱼C论坛

 找回密码
 立即注册
查看: 1589|回复: 1

[技术交流] [机器学习]一元一次函数的梯度下降法拟合的python实现

[复制链接]
发表于 2020-3-23 23:37:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import numpy as np
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

m = 1000

def f(x):
    # return 8.0 * x + 9.0 + (-1.5 + random.random() * 3)
    # return 8.0 * x + 9.0 + random.uniform(-1.5,1.5)
     return 8.0*x+9.0+(-1000+random.random()*2000)


def E(a, b, P):
    sum = 0
    for p in P:
        sum = sum + (p[0]*a+b-p[1])**2
    return sum / len(P)

def d_f_A(a, b, P):
    sum = 0
    for p in P:
        sum = sum + 2*p[0]*(a*p[0]+b-p[1])
    return sum / len(P)

def d_f_B(a, b, P):
    sum = 0
    for p in P:
        sum = sum + 2*(b+a*p[0]-p[1])
    return sum / len(P)

P = []
X = []
Y = []

for i in range(1, m):
    x = -1000 + random.random() * 2000
    X.append(x)
    y = f(x)
    Y.append(y)
    P.append([x, y])

learning_rate = 0.0000001
max_loop = 1000
tolerance = 0.01
a_init = random.random()*2
a = a_init
b_init = 8+random.random()*2
b = b_init
GDX = [a]
GDY = [b]
GDZ = [E(a, b, P)]
E_pre = 0

for i in range(max_loop):
    d_f_a = d_f_A(a, b, P)
    d_f_b = d_f_B(a, b, P)
    a = a-learning_rate * d_f_a
    b = b-learning_rate * d_f_b
    GDX.append(a)
    GDY.append(b)
    E_cur = E(a, b, P)
    GDZ.append(E_cur)
    # print(x, y)

    if abs(E_cur-E_pre)<tolerance:
        break
    E_pre = E_cur

print('a的初值为 =', a_init)
print('b的初值为 =', b_init)
print('拟合后 a=', a, 'b=', b)
print('E(a,b) =', E(a, b, P))


plt.scatter(X, Y)
xe = np.arange(-1000,1000)
plt.plot(xe,a*xe+b)
plt.show()



想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-12-23 09:04:46 | 显示全部楼层
请问有没有二元函数带约束的梯度下降法例子。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-8 04:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表