pytorch基础知识一【梯度】

1. 引入

已知函数表达式为:

y = w * x + b

如果求未知数w和b,可以给定两个点,联立方程求解,如下图所示:
在这里插入图片描述
现在给满足此等式的点加入噪声,通过这一系列的点求出w和b的近似值,评价近似值是否最优的的指标为损失函数,如下图所示:
在这里插入图片描述
在这里插入图片描述
如何最优化?

在这里插入图片描述

2. 实例代码

求解过程:
给定初始的w和b的值,利用给定的100个观测值按梯度步长逐渐让w和b逼近到其各自的真实值。
参数 = 参数 - 学习率 * 梯度在这里插入图片描述

import numpy as np

# y = wx + b
# 计算损失函数的值
def compute_error_for_line_given_points(b, w, points):
    totalError = 0
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        totalError += (y - (w * x + b)) ** 2
    return totalError / float(len(points))

#
def step_gradient(b_current, w_current, points, learningRate):
    b_gradient = 0
    w_gradient = 0
    N = float(len(points)) # 100个点
    for i in range(0, len(points)):
        x = points[i, 0]
        y = points[i, 1]
        # 所有观测点在(w_gradient,b_gradient)处的梯度的和的平均值
        b_gradient += -(2/N) * (y - ((w_current * x) + b_current))
        w_gradient += -(2/N) * x * (y - ((w_current * x) + b_current))
    new_b = b_current - (learningRate * b_gradient)
    new_w = w_current - (learningRate * w_gradient)
    print("new_b, new_w",new_b, new_w)
    return [new_b, new_w]

def gradient_descent_runner(points, starting_b, starting_w, learning_rate, num_iterations):
    b = starting_b
    w = starting_w
    for i in range(num_iterations):
        b, w = step_gradient(b, w, np.array(points), learning_rate)
    return [b, w]

def run():
    points = np.genfromtxt("data.csv", delimiter=",")
    learning_rate = 0.0001
    initial_b = 0 # initial y-intercept guess
    initial_w = 0 # initial slope guess
    num_iterations = 1000
    print("Starting gradient descent at b = {0}, m = {1}, error = {2}"
          .format(initial_b,
                  initial_w,
                  compute_error_for_line_given_points(initial_b, initial_w, points))
          )
    print("Running...")
    [b, w] = gradient_descent_runner(points, initial_b, initial_w, learning_rate, num_iterations)
    print("After {0} iterations b = {1}, m = {2}, error = {3}".
          format(num_iterations,
                 b,
                 w,
                 compute_error_for_line_given_points(b, w, points))
          )

if __name__ == '__main__':
    run()


执行结果:
	Starting gradient descent at b = 0, m = 0, error = 5565.107834483211
	Running...
	After 1000 iterations b = 0.08893651993741346, m = 1.4777440851894448, error = 112.61481011613473

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值