python 多元非线性回归
时间: 2025-02-16 17:10:54 浏览: 46
### Python 实现多元非线性回归分析
#### 使用 Scikit-Learn 和 Numpy 进行多元非线性回归
对于多元非线性回归,可以利用 `PolynomialFeatures` 将原始特征转换成更高阶的多项式特征,再应用线性回归模型。这使得能够拟合更复杂的函数关系。
```python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
import numpy as np
# 创建模拟数据集
np.random.seed(0)
X = np.sort(np.random.rand(40, 2), axis=0) # 多元输入
y = X[:, 0]**2 + X[:, 1]**3 + np.random.randn(40)/10 # 非线性目标变量
# 定义多项式回归器
degree = 3
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
# 训练模型
model.fit(X, y)
# 输出系数
print("Model coefficients:", model.named_steps['linearregression'].coef_)
```
此代码片段展示了如何创建一个三阶多项式的回归模型来处理两个独立变量的数据[^1]。通过调整 `degree` 参数可改变多项式的复杂度。
为了更好地理解模型性能,还可以计算决定系数 R² 来衡量拟合优劣:
```python
r_squared = model.score(X, y)
print(f'R-squared score: {r_squared:.3f}')
```
此外,在某些情况下可能需要解决最小二乘法问题以获得最优参数估计值。此时可以用到 NumPy 的 `linalg.lstsq()` 函数:
```python
coefficient_matrix = np.vander(X.ravel(), degree+1)
solution, residuals, rank, s_values = np.linalg.lstsq(coefficient_matrix, y, rcond=None)
print("Solution via lstsq:", solution)
```
这段代码使用 Vandermonde 矩阵构建了设计矩阵,并调用了 `lstsq` 方法求解未知数向量 \( \beta \)[^3]。
阅读全文
相关推荐
















