tensorflow 线性回归(numpy)

tensorflow 线性回归(numpy)

链接: 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()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值