发布于2020-03-17 18:11 阅读(770) 评论(0) 点赞(1) 收藏(2)
链接: https://pan.baidu.com/s/1uyet8NFjYl8Tk1LabRV_Jg 提取码: s2bx
import numpy as np
np.__version__
# 计算loss
def compute_error_from_line_given_points(b, w, points):
total_error = 0
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
# 计算损失
total_error += (y - (w * x + b))**2
return total_error / float(len(points))
# 求梯度
def step_gradient(b_current, w_current, points, learning_rate):
b_gradient = 0
w_gradient = 0
N = float(len(points))
# 循环计算梯度
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
# 计算梯度
b_gradient += (2/N) * ((w_current * x + b_current) - y)
w_gradient += (2/N) * x * ((w_current*x + b_current) - y)
# 更新参数
new_b = b_current - (learning_rate * b_gradient)
new_w = w_current - (learning_rate * w_gradient)
return [new_b, new_w]
# 循环梯度运行
def gradient_descent_runner(points, starting_b, starting_w, learning_rate, num_iterations):
w = starting_w
b = starting_b
# 循环更新梯度
for i in range(num_iterations):
b, w = step_gradient(b, w, np.array(points), learning_rate)
return [b, w]
def run():
# 1.导入数据
points = np.genfromtxt("data.csv", delimiter=",")
print(points.shape)
print(points[:5])
# 2.参数初始化
learning_rate = 0.0001
initial_b = 0
initial_w = 0
num_iterations = 1000
# 3.显示初始参数与loss
start_loss = compute_error_from_line_given_points(initial_b, initial_w, points)
print("初始化: b = %f, w = %f loss= %f" % (initial_b, initial_w, start_loss))
# 4.循环更新参数
print("开始执行....")
[b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations)
# 5.显示训练后的参数与loss
end_loss = compute_error_from_line_given_points(b, w, points)
print("初始化: b = %f, w = %f loss= %f" % (b, w, end_loss))
if __name__ == "__main__":
run()
作者:坚持就是胜利
链接:https://www.pythonheidong.com/blog/article/263467/4c7069a64a9e376c841b/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!