python请使用线性回归算法对波士顿房价进行预测
时间: 2023-09-16 14:13:46 浏览: 102
好的,以下是实现步骤:
1. 导入所需的库和数据集:
```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 mean_squared_error
boston = load_boston()
X = boston.data
y = boston.target
```
2. 分割数据集,将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
```
3. 构建线性回归模型,并对训练集进行训练:
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
4. 对测试集进行预测:
```python
y_pred = model.predict(X_test)
```
5. 计算模型的均方误差:
```python
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
```
完整代码如下:
```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 mean_squared_error
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)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
```
希望对你有帮助!
阅读全文