🤵♂️ 个人主页:@艾派森的个人主页
✍🏻作者简介:Python学习者
🐋 希望大家多多支持,我们一起进步!😄
如果文章对你有帮助的话,
欢迎评论 💬点赞👍🏻 收藏 📂加关注+
目录
1.项目背景
2.数据集介绍
3.技术工具
4.实验过程
4.1导入数据
4.2数据预处理
4.3数据可视化
4.4特征工程
4.5构建模型
4.6模型预测
源代码
1.项目背景
在当今的房地产市场中,公寓租赁价格的准确预测对于租户、房东以及房地产投资者而言至关重要。随着城市化进程的加速和人口流动的频繁,公寓租赁市场日益活跃,但价格的波动性也给市场参与者带来了挑战。
近年来,数据科学和机器学习技术的飞速发展为房地产市场的价格预测提供了强大的工具。其中,决策树回归算法作为一种直观、易于解释且能够处理非线性关系的算法,在房价预测领域得到了广泛应用。决策树通过递归地将数据划分为不同的子集,并基于特征的不同取值进行决策,最终形成一个树状结构的模型。这种模型不仅能够捕捉变量之间的复杂关系,还能提供直观的决策路径,使得预测结果易于理解和解释。
本实验旨在利用决策树回归算法构建一个公寓租赁价格预测模型。我们将收集并整理包含公寓租赁价格及其相关特征(如地理位置、房屋面积、装修程度、交通便利性等)的数据集。这些数据将作为模型训练和验证的基础。
在实验过程中,我们首先将对数据进行预处理,包括数据清洗、缺失值处理、异常值检测与剔除以及特征编码等步骤,以确保数据的准确性和一致性。随后,我们将利用决策树回归算法对数据进行训练,构建出能够预测公寓租赁价格的模型。在模型训练过程中,我们将通过调整算法参数(如树的深度、分裂标准等)来优化模型性能,并采用交叉验证等方法来评估模型的稳定性和泛化能力。
最终,我们将通过对比实际租赁价格与模型预测价格之间的差异来评估模型的预测精度。同时,我们还将分析模型在不同特征组合下的表现,以揭示哪些特征对公寓租赁价格的影响最为显著。这些信息不仅有助于我们更好地理解公寓租赁市场的运作机制,还能为市场参与者提供有价值的参考和指导。
2.数据集介绍
本实验数据集来源于Kaggle,原始数据集共有99492条,22个变量。该数据集包含有关公寓租赁的详细信息,非常适合各种机器学习任务,包括聚类、分类和回归。它具有一套全面的属性,可以捕捉租赁清单的基本方面,例如:
标识符和位置:包括唯一标识符 (id)、地理详细信息(地址、城市名称、州、纬度、经度)和分类列表的来源。
房产详情:提供有关公寓类别、标题、主体、便利设施、浴室数量、卧室和平方英尺(公寓面积)的信息。
定价信息:包含与定价相关的多个功能,包括价格(租金)、price_display(显示价格)、price_type(美元价格)和费用。
附加功能:指示公寓是否有照片(has_photo)、是否允许携带宠物(pets_allowed)以及其他相关详细信息,如货币和列表创建时间。
3.技术工具
Python版本:3.9
代码编辑器:jupyter notebook
4.实验过程
4.1导入数据
导入第三方库并加载数据集
查看数据大小
查看数据基本信息
查看数据的描述性统计
4.2数据预处理
统计缺失值情况
发现原始数据集在个别变量上缺失很多
统计重复值情况
删除缺失值和重复值
再次查看数据集大小
4.3数据可视化
plt.figure(figsize=(10,5))
plt.pie(df['pets_allowed'].value_counts().head(2), labels=df['pets_allowed'].value_counts().index[:2], autopct='%1.1f%%', startangle=90, colors=['#ff9999','#66b3ff'])
plt.title('Pets Allowed')
plt.show()
4.4特征工程
对非数值型变量进行编码处理
准备建模数据X和y
将数据集拆分为训练集和测试集,用随机森林模型得出特征重要性
4.5构建模型
初始化模型,接着进行训练并使用模型R方进行模型评估
从评估结果来看,决策树模型的R方最大,为0.96
故我们采用决策树模型作为最终训练模型
4.6模型预测
随机抽取10条真实值和预测值的数据进行对比
可以发现预测值与真实值非常接近
接着我们将预测结果进行可视化展示
可以发现预测曲线与真实曲线几乎完全重合,说明模型拟合效果非常不错!
源代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings('ignore')df = pd.read_csv('apartments_for_rent_classified_100K.csv', sep=";", encoding='cp1252')
df.head()
df.shape
df.info()
df.describe().T
df.isnull().sum()
df.duplicated().sum()
df.dropna(inplace=True)
df.drop_duplicates(inplace=True)
df.shape
plt.figure(figsize=(10,6))
sns.countplot(x='pets_allowed', data=df, palette='viridis')
plt.title('Pets Allowed Count')
plt.show()
plt.figure(figsize=(10,5))
plt.pie(df['pets_allowed'].value_counts().head(2), labels=df['pets_allowed'].value_counts().index[:2], autopct='%1.1f%%', startangle=90, colors=['#ff9999','#66b3ff'])
plt.title('Pets Allowed')
plt.show()
plt.figure(figsize=(10,6))
sns.countplot(x='has_photo',data=df,palette='viridis')
plt.title('Has_photo')
plt.show()
plt.figure(figsize=(10,5))
plt.pie(df['has_photo'].value_counts(), labels=df['has_photo'].value_counts().index, autopct='%1.1f%%', startangle=90,)
plt.title('Has Photo')
plt.show()
plt.figure(figsize=(10,6))
top10cities=df['cityname'].value_counts().head(10)
sns.countplot(y=top10cities.index, palette='viridis')
plt.title('Top 10 cities')
plt.show()
plt.figure(figsize=(10,6))
plt.pie(df['cityname'].value_counts().head(10), labels=df['cityname'].value_counts().index[:10], autopct='%1.1f%%', startangle=90)
plt.title('Top 10 cities')
plt.show()
plt.figure(figsize=(10,6))
top10states=df['state'].value_counts().head(10)
sns.countplot(y=top10states.index, palette='viridis', order=top10states.index)
plt.title('Top 10 States')
plt.xlabel('Count')
plt.ylabel('State')
plt.show()
# 编码处理
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
for column in df.select_dtypes(include=['object']).columns:df[column] = label_encoder.fit_transform(df[column])df.head()
x = df.drop(columns=['price', 'category', 'fee', 'has_photo', 'price_type', 'currency','pets_allowed','source'], axis=1)
y = df['price']
from sklearn.ensemble import RandomForestClassifier
# 将数据集拆分为训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 初始化随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
# 训练模型
rf.fit(x_train, y_train)
# 获取特征重要性
feature_importances = rf.feature_importances_
feature_importances_df = pd.DataFrame({'Feature': x.columns,'Importance': feature_importances
}).sort_values(by='Importance', ascending=False)print(feature_importances_df)
from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor, BaggingRegressor
from lightgbm import LGBMRegressor
from xgboost import XGBRegressor
from catboost import CatBoostRegressor
from sklearn.metrics import r2_score,mean_absolute_error# 初始化模型
models = {'SVR': SVR(),'Linear Regression': LinearRegression(),'Decision Tree': DecisionTreeRegressor(),'Random Forest': RandomForestRegressor(random_state=42),'LGBM': LGBMRegressor(random_state=42),'XGB': XGBRegressor(random_state=42),'CatBoost': CatBoostRegressor(verbose=0, random_state=42),'AdaBoost': AdaBoostRegressor(random_state=42),'Bagging': BaggingRegressor(random_state=42)
}# 训练并评估模型
for name, model in models.items():model.fit(x_train, y_train)y_pred = model.predict(x_test)score = r2_score(y_test, y_pred)print(f"{name} R^2 score: {score:.4f}")
# 构建决策树模型
from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor()
tree.fit(x_train, y_train)
y_pred = tree.predict(x_test)
# 模型评估
print("mean_absolute_error:", mean_absolute_error(y_test, y_pred))
print("R-squared score:", r2_score(y_test, y_pred))
# 模型预测
result_df = pd.DataFrame()
result_df['真实值'] = y_test
result_df['预测值'] = y_pred
result_df.head(10)
# 模型预测
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.plot(range(len(y_test))[:100],y_pred[:100],'b',label='predict')
plt.plot(range(len(y_test))[:100],y_test[:100],'r',label='test')
plt.legend(loc='upper right')
plt.xlabel('the number of Airline',fontdict={'weight': 'normal', 'size': 15})
plt.ylabel('value of Fare',fontdict={'weight': 'normal', 'size': 15})
plt.show()