随机梯度下降法

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

e0 = 1
e1 = 1
e2 = 1

alpha = 0.01
theta0 = np.random.uniform(0, 1)
theta1 = np.random.uniform(0, 1)
theta2 = np.random.uniform(0, 1)
theta = np.array([theta1, theta2])

eps = 1e-4

x = np.array([[2, 3], [4, 6], [7, 8], [12, 15]])
t = np.array([5, 8, 14, 17])

cnt = 0  # 迭代次数
while (abs(e0) >= eps or abs(e1) >= eps or abs(e2) >= eps):  # 这里用绝对值小于eps进行判定 如果不用绝对值的话如果有数据小于0的话会直接跳出循环
    cnt += 1
    i = np.random.randint(0,4) #随机一个整数作为本次的训练数据
    e0 = (np.sum((x[i] * theta)) + theta0 * 1 - t[i])
    e1 = (np.sum((x[i] * theta)) + theta0 * 1 - t[i]) * x[i][0]
    e2 = (np.sum((x[i] * theta)) + theta0 * 1 - t[i]) * x[i][1]
    i = np.random.randint(0,4)
    e0 += (np.sum((x[i] * theta)) + theta0 * 1 - t[i])
    e1 += (np.sum((x[i] * theta)) + theta0 * 1 - t[i]) * x[i][0]
    e2 += (np.sum((x[i] * theta)) + theta0 * 1 - t[i]) * x[i][1]
        # 上面是求导公式
    e0 /= 5
    e1 /= 5
    e2 /= 5

    theta0 = theta0 - alpha * e0  # 公式
    theta1 = theta1 - alpha * e1
    theta2 = theta2 - alpha * e2
    theta = np.array([theta1, theta2])  # 每次都要对theta进行更新以便进行下次迭代
print(cnt)
print(theta0, theta1, theta2)

# 至此我们已经得到了三个常数的近似值 下面绘制3D图
fig = plt.figure()
ax = Axes3D(fig)
a = np.arange(0, 20)  # 设置两个坐标轴的长度
b = np.arange(0, 20)
A, B = np.meshgrid(a, b)  # 生成网络格

Z = theta0 + theta1 * A + theta2 * B  # 把得到的theta值带入h(x)函数
plt.xlabel('x1')
plt.ylabel('x2')
ax.plot_surface(A, B, Z, rstride=3, cstride=3, cmap='rainbow')  # 设置跨度为3 映射颜色为彩虹色
plt.show()

得到的结果
在这里插入图片描述
生成的图
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值