python 中的 statsmodels 包用来做线性回归分析,最小二乘法

更多专业的人工智能相关文章,微信搜索  : robot-learner , 或扫码

 

multi variable linear regression,

考虑的模型如下:

y= ax1 + bx2+cx3

其中a,b,c为参数, x1,x2,x3为三个变量。

 

python code 如下:

 

 

import statsmodels.api as sm

X=[[544.0, 27.0, 0.0],
 [786.0, 17.0, 27.0],
 [1246.0, -3.0, 44.0],
 [1934.0, 0.0, 41.0],
 [2703.0, 0.0, 41.0],
 [4472.0, 2.0, 41.0],
 [5933.0, -2.0, 43.0],
 [7670.0, 0.0, 41.0],
 [9651.0, 0.0, 41.0],
 [11733.0, 17.0, 41.0],
 [14244.0, 78.0, 58.0],
 [17007.0, 62.0, 136.0],
 [20147.0, 93.0, 198.0],
 [23884.0, 149.0, 291.0],
 [27447.0, 131.0, 440.0],
 [30331.0, 259.0, 571.0],
 [33259.0, 457.0, 830.0],
 [35223.0, 688.0, 1287.0],
 [37427.0, 769.0, 1975.0],
 [38123.0, 1771.0, 2744.0]]

Y=[34.0,
 38.0,
 49.0,
 51.0,
 60.0,
 103.0,
 124.0,
 171.0,
 243.0,
 328.0,
 475.0,
 632.0,
 892.0,
 1153.0,
 1540.0,
 2050.0,
 2649.0,
 3281.0,
 3996.0,
 4740.0]

# fit the data with OLS model
model = sm.OLS(Y, X).fit()
predictions = model.predict(X) # make the predictions by the model

# Print out the statistics
model.summary()

 

结果如下:

### Python 多元线性回归最小二乘法实现 #### 使用 Numpy 实现多元线性回归 Numpy 是一个强大的数值计算,可以用来高效地处理向量化运算。对于多元线性回归模型 \(Y = X\beta\) ,其中\(X\)是特征矩阵(括截距项),而 \(\beta\) 则是我们要估计的参数向量。 为了应用最小二乘法来拟合这个模型,可以通过下面的方式构建和解决正规方程: \[ (X^T X)\hat{\beta} = X^TY \] 从而得到最优解: \[ \hat{\beta}=(X^{T}X)^{-1}X^{T}Y \] 这里是一个简单的例子展示如何使用 NumPy 来完成这项工作[^1]: ```python import numpy as np def multivariate_linear_regression(X, Y): """ Perform Multivariate Linear Regression using Least Squares Method. Parameters: X : array-like of shape (n_samples, n_features) Training data. Y : array-like of shape (n_samples,) Target values. Returns: beta_hat : ndarray of shape (n_features + 1,) Estimated coefficients including intercept term. """ # Add a column of ones to the input features matrix for the bias/intercept coefficient X_with_intercept = np.c_[np.ones((len(X), 1)), X] # Calculate Beta Hat according to formula mentioned above beta_hat = np.linalg.inv(X_with_intercept.T @ X_with_intercept) @ X_with_intercept.T @ Y return beta_hat # Example usage with synthetic dataset if __name__ == "__main__": rng = np.random.RandomState(42) # Generate some random training samples and targets num_samples = 100 num_features = 3 true_coefficients = [-5., 2., -1.5, .7] # Including Intercept Term noise_level = 1e-1 X_train = rng.randn(num_samples, num_features) y_train = X_train.dot(true_coefficients[1:]) + true_coefficients[0] \ + rng.normal(scale=noise_level, size=num_samples) estimated_coeffs = multivariate_linear_regression(X_train, y_train) print(f"Estimated Coefficients:\n{estimated_coeffs}") ``` 这段代码定义了一个名为 `multivariate_linear_regression` 的函数,它接受两个参数——输入特征矩阵 `X` 和目标值向量 `Y` 。该函数返回的是通过最小二乘法估算出来的系数向量 `\hat{\beta}` 。 #### 使用 Scipy 进行优化求解 Scipy 提供了更高级别的接口来进行最优化问题的求解,在某些情况下可能更加便捷。特别是当涉及到非线性的约束条件或者其他复杂情况时。但对于标准形式下的最小二乘问题来说,可以直接调用 `scipy.optimize.least_squares()` 函数。 不过需要注意的是,这种方法通常用于非线性最小二乘问题;而对于线性的情况,则推荐继续采用前面提到的方法或是直接转到下一节介绍的内容。 #### 使用 Statsmodels 简化建模过程 Statsmodels 是专门为统计分析设计的一个Python,提供了丰富的工具集支持各种类型的回归分析以及其他常见的经济计量学操作。在这个场景下,只需要几行代码就可以轻松建立并评估一个多变量线性回归模型。 下面是具体法: ```python import pandas as pd import statsmodels.api as sm df = pd.DataFrame({ 'x1': ... , # Replace these lines with actual feature columns from your dataset 'x2': ... }) target_column_name = '' # Specify target variable name here model = sm.OLS(endog=df[target_column_name], exog=sm.add_constant(df.drop(columns=[target_column_name]))) results = model.fit() print(results.summary()) ``` 在这段脚本里,首先创建了一个 Pandas DataFrame 对象 df 并填充好相应的自变量列名。接着指定了因变量的名字,并将其余所有的自变量传递给 OLS 类构造器作为解释变量(exogenous variables),同时记得加上常数项(intercept)。最后调用了 fit 方法执行实际的拟合流程,并打印出详细的摘要信息 summary()。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值