python案例如何判断一场比赛的进球总趋势?

wen python案例 10

本文目录导读:

python案例如何判断一场比赛的进球总趋势?

  1. 基础版本 - 进球趋势分析
  2. 增强版 - 实时趋势预测
  3. 使用示例
  4. 实时监测版本
  5. 统计模型预测
  6. 使用建议

我来提供一个判断足球比赛进球总趋势的Python方案,包括数据分析、趋势判断和可视化:

基础版本 - 进球趋势分析

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
class GoalTrendAnalyzer:
    def __init__(self, match_data):
        """
        初始化分析器
        match_data: 包含进球数据的DataFrame,列包括:
        - minute: 进球分钟
        - team: 进球队伍
        - score: 当时比分
        """
        self.data = match_data
        self.minute_bins = np.arange(0, 91, 5)  # 每5分钟一个区间
    def analyze_timing(self):
        """分析进球时间分布"""
        # 统计每5分钟的进球数
        self.data['time_bin'] = pd.cut(self.data['minute'], 
                                       bins=self.minute_bins, 
                                       right=False)
        timing_stats = self.data.groupby('time_bin').size().reset_index(name='goals')
        timing_stats['percentage'] = timing_stats['goals'] / len(self.data) * 100
        return timing_stats
    def analyze_momentum(self):
        """分析比赛势头变化"""
        # 计算连续进球间隔
        self.data['time_diff'] = self.data['minute'].diff().fillna(0)
        # 分析进球密集程度
        momentum = {
            'avg_interval': self.data['time_diff'].mean(),
            'max_interval': self.data['time_diff'].max(),
            'min_interval': self.data['time_diff'].min()
        }
        return momentum
    def predict_total_trend(self):
        """预测总进球趋势"""
        # 基于比赛进行时间预测最终进球数
        current_minute = self.data['minute'].max() if len(self.data) > 0 else 0
        goals_so_far = len(self.data)
        if goals_so_far == 0:
            return {'prediction': '低', 'score': 0}
        avg_goal_rate = goals_so_far / (current_minute / 90)
        predicted_total = int(avg_goal_rate * 90)
        if avg_goal_rate < 1.5:
            trend = '低进球趋势'
        elif avg_goal_rate < 2.5:
            trend = '中等进球趋势'
        else:
            trend = '高进球趋势'
        return {
            'prediction': trend,
            'expected_total': predicted_total,
            'current': goals_so_far,
            'current_minute': current_minute
        }
    def visualize_trend(self):
        """可视化进球趋势"""
        plt.figure(figsize=(12, 6))
        # 子图1:进球时间分布
        plt.subplot(1, 2, 1)
        timing = self.analyze_timing()
        plt.bar(range(len(timing)), timing['goals'], alpha=0.7)
        plt.xlabel('比赛时间段(每5分钟)')
        plt.ylabel('进球数')
        plt.title('进球时间分布')
        plt.xticks(range(len(timing)), [f"{int(bin)}'" for bin in timing['time_bin'].apply(lambda x: x.left)])
        # 子图2:累计进球趋势
        plt.subplot(1, 2, 2)
        cumulative = np.cumsum(timing['goals'])
        plt.plot(cumulative, marker='o', linewidth=2)
        plt.fill_between(range(len(timing)), cumulative, alpha=0.3)
        plt.xlabel('比赛时间段')
        plt.ylabel('累计进球数')
        plt.title('累计进球趋势')
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()

增强版 - 实时趋势预测

class AdvancedGoalTrendAnalyzer(GoalTrendAnalyzer):
    def __init__(self, match_data):
        super().__init__(match_data)
        self.team_stats = {}
    def analyze_team_dynamics(self):
        """分析各队进攻防守节奏"""
        for team in self.data['team'].unique():
            team_goals = self.data[self.data['team'] == team]['minute'].tolist()
            if len(team_goals) > 1:
                intervals = np.diff(team_goals)
                self.team_stats[team] = {
                    'total_goals': len(team_goals),
                    'avg_interval': np.mean(intervals),
                    'attack_pattern': '连续进攻' if np.mean(intervals) < 10 else '间歇进攻'
                }
            else:
                self.team_stats[team] = {
                    'total_goals': len(team_goals),
                    'avg_interval': None,
                    'attack_pattern': '尚未形成持续进攻'
                }
        return self.team_stats
    def detect_scoring_phases(self):
        """检测进球高峰期"""
        if len(self.data) < 1:
            return "暂无进球数据"
        # 将比赛分为3个阶段
        phases = {
            '上半场': self.data[self.data['minute'] <= 45],
            '下半场': self.data[(self.data['minute'] > 45) & (self.data['minute'] <= 90)]
        }
        active_phase = '全场'
        active_goals = len(self.data)
        for phase, phase_data in phases.items():
            phase_goals = len(phase_data)
            if phase_goals > active_goals * 0.6:
                active_phase = phase
        return f"当前比赛最活跃的进球时段:{active_phase}"
    def predict_final_score(self):
        """预测最终比分"""
        prediction = self.predict_total_trend()
        current_goals = prediction['current']
        # 简单的时间比例预测
        if len(self.data) > 0:
            current_minute = self.data['minute'].max()
            remaining_ratio = (90 - current_minute) / 90
            # 基于当前趋势预测
            if current_goals > 2:
                additional_goals = int(current_goals * remaining_ratio * 0.5)
            else:
                additional_goals = int(current_goals * remaining_ratio)
            predicted_total = current_goals + additional_goals
            return {
                'current_goals': current_goals,
                'predicted_total': predicted_total,
                'current_minute': current_minute,
                'confidence': '高' if remaining_ratio > 0.3 else '低'
            }
        return None
    def advanced_trend_matrix(self):
        """生成趋势矩阵"""
        # 计算各时间段进球强度
        timing = self.analyze_timing()
        goals_per_min = timing['goals'] / 5  # 每分钟进球率
        # 划分为增加/持平/减少
        trend_matrix = []
        for i in range(1, len(goals_per_min)):
            diff = goals_per_min[i] - goals_per_min[i-1]
            if diff > 0.2:
                trend_matrix.append('↑')
            elif diff < -0.2:
                trend_matrix.append('↓')
            else:
                trend_matrix.append('→')
        return trend_matrix

使用示例

def main():
    # 创建示例数据
    sample_data = pd.DataFrame({
        'minute': [10, 23, 35, 42, 55, 62, 68, 75, 80, 88],
        'team': ['A', 'B', 'A', 'A', 'B', 'A', 'B', 'A', 'A', 'B'],
        'score': [1, 1, 2, 3, 3, 4, 4, 5, 6, 6]
    })
    # 基础分析
    analyzer = GoalTrendAnalyzer(sample_data)
    print("=== 进球时间分析 ===")
    timing = analyzer.analyze_timing()
    print(timing)
    print("\n=== 比赛势头分析 ===")
    momentum = analyzer.analyze_momentum()
    print(momentum)
    print("\n=== 趋势预测 ===")
    prediction = analyzer.predict_total_trend()
    print(prediction)
    # 可视化
    analyzer.visualize_trend()
    # 高级分析
    adv_analyzer = AdvancedGoalTrendAnalyzer(sample_data)
    print("\n=== 球队动态分析 ===")
    team_stats = adv_analyzer.analyze_team_dynamics()
    print(team_stats)
    print("\n=== 球高峰检测 ===")
    print(adv_analyzer.detect_scoring_phases())
    print("\n=== 最终比分预测 ===")
    score_prediction = adv_analyzer.predict_final_score()
    print(score_prediction)
    print("\n=== 趋势矩阵 ===")
    trend_matrix = adv_analyzer.advanced_trend_matrix()
    print(trend_matrix)
if __name__ == "__main__":
    main()

实时监测版本

import time
import random
class LiveGoalMonitor:
    """实时进球监控"""
    def __init__(self):
        self.match_minute = 0
        self.goals = []
        self.analysis = GoalTrendAnalyzer(pd.DataFrame())
    def add_goal(self, minute, team):
        """添加进球"""
        new_goal = {'minute': minute, 'team': team}
        self.goals.append(new_goal)
        self.update_analysis()
    def update_analysis(self):
        """更新分析"""
        if self.goals:
            df = pd.DataFrame(self.goals)
            self.analysis = GoalTrendAnalyzer(df)
    def check_for_goal(self):
        """模拟检查是否进球"""
        # 模拟随机进球
        if random.random() < 0.03:  # 3%概率进球
            minute = random.randint(1, 90)
            team = random.choice(['A', 'B'])
            self.add_goal(minute, team)
            return f"⚽ 进球!{team}队在{minute}分钟进球"
        return "暂无新进球"
    def start_monitoring(self):
        """开始实时监控"""
        while self.match_minute <= 90:
            result = self.check_for_goal()
            if result != "暂无新进球":
                print(result)
                prediction = self.analysis.predict_total_trend()
                print(f"当前预测: {prediction}")
            time.sleep(1)
            self.match_minute += 1
# 使用实时监控
def run_live_monitoring():
    monitor = LiveGoalMonitor()
    print("比赛开始监控...")
    # 简化版本 - 只用一段时间来演示
    for _ in range(10):
        result = monitor.check_for_goal()
        if result != "暂无新进球":
            print(result)
            monitor.update_analysis()
            if monitor.goals:
                prediction = monitor.analysis.predict_total_trend()
                print(f"趋势预测: {prediction['prediction']}, 预计总进球: {prediction['expected_total']}")
    print("监控结束")

统计模型预测

from scipy import stats
class StatisticalGoalPredictor:
    """基于统计模型的进球预测"""
    def __init__(self, historical_data):
        self.historical_data = historical_data
        self.avg_goals_per_match = np.mean(historical_data)
    def poisson_predict(self, minutes_played, goals_so_far):
        """使用泊松分布预测总进球"""
        remaining_ratio = (90 - minutes_played) / 90
        expected_remaining = self.avg_goals_per_match * remaining_ratio
        # 泊松分布
        poisson_dist = stats.poisson(expected_remaining)
        total_predicted = goals_so_far + poisson_dist.mean()
        return {
            'expected_total': total_predicted,
            'current_goals': goals_so_far,
            'expected_remaining': expected_remaining,
            'probability_no_more_goals': poisson_dist.pmf(0)
        }
    def analyze_streak(self, goals_history):
        """分析进球连胜/连败趋势"""
        if len(goals_history) < 2:
            return "数据不足以分析"
        # 计算最近5场的平均进球
        recent_avg = np.mean(goals_history[-5:])
        overall_avg = np.mean(goals_history)
        if recent_avg > overall_avg * 1.2:
            return "近期进球趋势上升"
        elif recent_avg < overall_avg * 0.8:
            return "近期进球趋势下降"
        else:
            return "近期进球趋势稳定"
# 使用示例
historical_data = [2, 3, 1, 4, 2, 2, 3, 1, 3, 2]  # 每场总进球数
predictor = StatisticalGoalPredictor(historical_data)
prediction = predictor.poisson_predict(minutes_played=60, goals_so_far=2)
print(f"60分钟时预测最终进球数: {prediction['expected_total']:.1f}")

使用建议

  1. 数据收集:确保收集完整的进球时间数据
  2. 实时更新:使用爬虫或API收集实时比赛数据
  3. 多因素考虑:结合球队实力、交锋记录、伤停情况等
  4. 可视化:持续更新图形展示趋势变化

这个方案能够帮助您分析比赛进球趋势,并进行合理预测,根据实际需要可以选择使用基础版或高级版。

抱歉,评论功能暂时关闭!