初级
第01章 统计学习方法概论 - 使用最小二乘法拟和曲线 - 实现fitting函数
未完成 0%
初级参考
完整示例代码供参考,建议自己理解后重新输入
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
def real_func(x):
return np.sin(2*np.pi*x)
def fit_func(p, x):
f = np.poly1d(p)
return f(x)
def residuals_func(p, x, y):
return fit_func(p, x) - y
x = np.linspace(0, 1, 10)
x_points = np.linspace(0, 1, 1000)
y_ = real_func(x)
y = [np.random.normal(0, 0.1) + y1 for y1 in y_]
def fitting(M=0):
p_init = np.random.rand(M + 1)
p_lsq = leastsq(residuals_func, p_init, args=(x, y))
print('Fitting Parameters:', p_lsq[0])
plt.plot(x_points, real_func(x_points), label='real')
plt.plot(x_points, fit_func(p_lsq[0], x_points), label='fitted curve')
plt.plot(x, y, 'bo', label='noise')
plt.legend()
return p_lsq
👑
升级 VIP
解锁全部题目,畅通无阻地学习
- ✓ 解锁全部训练包所有题目
- ✓ 查看完整参考代码和提示
- ✓ 浏览器内直接运行 Python 代码
- ✓ 自动批改 + 进度追踪
30天
¥18
1年
¥99
2年
¥158
3年
¥199