实战kaggle比赛房价预测完整代码
时间: 2023-10-14 18:20:37 浏览: 216
以下是一个完整的kaggle房价预测比赛的代码示例。注意,这只是一个示例,并不是唯一的解决方案。
首先,我们需要导入必要的库:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error
```
接下来,我们可以读取训练和测试数据:
```python
train_data = pd.read_csv("train.csv")
test_data = pd.read_csv("test.csv")
```
然后,我们可以进行一些基本的数据探索和清理:
```python
# 检查缺失值
print(train_data.isnull().sum())
# 删除缺失值过多的列和无关列
train_data.drop(["Alley", "PoolQC", "MiscFeature", "Id"], axis=1, inplace=True)
test_data.drop(["Alley", "PoolQC", "MiscFeature", "Id"], axis=1, inplace=True)
# 用中位数替换缺失值
train_data["LotFrontage"].fillna(train_data["LotFrontage"].median(), inplace=True)
test_data["LotFrontage"].fillna(test_data["LotFrontage"].median(), inplace=True)
train_data["MasVnrArea"].fillna(train_data["MasVnrArea"].median(), inplace=True)
test_data["MasVnrArea"].fillna(test_data["MasVnrArea"].median(), inplace=True)
train_data["GarageYrBlt"].fillna(train_data["GarageYrBlt"].median(), inplace=True)
test_data["GarageYrBlt"].fillna(test_data["GarageYrBlt"].median(), inplace=True)
# 对于其他缺失值,用众数替换
for column in train_data.columns:
if train_data[column].dtype == "object":
train_data[column].fillna(train_data[column].mode()[0], inplace=True)
test_data[column].fillna(test_data[column].mode()[0], inplace=True)
else:
train_data[column].fillna(train_data[column].median(), inplace=True)
test_data[column].fillna(test_data[column].median(), inplace=True)
# 对于分类变量,进行独热编码
train_data = pd.get_dummies(train_data)
test_data = pd.get_dummies(test_data)
# 确保训练和测试数据的列数相同
train_labels = train_data["SalePrice"]
train_data, test_data = train_data.align(test_data, join="inner", axis=1)
```
接下来,我们可以对数据进行标准化:
```python
scaler = StandardScaler()
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
```
然后,我们可以将数据拆分为训练和验证集:
```python
X_train, X_val, y_train, y_val = train_test_split(train_data, train_labels, test_size=0.2, random_state=42)
```
接下来,我们可以训练和评估几个不同的模型:
```python
# 线性回归模型
lr = LinearRegression()
lr.fit(X_train, y_train)
lr_preds = lr.predict(X_val)
print("Linear Regression RMSE:", np.sqrt(mean_squared_error(y_val, lr_preds)))
# 随机森林模型
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
rf_preds = rf.predict(X_val)
print("Random Forest RMSE:", np.sqrt(mean_squared_error(y_val, rf_preds)))
# XGBoost模型
xgb = XGBRegressor(n_estimators=100, learning_rate=0.1, random_state=42)
xgb.fit(X_train, y_train)
xgb_preds = xgb.predict(X_val)
print("XGBoost RMSE:", np.sqrt(mean_squared_error(y_val, xgb_preds)))
```
最后,我们可以用最佳模型生成提交文件:
```python
# 训练最佳模型
best_model = XGBRegressor(n_estimators=1000, learning_rate=0.05, random_state=42)
best_model.fit(train_data, train_labels)
# 生成提交文件
test_preds = best_model.predict(test_data)
submission = pd.DataFrame({"Id": test["Id"], "SalePrice": test_preds})
submission.to_csv("submission.csv", index=False)
```
这就是完整的代码示例。请注意,这只是一个可能的解决方案,你可以根据自己的需求和数据进行调整。
阅读全文