kaggle 房价预测

问题描述
代码

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

1)导入工具包

	import pandas as pd
	import 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")
### Kaggle 房价预测数据集与机器学习模型示例 房价预测是机器学习领域中一个经典的回归问题,通常用于评估模型的性能和算法的有效性。以下是一个基于Kaggle房价预测数据集的完整解决方案示例[^1]。 #### 数据预处理 在进行模型训练之前,需要对数据进行预处理。首先,将数据集拆分为训练集和测试集,并按照8:2的比例分割。这可以通过 `train_test_split` 函数实现[^3]。 ```python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( data.drop('SalePrice', axis=1), data['SalePrice'], test_size=0.2, random_state=42 ) ``` #### 特征选择与超参设置 特征选择、超参设置以及数据集预处理方式对模型的最终结果具有重要影响。这些步骤需要仔细设计以确保模型的性能最优[^1]。 #### 模型训练与评估 以下是使用多种模型进行训练和评估的代码示例。通过计算均方根误差(RMSE),可以比较不同模型的性能[^2]。 ```python import numpy as np from sklearn.metrics import mean_squared_error from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.linear_model import LinearRegression # 定义模型列表 models = [] models_name = [] # 添加模型 models.append(LinearRegression()) models_name.append('Linear Regression') models.append(RandomForestRegressor(random_state=42)) models_name.append('Random Forest') models.append(GradientBoostingRegressor(random_state=42)) models_name.append('Gradient Boosting') # 训练并评估模型 for i, model in enumerate(models): model.fit(X_train, y_train) y_preds = model.predict(X_test) model_score = np.sqrt(mean_squared_error(y_test, y_preds)) print('RMSE of {}: {}'.format(models_name[i], model_score)) ``` #### 模型堆叠(Stacking) 为了进一步提升模型性能,可以采用模型堆叠技术。以下是一个简单的堆叠模型示例。 ```python from sklearn.ensemble import StackingRegressor # 定义基础模型 base_models = [ ('lr', LinearRegression()), ('rf', RandomForestRegressor(random_state=42)), ('gb', GradientBoostingRegressor(random_state=42)) ] # 定义堆叠模型 stack_model = StackingRegressor( estimators=base_models, final_estimator=LinearRegression() ) # 训练堆叠模型 stack_model.fit(X_train, y_train) # 评估堆叠模型 y_preds = stack_model.predict(X_test) stack_model_score = np.sqrt(mean_squared_error(y_test, y_preds)) print('RMSE of Stacking Model: {}'.format(stack_model_score)) ``` #### 总结 以上代码展示了如何从数据预处理到模型训练和评估的完整流程。通过尝试不同的模型和优化方法,可以显著提高房价预测的准确性[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值