博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python之随机梯度下降
阅读量:7082 次
发布时间:2019-06-28

本文共 1072 字,大约阅读时间需要 3 分钟。

实现: # -*- coding: UTF-8 -*- """     练习使用随机梯度下降算法 """ import numpy as np import math __author__ = 'zhen' # 生成测试数据 x = 2 * np.random.rand(100, 1)  # 随机生成100*1的二维数组,值分别在0~2之间 y = 4 + 3 * x + np.random.randn(100, 1)  # 随机生成100*1的二维数组,值分别在4~11之间 x_b = np.c_[np.ones((100, 1)), x] print("x矩阵内容如下:\n{}".format(x_b[0:3])) n_epochs = 100 t0, t1 = 1, 10 m = n_epochs def learning_schedule(t):  # 模拟实现动态修改步长     return t0 / (t + t1) theta = np.random.randn(2, 1) for epoch in range(n_epochs):     for i in range(m):         random_index = np.random.randint(m)         x_i = x_b[random_index:random_index+1]         y_i = y[random_index:random_index+1] gradients = 2 * x_i.T.dot(x_i.dot(theta)-y_i)  # 调用公式         learning_rate = learning_schedule(epoch * m + i)         theta = theta - learning_rate * gradients     if epoch % 30 == 0:         print("抽样查看:\n{}".format(theta)) print("最终结果:\n{}".format(theta)) # 计算误差 error = math.sqrt(math.pow((theta[0][0] - 4), 2) + math.pow((theta[1][0] - 3), 2)) print("误差:\n{}".format(error)) 结果:

 

 

转载于:https://www.cnblogs.com/yszd/p/9280584.html

你可能感兴趣的文章
Mackevision 赞助上海第三届中国汽车论坛
查看>>
2017:连接客户的一年
查看>>
ORA-10997:another startup/shutdown operation of this instance in progress解决方法
查看>>
Velocity工作原理解析和优化
查看>>
zabbix 监控 Tomcat
查看>>
如何用Exchange Server 2003 构建多域名邮件系统
查看>>
Delphi内嵌汇编语言BASM精要(转帖)
查看>>
ASP.NET MVC 在控制器中接收视图表单POST过来的数据方法
查看>>
云计算这么火,但市场发展依然存在着7大障碍
查看>>
Oracle 11g AMM与ASMM切换
查看>>
bootstrap-wysiwyg中JS控件富文本中的图片由本地上传到服务器(阿里云、七牛、自己的数据库)...
查看>>
H3 BPM SharePoint解决方案
查看>>
[原]linux 修改 hostname 立即生效
查看>>
图片抖动效果(兼容)
查看>>
windows查看端口占用情况
查看>>
ASA NAT Priority
查看>>
ping -R和traceroute的测试
查看>>
10.python网络编程(解决粘包问题 part 2)
查看>>
自动移动域中计算机到目标OU的脚本
查看>>
grep/sed/awk实战
查看>>