sklearn实现线性回归
时间: 2023-11-09 12:04:34 浏览: 102
sklearn实现线性回归的步骤如下所示:
1. 导入必要模块:
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
```
2. 加载数据:
```
# 以波士顿房价数据集为例
boston = datasets.load_boston()
X = boston.data
y = boston.target
```
3. 划分训练集和测试集:
```
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
4. 创建线性回归模型对象:
```
lin_reg = LinearRegression()
```
5. 训练模型:
```
lin_reg.fit(X_train, y_train)
```
6. 预测结果:
```
y_pred = lin_reg.predict(X_test)
```
通过以上步骤,我们可以使用sklearn库中的LinearRegression类实现线性回归,并对给定的特征数据进行预测。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [sklearn之线性回归](https://blog.csdn.net/luguojiu/article/details/103252707)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [Sklearn——用Sklearn实现线性回归(LinearRegression)](https://blog.csdn.net/weixin_37763870/article/details/105161775)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文