栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

随机梯度下降法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

随机梯度下降法

代码如下:

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)

# 至此我们已经得到了三个常数的近似值

运行结果如下图:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/488145.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号