python线性回归 中意灬
时间: 2023-11-06 10:02:25 浏览: 34
线性回归是一种回归分析方法,用于分析两个或多个变量之间的相关关系及其程度。在Python中,可以使用sklearn库进行线性回归的建模和预测。岭回归是线性回归的一种扩展方法,通过添加正则化项来解决过拟合的问题。
以下是使用Python进行线性回归的代码示例:
```python
import sklearn.linear_model
import sklearn.datasets
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 导入数据集
X, Y = sklearn.datasets.load_diabetes(return_X_y=True)
X = X[:, np.newaxis, 2]
# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)
# 构建线性回归模型
clf = sklearn.linear_model.LinearRegression()
# 训练模型
clf.fit(X_train, y_train)
# 测试模型
y_pred = clf.predict(X_test)
# 输出模型评估结果
print('回归系数a:', clf.coef_)
print('截距b:', clf.intercept_)
print('均方误差MSE:', mean_squared_error(y_pred, y_test))
print('决定系数R^2:', clf.score(X_test, y_test))
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)