python一元线性回归:梯度下降法、损失函数

# -*- coding: utf-8 -*-


import numpy as np
import matplotlib.pyplot as plt

# %matplotlib inline

# 1.读入数据
data = np.genfromtxt('一元线性回归.csv', delimiter=',')
x_data = data[:, 0]  # 1维
y_data = data[:, 1]  # 1维
plt.scatter(x_data, y_data)

# 2.用梯度下降法调整参数
k = 0  # 先随便设置一个k
b = 0  # 先随便设置一个b
learing_rate = 0.0001  # 学习率
epoches = 30  # 循环30次
m = len(x_data)  # 一共100条数据

# 不断的调用k和b
for i in range(epoches):
    # for j in range(m):
    k_grad = (k * x_data + b - y_data) * x_data
    b_grad = k * x_data + b - y_data

    k_grad = (-1 / m) * sum(k_grad)
    b_grad = (-1 / m) * sum(b_grad)

    k = k + learing_rate * k_grad
    b = b + learing_rate * b_grad

print('最终结果:k={}, b={}'.format(k, b))
plt.scatter(x_data, y_data)
plt.plot(x_data, x_data * k + b, 'r')

# 改进1

k = 0  # 先随便设置一个k
b = 0  # 先随便设置一个b
learing_rate = 0.0001  # 学习率
epoches = 30  # 循环30次
m = len(x_data)  # 一共100条数据


def loss_function(k, b):
    total_error = (k * x_data + b - y_data) ** 2
    total_error = sum(total_error)
    return total_error / (2 * m)


# 不断的调用k和b
for i in range(1, epoches + 1):

    k_grad = (k * x_data + b - y_data) * x_data
    b_grad = k * x_data + b - y_data

    k_grad = (-1 / m) * sum(k_grad)
    b_grad = (-1 / m) * sum(b_grad)

    k = k + learing_rate * k_grad
    b = b + learing_rate * b_grad

    # 每循环5次,输出此时k, b和损失函数
    if i % 3 == 0:
        print('epoch{}:k={},b={},loss function={}'.format(i, k, b, loss_function(k, b)))
        plt.scatter(x_data, y_data)
        plt.plot(x_data, x_data * k + b, 'r')
        plt.show()

print('最终结果:k={}, b={}'.format(k, b))
plt.scatter(x_data, y_data)
plt.plot(x_data, x_data * k + b, 'r')
plt.show()

在这里插入图片描述
在这里插入图片描述

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
一元线性回归是一种简单的回归分析方法,用于建立一个自变量和因变量之间的线性关系模型。梯度下降法是一种常用的优化算法,用于求解最小化损失函数的参数。 以下是一元线性回归梯度下降法Python实现: ```python import numpy as np def gradient_descent(x, y, learning_rate, num_iterations): num_samples = len(x) theta0 = 0 theta1 = 0 for i in range(num_iterations): y_pred = theta0 + theta1 * x error = y_pred - y # 更新参数 theta0 -= learning_rate * (1/num_samples) * np.sum(error) theta1 -= learning_rate * (1/num_samples) * np.sum(error * x) return theta0, theta1 # 示例数据 x = np.array([1, 2, 3, 4, 5]) y = np.array([2, 4, 6, 8, 10]) learning_rate = 0.01 num_iterations = 1000 theta0, theta1 = gradient_descent(x, y, learning_rate, num_iterations) print("theta0:", theta0) print("theta1:", theta1) ``` 上述代码中,我们首先定义了一个`gradient_descent`函数,该函数接受输入数据`x`和目标值`y`,学习率`learning_rate`以及迭代次数`num_iterations`作为参数。在每次迭代中,根据当前的参数值计算预测值`y_pred`,然后计算误差`error`。接下来,根据梯度下降法的更新规则,更新参数`theta0`和`theta1`。最后,返回最终的参数值。 在示例数据中,我们使用了简单的线性关系,即`y = 2x`。通过运行上述代码,可以得到最终的参数值`theta0`为接近0,`theta1`为接近2,这与我们设定的线性关系相符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

rubyw

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

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

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

打赏作者

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

抵扣说明:

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

余额充值