程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

tensorflow 线性回归(numpy)

发布于2020-03-17 18:11     阅读(770)     评论(0)     点赞(1)     收藏(2)


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()

在这里插入图片描述



所属网站分类: 技术文章 > 博客

作者:坚持就是胜利

链接:https://www.pythonheidong.com/blog/article/263467/4c7069a64a9e376c841b/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)