python调用最小二乘法
时间: 2024-01-02 15:23:07 浏览: 75
Python基于最小二乘法实现曲线拟合示例
以下是使用Python调用最小二乘法的示例:
1. 线性最小二乘法:
```python
import numpy as np
from scipy.optimize import least_squares
# 定义目标函数
def target_func(x, a, b):
return a * x + b
# 定义误差函数
def error_func(params, x, y):
a, b = params
return target_func(x, a, b) - y
# 输入数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3.9, 6.1, 8.2, 9.8])
# 初始参数值
initial_params = np.array([0, 0])
# 调用最小二乘法
result = least_squares(error_func, initial_params, args=(x, y))
# 输出结果
a, b = result.x
print("最小二乘法拟合结果:")
print(f"a = {a:.4f}")
print(f"b = {b:.4f}")
```
2. 非线性最小二乘法:
```python
import numpy as np
from scipy.optimize import least_squares
# 定义目标函数
def target_func(params, x):
a, b, c = params
return a * np.exp(-b * x) + c
# 定义误差函数
def error_func(params, x, y):
return target_func(params, x) - y
# 输入数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([1.2, 1.9, 3.1, 3.8, 4.9])
# 初始参数值
initial_params = np.array([1, 1, 1])
# 调用最小二乘法
result = least_squares(error_func, initial_params, args=(x, y))
# 输出结果
a, b, c = result.x
print("最小二乘法拟合结果:")
print(f"a = {a:.4f}")
print(f"b = {b:.4f}")
print(f"c = {c:.4f}")
```
阅读全文