Python——拟合一次函数

一、准备数据

1.新建txt文件,输入以下数据,保存文件为click.csv

x,y
235,591
216,539
148,413
35,310
85,308
204,519
49,325
25,332
173,498
191,498
134,392
99,334
117,385
112,387
162,425
272,659
159,400
159,427
59,319
198,522

数据经过可视化后呈现如下:

2. 数据预处理

把训练数据变成平均值为 0、方差为1的数据。这个预处理不是必须的,但是做了之后,参数的收敛会更快。这种做法也被称为标准化或者z-score规范化,变换表达式是这样的。µ是训练数据的平均值,σ是标准差

预处理后,横轴变化:

回忆一次函数和目标函数:

回忆参数更新表达式:

二、完整代码

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('click.csv', delimiter=',', dtype='int', skiprows=1)
train_x = train[:,0]
train_y = train[:,1]

# 标准化
mu = train_x.mean()
sigma = train_x.std()
def standardize(x):
    return (x - mu) / sigma

train_z = standardize(train_x)

# 参数初始化
theta0 = np.random.rand()
theta1 = np.random.rand()

# 预测函数
def f(x):
    return theta0 + theta1 * x

# 目标函数
def E(x, y):
    return 0.5 * np.sum((y - f(x)) ** 2)

# 学习率
ETA = 1e-3

# 误差的差值
diff = 1

# 更新次数
count = 0

# 直到误差的差值小于 0.01 为止,重复参数更新
error = E(train_z, train_y)
while diff > 1e-2:
    # 更新结果保存到临时变量
    tmp_theta0 = theta0 - ETA * np.sum((f(train_z) - train_y))
    tmp_theta1 = theta1 - ETA * np.sum((f(train_z) - train_y) * train_z)

    # 更新参数
    theta0 = tmp_theta0
    theta1 = tmp_theta1

    # 计算与上一次误差的差值
    current_error = E(train_z, train_y)
    diff = error - current_error
    error = current_error

    # 输出日志
    count += 1
    log = '第 {} 次 : theta0 = {:.3f}, theta1 = {:.3f}, 差值 = {:.4f}'
    print(log.format(count, theta0, theta1, diff))

# 绘图确认
x = np.linspace(-3, 3, 100)
plt.plot(train_z, train_y, 'o')
plt.plot(x, f(x))
plt.show()

三、运行结果

控制台输出:

绘图:

拟合效果还不错。

测试数据:输入print(f(standardize(100))),输出370.70966211722651。

 

### 使用Python实现三次多项式拟合 为了完成三次多项式的拟合,可以利用 `NumPy` 提供的工具函数 `polyfit` 和 `poly1d` 来构建并评估多项式模型。以下是具体方法及其示例代码。 #### 方法描述 在实际应用中,可以通过调用 `numpy.polyfit` 函数指定次数为 3 的多项式来拟合一组给定的数据点。该函数会返回一组系数向量,表示所求得的多项式方程 \( P(x) = a_3 \cdot x^3 + a_2 \cdot x^2 + a_1 \cdot x + a_0 \)[^2]。随后可使用这些系数创建一个多项式对象以便进一步操作或绘图展示[^5]。 下面提供了一个完整的例子用于说明这一过程: ```python import numpy as np import matplotlib.pyplot as plt # 创建模拟数据集 np.random.seed(42) x = np.linspace(-5, 5, num=50) y = 0.8 * (x ** 3) - 2*(x**2) + 3*x - 7 + np.random.randn(len(x)) # 进行三次多项式拟合 coefficients = np.polyfit(x, y, deg=3) # 构建多项式表达形式 polynomial_model = np.poly1d(coefficients) print("Fitted polynomial:", polynomial_model) # 绘制原始散点图与拟合曲线对比 plt.figure(figsize=(8,6)) plt.scatter(x,y,label="Data Points",color='blue') xx = np.linspace(min(x)-1,max(x)+1,num=100) yy = polynomial_model(xx) plt.plot(xx, yy, label=f"Fitted Curve ({polynomial_model})", color='red', linestyle="--") plt.title('Cubic Polynomial Fitting Example') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.legend() plt.grid(True) plt.show() ``` 上述脚本首先生成了一套带有噪声干扰的真实三维空间分布样条作为输入数据;接着运用 NumPy 库中的 polyfit 功能执行了针对此集合的最佳匹配分析——即寻找最接近原趋势线的一个特定阶数(这里是三阶)代数关系式;最后借助 Matplotlib 展现出了两者之间的契合程度效果[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

穿梭的编织者

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

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

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

打赏作者

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

抵扣说明:

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

余额充值