sklearn线性回归
时间: 2023-06-21 08:03:37 浏览: 95
sklearn是一个Python的机器学习库,其中包含了许多常见的机器学习算法,包括线性回归。下面简要介绍如何使用sklearn进行线性回归。
首先,需要导入sklearn库和数据集。我们可以使用sklearn内置的波士顿房价数据集进行演示:
```python
from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data
y = boston.target
```
接下来,我们需要将数据集分成训练集和测试集。我们可以使用train_test_split函数,将数据集随机分成训练集和测试集:
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
然后,我们可以创建一个LinearRegression对象,并使用fit函数进行训练:
```python
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
```
最后,我们可以使用predict函数对测试集进行预测,并计算出模型的评分(即R2值):
```python
from sklearn.metrics import r2_score
y_pred = model.predict(X_test)
score = r2_score(y_test, y_pred)
print("R2 score:", score)
```
完整的代码如下:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
boston = load_boston()
X = boston.data
y = boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score = r2_score(y_test, y_pred)
print("R2 score:", score)
```
这就是使用sklearn进行线性回归的基本流程。
阅读全文