当前位置: 代码迷 >> 综合 >> kaggle 房价预测
  详细解决方案

kaggle 房价预测

热度:30   发布时间:2023-11-22 18:03:30.0

问题描述
代码

经典的回归问题,过了一遍流程。

1)导入工具包

	import pandas as pdimport numpy as np import matplotlib.pyplot as plt %matplotlib inline

2)导入数据集,分割为训练集、测试集

train_df = pd.read_csv('house_price_data/train.csv',index_col=0)
test_df = pd.read_csv('house_price_data/test.csv',index_col=0)#查看数据
train_df.head()#查看标签缺失值
(train_df['SalePrice'] == 0).sum()#训练集标签平滑化处理
y_train = np.log1p(train_df.pop('SalePrice'))

3)特征工程

#对所有数据的特征一起处理
all_df = pd.concat((train_df, test_df), axis=0)#选择性将连续值特征转离散特征
all_df['MSSubClass'] = all_df['MSSubClass'].astype(str)#离散特征做one-hot处理
all_df_dummy = pd.get_dummies(all_df)#缺失数据处理
mean_cols = all_df_dummy.mean()
all_df_dummy = all_df_dummy.fillna(mean_cols)#连续值特征标准化处理
numeric_cols = all_df.columns[all_df.dtypes!='object']
numeric_cols_mean = all_df_dummy.loc[:,numeric_cols].mean()
numeric_cols_std = all_df_dummy.loc[:,numeric_cols].std()
all_df_dummy.loc[:,numeric_cols] = (all_df_dummy.loc[:,numeric_cols] - numeric_cols_mean) / numeric_cols_std

4)建立模型

train_df_dummy = all_df_dummy.loc[train_df.index]
test_df_dummy = all_df_dummy.loc[test_df.index]#data frame转numpy array
X_train = train_df_dummy.values
X_test = test_df_dummy.values
X_train.shape, X_test.shape#4.1构建岭回归模型
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
#grid search调参
alphas = np.logspace(-3, 2, 50)
test_scores = []
for alpha in alphas:clf = Ridge(alpha)# cross validation 取平均测试误差test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=10, scoring='neg_mean_squared_error'))test_scores.append(np.mean(test_score))import matplotlib.pyplot as plt 
%matplotlib inline
plt.plot(alphas,test_scores)
plt.title("Alpha vs Cross Validation Error")  #如图,alpha取15#4.2构建随机森林模型
from sklearn.ensemble import RandomForestRegressor
max_features = [.1, .3, .5, .7, .9, .99]
test_scores = []
for max_feat in max_features:clf = RandomForestRegressor(n_estimators=200, max_features=max_feat)  #n_estimators表示决策树的数量test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=5, scoring='neg_mean_squared_error'))test_scores.append(np.mean(test_score))import matplotlib.pyplot as plt 
%matplotlib inline
plt.plot(max_features,test_scores)
plt.title("max_features vs Cross Validation Error")  #如图,max_feature取0.3

5)模型集成

#定义模型
ridge = Ridge(alpha=15)
rf = RandomForestRegressor(n_estimators=500, max_features=0.3)#拟合数据
ridge.fit(X_train, y_train)
rf.fit(X_train, y_train)#预测结果
y_ridge = np.expm1(ridge.predict(X_test))  #训练集做过标签平滑,还原到正确的结果
y_rf = np.expm1(rf.predict(X_test))#回归问题采用平均法做集成
y_final = (y_ridge + y_rf) / 2

6)提交结果(以df方式)

submission_df = pd.DataFrame(data= {
    'SalePrice': y_final},index = test_df.index)
submission_df.to_csv("house_price_submission.csv")