python:Logistic Regression

python 复制代码
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Logistic Regression
# 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 20:36 
# User      :  geovindu
# Product   : PyCharm
# Project   : Pysimple
# File      : LogisticRegression.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

# 设置中文字体,防止图表乱码
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'sans-serif']
plt.rcParams['axes.unicode_minus'] = False

# ==========================================
# 1. 准备数据 (2000-2025年部分代表性年份的深圳均价,单位:元/㎡)
# ==========================================
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
}

# 转换为 DataFrame
df = pd.DataFrame(list(data.items()), columns=['年份', '均价'])

# ==========================================
# 2. 特征工程 (Feature Engineering)
# ==========================================
# 逻辑回归需要特征来预测结果。我们构造两个特征:
# 1. 前一年的均价 (lag_1)
# 2. 前一年的涨幅百分比 (pct_change)
df['前一年均价'] = df['均价'].shift(1)
df['前一年涨幅'] = df['均价'].pct_change()

# 去除因 shift 产生的空值
df = df.dropna()

# 定义目标变量 (Target):如果当年涨幅 > 5%,标记为 1 (大幅上涨),否则为 0 (平稳或下跌)
df['当年涨幅'] = df['均价'].pct_change()
df['是否大涨'] = (df['当年涨幅'] > 0.05).astype(int)

# 再次去除空值
df = df.dropna()

# 提取特征 (X) 和标签 (y)
# 我们使用 '前一年均价' 和 '前一年涨幅' 来预测 '当年是否大涨'
X = df[['前一年均价', '前一年涨幅']]
y = df['是否大涨']

print("📊 准备的数据集:")
print(df[['年份', '前一年均价', '前一年涨幅', '当年涨幅', '是否大涨']])

# ==========================================
# 3. 划分训练集与测试集
# ==========================================
# 由于数据量较小,这里测试集占 30%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)

# 特征标准化 (逻辑回归对特征尺度敏感,必须标准化)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# ==========================================
# 4. 构建与训练逻辑回归模型
# ==========================================
# 设置 max_iter 增加最大迭代次数,防止不收敛
model = LogisticRegression(random_state=42, max_iter=1000)
model.fit(X_train_scaled, y_train)

# ==========================================
# 5. 模型评估
# ==========================================
y_pred = model.predict(X_test_scaled)
y_prob = model.predict_proba(X_test_scaled)[:, 1] # 获取预测为 1 (大涨) 的概率

print("\n" + "="*50)
print("📈 模型评估结果")
print("="*50)
print(f"准确率 (Accuracy): {accuracy_score(y_test, y_pred):.2f}")
print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=['平稳/下跌 (0)', '大幅上涨 (1)']))

print("混淆矩阵:")
print(confusion_matrix(y_test, y_pred))

# ==========================================
# 6. 预测未来 (2026年)
# ==========================================
# 假设我们要预测 2026 年。我们需要 2025 年的数据作为特征
# 2025年均价为 60000,2024年为 62000,涨幅为 (60000-62000)/62000
last_year_price = 60000
last_year_pct = (60000 - 62000) / 62000

future_X = pd.DataFrame({'前一年均价': [last_year_price], '前一年涨幅': [last_year_pct]})
future_X_scaled = scaler.transform(future_X)

# 预测概率和类别
prob = model.predict_proba(future_X_scaled)[0][1]
pred_class = model.predict(future_X_scaled)[0]

print("\n" + "="*50)
print("🔮 2026年深圳房价趋势预测")
print("="*50)
print(f"基于 2025 年数据 (均价: {last_year_price}元, 涨幅: {last_year_pct:.2%})")
print(f"模型预测 2026 年大幅上涨(>5%)的概率为: {prob:.2%}")
if pred_class == 1:
    print("👉 结论:预计 2026 年房价将【大幅上涨】。")
else:
    print("👉 结论:预计 2026 年房价将【保持平稳或下跌】。")

# ==========================================
# 7. 可视化决策边界 (仅针对两个特征的情况)
# ==========================================
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 = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, alpha=0.3, cmap='coolwarm')
plt.xlabel('标准化后的前一年均价')
plt.ylabel('标准化后的前一年涨幅')
plt.title('逻辑回归:深圳房价是否大幅上涨预测 (决策边界)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
相关推荐
ssshooter44 分钟前
Replit 项目本地跑:一份实测过的改造清单
前端·后端·设计模式
摇滚侠1 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
番茄味城市甜菜1 小时前
二叉树刷题(C语言)
c语言·开发语言
布莱克6051 小时前
Swift 自动引用计数(ARC)详解:原理、循环引用与最佳实践
开发语言·ios·swift·arc·自动引用计数
FungLeo1 小时前
FengCMS·PHP+MySQL 升级实录 ·本地容器环境设计:只读挂载、LOCAL_UID、数据卷权限
开发语言·mysql·docker·php·fengcms
geovindu2 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手2 小时前
2. 编程语言-Python-Anaconda
开发语言·python
aifannihao2 小时前
断言从 == 改成 > 0:用 Python 审出 git diff 里的测试降级
git·python·测试·标准库·代码审查
高洁012 小时前
具身智能的人机协作与物理空间安全
人工智能·python·深度学习·机器学习·django