Python和numpy实现一元二次函数回归

均方误差(MSE)是回归问题中常用的损失函数,它衡量了模型预测值与真实值之间的平方误差的平均值。MSE损失函数的定义如下:

其中,m 是样本数量,y(i) 是第 i 个样本的真实标签,y^​(i) 是模型对第 i 个样本的预测值。

为了使用梯度下降算法更新模型参数,我们需要计算MSE损失函数对参数的导数。

我们的模型设置为 y = ax^{2} + bx + c

然后需要计算MSE对 a​ 、b、c 的偏导数:

\frac{\partial MSE}{\partial a} = \frac{2}{m}\sum_{i=1}^{m}(\hat{y^{(i)}}-y^{(i)})*x^2

\frac{\partial MSE}{\partial b} = \frac{2}{m}\sum_{i=1}^{m}(\hat{y^{(i)}}-y^{(i)})*x

\frac{\partial MSE}{\partial a} = \frac{2}{m}\sum_{i=1}^{m}(\hat{y^{(i)}}-y^{(i)})*1

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
import random
n_features = 1     # 特征数
n_samples  = 100   # 样本数

np.random.seed(1) # 设置随机数种子,保证每次运行都是相同的结果

a = random.random()
b = random.random()
c = random.random()
print(f"a = {a}, b = {b}, c = {c}")
# 真实的权重
a_true = 2
b_true = 3
c_true = 4

x = np.random.normal(0,1,n_samples)
y_true = a_true * x ** 2 + b_true * x + c_true + np.random.randn(100)

def mse_loss(x_list, y_list):
    s = 0
    for x, y in zip(x_list, y_list):
        s += (x - y)**2
    return s / len(x_list)


# 设置训练参数
epoch = 1000
lr = 0.01

for e in range(epoch):
    x_list = x
    y_list = [(a_true * x ** 2 + b_true * x + c_true) for x in x_list]
    y_pre = [(a * y ** 2 + b * y + c) for y in x_list]
    ls = mse_loss(y_list, y_pre)
    print("epoch:", e ,", loss = ", ls)
    if ls < 0.01:
        break
    # 开始更新参数
    a -= lr * 2 * np.sum([(a * x ** 2 + b * x + c - y)*x**2 for x,y in zip(x_list, y_list)])/ len(x)
    b -= lr * 2 * np.sum([(a * x ** 2 + b * x + c - y)*x for x,y in zip(x_list, y_list)])/ len(x)
    c -= lr * 2 * np.sum([(a * x ** 2 + b * x + c - y) for x,y in zip(x_list, y_list)])/ len(x)
print(f"a = {a}, b = {b}, c = {c}")

# 可视化
plt.scatter(list(x), list(y_true))
x = np.linspace(-3, 3, 101)
y_pre = a * x ** 2 + b * x + c
plt.plot(x, y_pre)
plt.show()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值