基于决策树算法对房价预测(包含数据集和代码)
时间: 2024-01-12 10:02:28 浏览: 139
决策树预测算法
好的,以下是基于决策树算法对房价预测的代码和数据集:
首先,我们需要准备数据集。此处使用的是scikit-learn库自带的波士顿房价数据集。
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import pandas as pd
data = load_boston()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['price'] = data.target
X_train, X_test, y_train, y_test = train_test_split(df[data.feature_names], df['price'], test_size=0.2, random_state=42)
```
接着,我们使用sklearn库中的DecisionTreeRegressor类建立决策树模型,并训练模型:
```python
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor(max_depth=5)
model.fit(X_train, y_train)
```
最后,我们使用测试集进行模型评估:
```python
from sklearn.metrics import mean_squared_error
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)
```
完整代码如下:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
import pandas as pd
# 准备数据集
data = load_boston()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['price'] = data.target
X_train, X_test, y_train, y_test = train_test_split(df[data.feature_names], df['price'], test_size=0.2, random_state=42)
# 建立决策树模型并训练
model = DecisionTreeRegressor(max_depth=5)
model.fit(X_train, y_train)
# 模型评估
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)
```
希望能对你有所帮助!
阅读全文