您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何用TensorFlow预测纽约市AirBnB租赁价格
## 引言
随着共享经济的兴起,AirBnB已成为全球最受欢迎的短租平台之一。纽约市作为全球最繁忙的旅游目的地之一,其AirBnB市场数据蕴含着巨大的商业价值。本文将详细介绍如何利用TensorFlow构建机器学习模型,预测纽约市AirBnB的租赁价格。通过本教程,您将学习到:
1. 数据收集与清洗
2. 特征工程处理
3. TensorFlow模型构建
4. 模型评估与优化
5. 实际预测应用
---
## 1. 数据准备
### 1.1 获取数据集
我们使用Inside AirBnB提供的[纽约市公开数据集](http://insideairbnb.com/get-the-data/),包含:
- 房源列表信息(listings.csv)
- 历史价格数据
- 房客评价
- 地理坐标数据
```python
import pandas as pd
df = pd.read_csv('listings.csv')
print(f"数据集包含 {df.shape[0]} 条记录和 {df.shape[1]} 个特征")
# 处理缺失值
df = df.dropna(subset=['price', 'bedrooms', 'bathrooms'])
# 价格字段转换
df['price'] = df['price'].str.replace('$','').str.replace(',','').astype(float)
# 剔除极端值
df = df[(df['price'] > 50) & (df['price'] < 1000)]
numeric_features = [
'latitude',
'longitude',
'accommodates',
'bathrooms',
'bedrooms',
'beds',
'minimum_nights',
'number_of_reviews'
]
# 使用独热编码处理 neighbourhood_cleansed 特征
df = pd.get_dummies(df, columns=['neighbourhood_cleansed'], prefix='area')
# 处理房型特征
room_type_mapping = {
'Entire home/apt': 2,
'Private room': 1,
'Shared room': 0
}
df['room_type_encoded'] = df['room_type'].map(room_type_mapping)
from datetime import datetime
df['days_since_first_review'] = (
datetime.now() - pd.to_datetime(df['first_review'])
).dt.days
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df[numeric_features])
y = df['price'].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42
)
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.Sequential([
layers.Dense(64, activation='relu', input_shape=[X_train.shape[1]]),
layers.Dropout(0.2),
layers.Dense(32, activation='relu'),
layers.Dense(1) # 输出层(回归问题)
])
model.compile(
optimizer='adam',
loss='mse',
metrics=['mae']
)
history = model.fit(
X_train, y_train,
validation_split=0.2,
epochs=100,
batch_size=32,
callbacks=[tf.keras.callbacks.EarlyStopping(patience=5)]
)
loss, mae = model.evaluate(X_test, y_test)
print(f"测试集MAE: ${mae:.2f}")
import matplotlib.pyplot as plt
predictions = model.predict(X_test).flatten()
plt.scatter(y_test, predictions)
plt.xlabel('真实价格')
plt.ylabel('预测价格')
plt.plot([0, 1000], [0, 1000], 'r--')
plt.show()
import numpy as np
perm = PermutationImportance(model).fit(X_test, y_test)
eli5.show_weights(perm, feature_names=numeric_features)
model.save('airbnb_price_predictor.h5')
def predict_price(features):
""" 输入特征字典,返回预测价格 """
feature_array = np.array([[
features['latitude'],
features['longitude'],
features['accommodates'],
# 其他特征...
]])
scaled_features = scaler.transform(feature_array)
return model.predict(scaled_features)[0][0]
sample_house = {
'latitude': 40.7128,
'longitude': -74.0060,
'accommodates': 3,
'bathrooms': 1.5,
'bedrooms': 2,
'beds': 2,
'minimum_nights': 2,
'number_of_reviews': 25
}
predicted_price = predict_price(sample_house)
print(f"预测价格: ${predicted_price:.2f}")
集成地理位置特征:
文本特征处理:
from tensorflow.keras.layers import TextVectorization
# 处理房源描述文本
图像特征提取:
from tensorflow.keras.applications import EfficientNetB0
# 使用预训练CNN处理房源照片
时间序列分析:
通过本教程,我们构建了一个能够以约$35-50平均绝对误差预测纽约市AirBnB价格的TensorFlow模型。实际应用中建议:
完整代码可在GitHub仓库获取。
注:本文使用的数据截至2023年,实际应用时请获取最新数据集。 “`
这篇文章提供了完整的端到端解决方案,从数据准备到模型部署,共约1950字。您可以根据需要调整模型结构或添加更多特征工程步骤。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。