python: Random Forest

ruby 复制代码
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Random Forest
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
# Datetime  : 2026/11/26 23:43 
# User      :  geovindu
# Product   : PyCharm
# Project   : Pysimple
# File      : RandomForest.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, accuracy_score

plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'sans-serif']
plt.rcParams['axes.unicode_minus'] = False

# ==========================================
# 1. 准备数据
# ==========================================
data = {
    2000: 5420, 2002: 5800, 2004: 6500, 2006: 9200, 2008: 12500,
    2010: 16800, 2012: 21000, 2014: 24500, 2016: 42000, 2018: 54000,
    2020: 68000, 2021: 72000, 2022: 69000, 2023: 65000, 2024: 62000,
    2025: 60000
}
df = pd.DataFrame(list(data.items()), columns=['年份', '均价'])

# ==========================================
# 2. 特征工程
# ==========================================
df['前一年均价'] = df['均价'].shift(1)
df['前一年涨幅'] = df['均价'].pct_change()
df['当年涨幅'] = df['均价'].pct_change()
df['是否大涨'] = (df['当年涨幅'] > 0.05).astype(int)
df = df.dropna().reset_index(drop=True)

# ★★★ 关键修复:只取这两列作为特征,排除 年份/均价/当年涨幅/是否大涨 ★★★
FEATURES = ['前一年均价', '前一年涨幅']
X = df[FEATURES]
y = df['是否大涨']

print("📊 特征矩阵 X:")
print(X)
print("\n📊 标签 y:")
print(y)

# ==========================================
# 3. 划分训练集与测试集
# ==========================================
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42, stratify=y
)

# ==========================================
# 4. 随机森林(不需要标准化)
# ==========================================
print("\n" + "=" * 50)
print("🌲 随机森林分类模型")
print("=" * 50)

rf_model = RandomForestClassifier(
    n_estimators=100, max_depth=3, random_state=42, class_weight='balanced'
)
rf_model.fit(X_train, y_train)

rf_pred = rf_model.predict(X_test)
print(f"准确率: {accuracy_score(y_test, rf_pred):.2f}")
print("\n分类报告:")
print(classification_report(y_test, rf_pred,
                            target_names=['平稳/下跌 (0)', '大幅上涨 (1)'],
                            zero_division=0))

print("\n🌟 特征重要性:")
for name, imp in zip(FEATURES, rf_model.feature_importances_):
    print(f"- {name}: {imp:.4f}")

# ==========================================
# 5. KNN(必须标准化)
# ==========================================
print("\n" + "=" * 50)
print("🎯 K近邻分类模型")
print("=" * 50)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)   # 此时 scaler 只记录 2 个特征名
X_test_scaled = scaler.transform(X_test)

knn_model = KNeighborsClassifier(n_neighbors=3)
knn_model.fit(X_train_scaled, y_train)

knn_pred = knn_model.predict(X_test_scaled)
print(f"准确率: {accuracy_score(y_test, knn_pred):.2f}")
print("\n分类报告:")
print(classification_report(y_test, knn_pred,
                            target_names=['平稳/下跌 (0)', '大幅上涨 (1)'],
                            zero_division=0))

# ==========================================
# 6. 预测 2026 年
# ==========================================
last_year_price = 60000
last_year_pct = (60000 - 62000) / 62000

# ★★★ 关键修复:列名必须与 FEATURES 完全一致 ★★★
future_X = pd.DataFrame([[last_year_price, last_year_pct]], columns=FEATURES)
future_X_scaled = scaler.transform(future_X)     # 这里不再报错

rf_prob = rf_model.predict_proba(future_X)[0][1]
knn_prob = knn_model.predict_proba(future_X_scaled)[0][1]

print("\n" + "=" * 50)
print("🔮 2026年深圳房价趋势预测对比")
print("=" * 50)
print(f"基于 2025 年数据 (均价: {last_year_price}元, 涨幅: {last_year_pct:.2%})")
print(f"【随机森林】大涨概率: {rf_prob:.2%} -> {'大幅上涨' if rf_prob > 0.5 else '平稳/下跌'}")
print(f"【K近邻】  大涨概率: {knn_prob:.2%} -> {'大幅上涨' if knn_prob > 0.5 else '平稳/下跌'}")

# ==========================================
# 7. KNN 决策边界可视化
# ==========================================
plt.figure(figsize=(10, 6))
plt.scatter(X_test_scaled[:, 0], X_test_scaled[:, 1], c=y_test,
            cmap='coolwarm', edgecolors='k', label='测试集真实值')

x_min, x_max = X_test_scaled[:, 0].min() - 1, X_test_scaled[:, 0].max() + 1
y_min, y_max = X_test_scaled[:, 1].min() - 1, X_test_scaled[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
                     np.arange(y_min, y_max, 0.01))
Z = knn_model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.3, cmap='coolwarm')

plt.xlabel('标准化后的前一年均价')
plt.ylabel('标准化后的前一年涨幅')
plt.title('KNN分类:深圳房价是否大幅上涨预测 (决策边界)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
相关推荐
真上帝的左手24 分钟前
2. 编程语言-Python-Anaconda
开发语言·python
aifannihao29 分钟前
断言从 == 改成 > 0:用 Python 审出 git diff 里的测试降级
git·python·测试·标准库·代码审查
高洁011 小时前
具身智能的人机协作与物理空间安全
人工智能·python·深度学习·机器学习·django
.道阻且长.1 小时前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展
zc.z1 小时前
提示词工程(十三):Agent System Prompt 设计——知识体系、深度讲解与面试实战
python·prompt·提示词工程·prompt实战技巧·prompt技术
苏三说技术1 小时前
Spring AI 2.1 正式发布 ,新增一个重要功能
后端
凌冰_1 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏1 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
Rain的Java大神之路3 小时前
Spring AI 2.0 GA 深度复盘:Java 后端做 AI 的分水岭,到底画在哪?
java·后端·aigc