本文目录导读:

我来设计一个有趣的Python案例来预测足球杯赛决赛的紧张程度,这个模型会综合考虑多个因素:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
import warnings
warnings.filterwarnings('ignore')
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class CupFinalTensionPredictor:
"""
杯赛决赛紧张程度预测器
综合考虑比赛因素、球队实力、历史元素等
"""
def __init__(self):
# 定义紧张程度评分等级
self.tension_levels = {
0: "非常轻松",
1: "比较轻松",
2: "适中",
3: "比较紧张",
4: "非常紧张",
5: "极端紧张"
}
def calculate_team_strength(self, team_stats):
"""
计算球队综合实力
team_stats: 包含球队各项统计指标的字典
"""
# 权重分配
weights = {
'fifa_rank': 0.3, # FIFA排名
'goals_per_game': 0.25, # 场均进球
'defense_strength': 0.2, # 防守强度(失球率)
'possession': 0.15, # 控球率
'recent_form': 0.1 # 近期状态
}
strength_score = 0
for key, weight in weights.items():
if key == 'fifa_rank':
# FIFA排名越低越好,需要反向处理
score = (100 - team_stats.get(key, 50)) / 100
elif key == 'defense_strength':
# 失球率越低越好,反向处理
score = 1 - min(team_stats.get(key, 0.5), 1)
else:
score = min(team_stats.get(key, 0), 1)
strength_score += score * weight
return strength_score
def calculate_match_importance(self, match_context):
"""
计算比赛重要程度
"""
importance_factors = {
'is_final': 0.4, # 是否是决赛
'rivalry_level': 0.3, # 宿敌程度
'tournament_level': 0.2, # 赛事级别
'history_weight': 0.1 # 历史渊源重要性
}
importance_score = 0
for factor, weight in importance_factors.items():
score = min(match_context.get(factor, 0), 1)
importance_score += score * weight
return importance_score
def calculate_historical_tension(self, match_history):
"""
根据历史交锋数据计算紧张程度
"""
if not match_history or len(match_history) == 0:
return 0.5 # 默认中等紧张
# 计算历史交锋的平均分差
avg_goal_diff = np.mean([m['goal_diff'] for m in match_history])
# 计算历史红黄牌数量
avg_cards = np.mean([m['cards'] for m in match_history])
# 计算历史进球数
avg_goals = np.mean([m['total_goals'] for m in match_history])
# 转化为0-1的打分
tension_from_diff = 1 - min(abs(avg_goal_diff), 3) / 3 # 分差越小越紧张
tension_from_cards = min(avg_cards, 10) / 10 # 红黄牌越多越紧张
tension_from_goals = min(avg_goals, 6) / 6 # 进球越多越紧张
historical_tension = (tension_from_diff * 0.4 +
tension_from_cards * 0.3 +
tension_from_goals * 0.3)
return historical_tension
def predict_tension(self, team_a_stats, team_b_stats, match_context, match_history=[]):
"""
综合预测比赛紧张程度
参数:
- team_a_stats: 主队统计
- team_b_stats: 客队统计
- match_context: 比赛背景
- match_history: 历史交锋记录
"""
# 1. 计算两队实力
team_a_strength = self.calculate_team_strength(team_a_stats)
team_b_strength = self.calculate_team_strength(team_b_stats)
# 2. 计算实力差距 (实力越接近越紧张)
strength_gap = abs(team_a_strength - team_b_strength)
tension_from_gap = 1 - min(strength_gap, 0.5) / 0.5
# 3. 计算比赛重要程度
match_importance = self.calculate_match_importance(match_context)
# 4. 计算历史交锋紧张程度
historical_tension = self.calculate_historical_tension(match_history)
# 5. 综合计算最终紧张程度 (0-1)
weights = {
'strength_gap': 0.25, # 实力差距权重
'importance': 0.40, # 比赛重要性权重
'history': 0.15, # 历史交锋权重
'stake': 0.20 # 比赛结果影响权重
}
# 计算比赛结果影响(胜利的收益越大越紧张)
stake = min(match_context.get('champion_prize', 0.7), 1)
final_tension = (weights['strength_gap'] * tension_from_gap +
weights['importance'] * match_importance +
weights['history'] * historical_tension +
weights['stake'] * stake)
# 转换为0-5的评分
tension_score = round(final_tension * 5, 2)
# 确定紧张程度等级
tension_level = int(tension_score)
if tension_level >= 5:
tension_level = 5
return {
'tension_score': tension_score,
'tension_level': tension_level,
'tension_description': self.tension_levels[tension_level],
'details': {
'team_a_strength': round(team_a_strength, 3),
'team_b_strength': round(team_b_strength, 3),
'strength_gap': round(strength_gap, 3),
'match_importance': round(match_importance, 3),
'historical_tension': round(historical_tension, 3),
'stake_level': round(stake, 3)
}
}
# 示例使用
predictor = CupFinalTensionPredictor()
# 模拟一场比赛数据
team_a_stats = {
'fifa_rank': 12,
'goals_per_game': 0.85,
'defense_strength': 0.15, # 场均失球率
'possession': 0.58,
'recent_form': 0.75
}
team_b_stats = {
'fifa_rank': 8,
'goals_per_game': 0.92,
'defense_strength': 0.12,
'possession': 0.62,
'recent_form': 0.82
}
match_context = {
'is_final': 1.0, # 决赛
'rivalry_level': 0.8, # 老对手
'tournament_level': 1.0, # 世界大赛
'history_weight': 0.7, # 历史渊源深
'champion_prize': 0.9 # 冠军奖励重大
}
# 历史交锋记录 (最近5场)
match_history = [
{'goal_diff': 1, 'cards': 5, 'total_goals': 3},
{'goal_diff': 0, 'cards': 7, 'total_goals': 2},
{'goal_diff': -1, 'cards': 4, 'total_goals': 4},
{'goal_diff': 0, 'cards': 8, 'total_goals': 1},
{'goal_diff': 2, 'cards': 6, 'total_goals': 5}
]
# 进行预测
prediction = predictor.predict_tension(team_a_stats, team_b_stats, match_context, match_history)
# 输出结果
print("=" * 60)
print("🏆 杯赛决赛紧张程度预测系统 🏆")
print("=" * 60)
print(f"📊 预测紧张程度评分: {prediction['tension_score']}/5")
print(f"😰 紧张等级: {prediction['tension_description']}")
print("-" * 60)
print("📈 详细分析:")
print(f" • 主队综合实力: {prediction['details']['team_a_strength']}")
print(f" • 客队综合实力: {prediction['details']['team_b_strength']}")
print(f" • 实力差距: {prediction['details']['strength_gap']}")
print(f" • 比赛重要程度: {prediction['details']['match_importance']}")
print(f" • 历史交锋紧张度: {prediction['details']['historical_tension']}")
print(f" • 结果利益重大程度: {prediction['details']['stake_level']}")
# 可视化
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 左图:紧张程度指标
categories = ['实力差距', '比赛重要性', '历史交锋', '利益程度']
values = [
prediction['details']['strength_gap'],
prediction['details']['match_importance'],
prediction['details']['historical_tension'],
prediction['details']['stake_level']
]
bars = ax1.bar(categories, values, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'])
ax1.set_ylim(0, 1)
ax1.set_title('紧张程度指标分析')
ax1.set_ylabel('影响程度')
ax1.grid(axis='y', alpha=0.3)
# 在柱状图上添加数值
for bar, val in zip(bars, values):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height + 0.02,
f'{val:.2f}', ha='center', va='bottom')
# 右图:最终紧张程度评估
tension_score = prediction['tension_score']
colors = ['#90EE90', '#87CEEB', '#FFD700', '#FFA500', '#FF6B6B', '#FF0000']
ax2.pie([tension_score, 5 - tension_score],
labels=[f'预测紧张度\n{tension_score}/5', f'剩余空间\n{5-tension_score:.2f}/5'],
colors=[colors[prediction['tension_level']], '#DDDDDD'],
autopct='%1.1f%%', startangle=90)
ax2.set_title('综合紧张程度评估')
plt.tight_layout()
plt.show()
# 添加模拟数据生成功能(用于批量预测)
def generate_simulation_data(n=100):
"""
生成模拟数据用于测试
"""
data = []
for _ in range(n):
team_a = {
'fifa_rank': np.random.randint(1, 100),
'goals_per_game': np.random.uniform(0.5, 1.5),
'defense_strength': np.random.uniform(0.1, 0.5),
'possession': np.random.uniform(0.4, 0.7),
'recent_form': np.random.uniform(0.4, 0.95)
}
team_b = {
'fifa_rank': np.random.randint(1, 100),
'goals_per_game': np.random.uniform(0.5, 1.5),
'defense_strength': np.random.uniform(0.1, 0.5),
'possession': np.random.uniform(0.4, 0.7),
'recent_form': np.random.uniform(0.4, 0.95)
}
context = {
'is_final': np.random.choice([0.3, 0.6, 1.0]),
'rivalry_level': np.random.uniform(0.3, 0.9),
'tournament_level': np.random.choice([0.4, 0.7, 1.0]),
'history_weight': np.random.uniform(0.3, 0.9),
'champion_prize': np.random.uniform(0.5, 1.0)
}
data.append((team_a, team_b, context))
return data
# 批量预测示例
sim_data = generate_simulation_data(5)
print("\n📊 批量预测示例:")
for i, (ta, tb, ctx) in enumerate(sim_data[:3], 1):
result = predictor.predict_tension(ta, tb, ctx)
print(f" 比赛{i}: 紧张评分 {result['tension_score']}/5, 等级: {result['tension_description']}")
print("\n✅ 预测完成!")
预测原理说明:
这个预测系统基于以下关键因素:
🎯 主要预测因素
- 实力差距 - 两队实力越接近,比赛越胶着,紧张程度越高
- 比赛重要性 - 决赛比小组赛更紧张,宿敌对决更紧张
- 历史交锋 - 历史上有激烈交锋的更容易复现紧张局面
- 利益程度 - 冠军奖励越重大,球队越谨慎,越紧张
📊 评分系统
- 0-1分: 非常轻松的比赛
- 1-2分: 比较轻松
- 2-3分: 适中程度
- 3-4分: 比较紧张
- 4-5分: 极端紧张
💡 应用场景
- 赛前心理准备
- 预测比赛观赏性
- 体育分析报告
- 竞猜辅助工具
这个模型可以根据实际需求调整权重,增加更多数据维度,比如球员伤病、裁判风格、主场优势等因素,使预测更加精准。