首页 / 算法 / 优化算法——梯度下降法实现
优化算法——梯度下降法实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了优化算法——梯度下降法实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1909字,纯文字阅读大概需要3分钟。
内容图文
![优化算法——梯度下降法实现](/upload/InfoBanner/zyjiaocheng/850/c502f312e3cd40fb9b21938570abcdbb.jpg)
批量梯度下降算法实现
import numpy as np
# 设置数据集的行数和维数
r = 20
c = 10
# 生成数据集合label
x = np.random.randint(0, 10, r * c).reshape(r, c) # 20行,10列
x = np.hstack((x, np.ones(r).reshape(r, 1))) # 20行,11列
y = np.random.randint(0, 1, r).reshape(r, 1) # 20行,1列
# 代价函数
def cost(x, y, theta, m):
diff = np.dot(x, theta) - y
return (1 / (2 * m)) * np.dot(np.transpose(diff), diff)
# 梯度函数
def grad(x, y, theta, m):
diff = np.dot(x, theta) - y
return 1 / m * np.dot(np.transpose(x), diff) # 结果是一列
def gradient_descent(x, y, num, error):
m = x.shape[0] # 20行
theta = np.random.randint(0, 10, c + 1).reshape(c + 1, 1) # 20行一列
time = 0
while cost(x, y, theta, m) > error and time < num:
theta = theta - 0.001 * grad(x, y, theta, m)
time += 1
print(cost(x, y, theta, m))
return theta
ans = gradient_descent(x, y, 10000, 0.01)
print(ans)
随机梯度下降算法实现
import numpy as np
import time
# 设置数据集的行数和维数
r = 20
c = 10
# 生成数据集合label
x = np.random.randint(0, 100, r * c).reshape(r, c) # 20行,10列
x = np.hstack((x, np.ones(r).reshape(r, 1))) # 20行,11列
# print(x)
y = np.random.randint(0, 100, r).reshape(r, 1) # 20行,1列
# print(y)
# 损失函数
def cost(x, y, theta, m):
diff = np.dot(x, theta) - y
return (1 / (2 * m)) * np.dot(np.transpose(diff), diff)
# 梯度函数,给样本(xi,yi)求第j个theta的偏导数
def grad(xi, yi, theta, j, m): # 明确选定的theta的第几个值
return 1. / m *(np.dot(xi, theta) - yi) * xi[j]
def gradient_descent(x, y, num, error):
m = x.shape[0] # 20行
theta = np.random.random(c + 1).reshape(c + 1, 1) # 这里不能用随机整数,无法更新
time = 0
while cost(x, y, theta, m) > error and time < num:
index = np.random.randint(m)
xi = x[index]
yi = y[index]
for i in range(11): # 依次更新theta
gr = grad(xi, yi, theta, i , 20)
theta[i] = theta[i] - 0.0001*gr
time += 1
print(cost(x, y, theta, m))
return theta
ans = gradient_descent(x, y, 1000, 0.01)
print(np.dot(x, ans) - y)
print(ans)
内容总结
以上是互联网集市为您收集整理的优化算法——梯度下降法实现全部内容,希望文章能够帮你解决优化算法——梯度下降法实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。