线性回归实践,波斯顿房价预测的代码
时间: 2024-09-19 22:00:45 浏览: 75
线性回归是一种常见的统计分析方法,常用于预测连续变量。在波士顿房价预测的实践中,我们可以使用Python的scikit-learn库来进行。以下是一个简单的例子:
```python
# 导入所需的库
import pandas as pd
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, r2_score
# 加载波士顿房价数据集
boston = load_boston()
data = pd.DataFrame(boston.data, columns=boston.feature_names)
target = boston.target # 房价
# 划分特征和目标变量,并将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)
# 创建并训练线性回归模型
model = LinearRegression()
model.fit(X_train, y_train)
# 预测测试集结果
y_pred = model.predict(X_test)
# 计算评估指标
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error:", mse)
print("R-squared Score:", r2)
阅读全文