You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

11 months ago
import numpy as np
import matplotlib.pyplot as plt
# 定义待拟合的函数形式
def func(x, coeffs):
return coeffs[0] * x + coeffs[1]
# 定义目标函数,即待拟合数据
def target_func(x):
return 2.5 * x + 1.2
# 生成带噪声的待拟合数据
np.random.seed(0)
x_data = np.linspace(0, 10, 100)
y_data = target_func(x_data) + np.random.normal(0, 0.5, 100)
# 定义损失函数,即拟合函数与目标函数之间的差距
def loss_func(coeffs, x, y):
return np.mean((y - func(x, coeffs))**2)
# 定义梯度计算函数,即损失函数对于系数的偏导数
def gradient_func(coeffs, x, y):
gradient = np.zeros_like(coeffs)
gradient[0] = -2 * np.mean((y - func(x, coeffs)) * x)
gradient[1] = -2 * np.mean(y - func(x, coeffs))
return gradient
# 初始化参数
learning_rate = 0.01
num_iterations = 1000
initial_coeffs = np.array([1.0, 1.0], dtype=float)
# 使用梯度下降法拟合函数
coeffs = initial_coeffs
for i in range(num_iterations):
gradient = gradient_func(coeffs, x_data, y_data)
coeffs -= learning_rate * gradient
# 打印拟合得到的系数
print("拟合得到的系数:", coeffs)
# 绘制拟合结果
x_fit = np.linspace(0, 10, 100)
y_fit = func(x_fit, coeffs)
plt.plot(x_data, y_data, 'bo', label='原始数据')
plt.plot(x_fit, y_fit, 'r-', label='拟合曲线')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()