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

wen python案例 2

本文目录导读:

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

  1. 基础版本:简单进球分布分析
  2. 进阶版本:滑动窗口趋势分析
  3. 机器学习版本:趋势预测
  4. 综合使用案例
  5. 使用说明

我来提供一个用Python分析比赛进球趋势的完整案例,这里提供几种不同的分析方法:

基础版本:简单进球分布分析

import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
def analyze_goal_trend_basic(goal_minutes, match_length=90):
    """
    分析进球时间的分布趋势
    goal_minutes: 进球时间列表(分钟)
    """
    # 将比赛分为几个时间段
    periods = {
        '上半场(0-15min)': (0, 15),
        '上半场(16-30min)': (16, 30),
        '上半场(31-45min)': (31, 45),
        '下半场(46-60min)': (46, 60),
        '下半场(61-75min)': (61, 75),
        '下半场(76-90min)': (76, 90)
    }
    period_goals = {period: 0 for period in periods}
    for minute in goal_minutes:
        for period, (start, end) in periods.items():
            if start <= minute <= end:
                period_goals[period] += 1
                break
    # 计算趋势
    total_goals = len(goal_minutes)
    avg_goals_per_period = total_goals / len(periods)
    print("=" * 50)
    print("比赛进球趋势分析结果")
    print("=" * 50)
    print(f"总进球数: {total_goals}")
    print(f"每个时间段平均进球: {avg_goals_per_period:.2f}")
    # 判断趋势
    early_goals = sum([period_goals[p] for p in list(periods.keys())[:2]])
    mid_goals = sum([period_goals[p] for p in list(periods.keys())[2:4]])
    late_goals = sum([period_goals[p] for p in list(periods.keys())[4:]])
    print(f"\n早些时段进球数: {early_goals}")
    print(f"中段时间进球数: {mid_goals}")
    print(f"晚些时段进球数: {late_goals}")
    if late_goals > early_goals and late_goals > mid_goals:
        print("趋势判断: 比赛后期进球趋势明显增加")
    elif early_goals > late_goals and early_goals > mid_goals:
        print("趋势判断: 比赛初期进球趋势明显")
    elif mid_goals > early_goals and mid_goals > late_goals:
        print("趋势判断: 比赛中期进球趋势明显")
    else:
        print("趋势判断: 进球分布相对均匀")
    # 可视化
    plt.figure(figsize=(10, 6))
    periods_list = list(periods.keys())
    goals_list = [period_goals[p] for p in periods_list]
    plt.bar(periods_list, goals_list, color='skyblue')
    plt.axhline(y=avg_goals_per_period, color='red', linestyle='--', label='平均值')
    plt.xlabel('比赛时间段')
    plt.ylabel('进球数')
    plt.title('比赛进球时间分布')
    plt.legend()
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()
    return period_goals
# 示例数据
goal_times = [12, 23, 35, 48, 52, 67, 75, 82, 88, 90]
analyze_goal_trend_basic(goal_times)

进阶版本:滑动窗口趋势分析

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def analyze_goal_trend_advanced(goal_minutes, window_size=10):
    """
    使用滑动窗口分析进球趋势
    """
    # 创建时间线
    match_minutes = np.arange(0, 91, 1)
    goal_count = np.zeros(len(match_minutes))
    # 标记进球分钟
    for minute in goal_minutes:
        idx = np.where(match_minutes == minute)[0]
        if len(idx) > 0:
            goal_count[idx[0]] = 1
    # 滑动窗口计算
    goal_trend = []
    for i in range(window_size, len(match_minutes)+1):
        window_sum = np.sum(goal_count[i-window_size:i])
        goal_trend.append(window_sum)
    # 填补前几个值
    goal_trend = [goal_trend[0]] * (window_size-1) + goal_trend
    # 判断趋势
    print("=" * 50)
    print("滑动窗口进球趋势分析")
    print("=" * 50)
    # 简单线性回归判断趋势
    x = np.arange(len(goal_trend))
    z = np.polyfit(x, goal_trend, 1)
    slope = z[0]
    print(f"趋势斜率: {slope:.4f}")
    if slope > 0.01:
        print("趋势判断: 进球频率整体上升趋势")
    elif slope < -0.01:
        print("趋势判断: 进球频率整体下降趋势")
    else:
        print("趋势判断: 进球频率相对平稳")
    # 可视化
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
    # 第一个图:进球分布
    ax1.scatter(goal_minutes, [1]*len(goal_minutes), alpha=0.6, s=100, c='red')
    ax1.set_xlabel('比赛时间(分钟)')
    ax1.set_ylabel('进球事件')
    ax1.set_title('进球时间分布')
    ax1.set_xlim(0, 90)
    ax1.set_yticks([])
    # 第二个图:滑动窗口趋势
    ax2.plot(match_minutes, goal_trend[:91], 'b-', linewidth=2)
    ax2.axhline(y=np.mean(goal_trend), color='red', linestyle='--', label=f'平均值: {np.mean(goal_trend):.2f}')
    ax2.set_xlabel('比赛时间(分钟)')
    ax2.set_ylabel('窗口内进球数')
    ax2.set_title(f'滑动窗口进球趋势 (窗口大小: {window_size}分钟)')
    ax2.legend()
    ax2.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()
    return goal_trend
# 示例数据
goal_times = [5, 12, 25, 33, 45, 55, 62, 78, 83, 90]
analyze_goal_trend_advanced(goal_times, window_size=15)

机器学习版本:趋势预测

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
def predict_goal_trend(goal_minutes):
    """
    使用多项式回归预测进球趋势
    """
    # 准备数据
    X = np.array(goal_minutes).reshape(-1, 1)
    y = np.zeros(91)  # 0-90分钟
    # 创建目标数组(进球时刻为1)
    X_full = np.arange(0, 91).reshape(-1, 1)
    y_full = np.zeros(91)
    for minute in goal_minutes:
        if minute <= 90:
            y_full[minute] = 1
    # 多项式回归
    poly_features = PolynomialFeatures(degree=3)
    X_poly = poly_features.fit_transform(X_full)
    model = LinearRegression()
    model.fit(X_poly, y_full)
    # 生成预测数据
    X_future = np.arange(91, 121).reshape(-1, 1)  # 预测未来30分钟
    X_future_poly = poly_features.transform(X_future)
    future_pred = model.predict(X_future_poly)
    # 计算实际进球率
    actual_rate = len(goal_minutes) / 90
    print("=" * 50)
    print("进球趋势预测分析")
    print("=" * 50)
    print(f"实际平均进球率: {actual_rate:.3f} 球/分钟")
    print(f"预测未来30分钟进球概率: {np.clip(sum(future_pred[future_pred > 0.01]), 0, 1):.2f}")
    # 计算比赛不同阶段的进球概率
    half_1 = sum(y_full[0:45])
    half_2 = sum(y_full[45:90])
    print(f"\n上半场进球数: {int(half_1)}")
    print(f"下半场进球数: {int(half_2)}")
    # 计算进球趋势指数
    if half_2 > half_1:
        trend_index = (half_2 - half_1) / max(half_1, 1)
        print(f"\n趋势指数: +{trend_index:.3f} (进攻趋势增强)")
    elif half_1 > half_2:
        trend_index = (half_1 - half_2) / max(half_2, 1)
        print(f"\n趋势指数: -{trend_index:.3f} (进攻趋势减弱)")
    else:
        print("\n趋势指数: 0.000 (比赛节奏平稳)")
    # 可视化
    plt.figure(figsize=(12, 6))
    # 实际数据
    plt.plot(X_full, y_full, 'r.', markersize=10, label='实际进球')
    plt.plot(X_future, future_pred, 'g--', alpha=0.7, label='预测趋势')
    # 拟合曲线
    X_all = np.arange(0, 120).reshape(-1, 1)
    X_all_poly = poly_features.transform(X_all)
    pred_all = model.predict(X_all_poly)
    plt.plot(X_all, pred_all, 'b-', alpha=0.5, label='整体趋势')
    plt.xlabel('比赛时间(分钟)')
    plt.ylabel('进球概率')
    plt.title('比赛进球趋势预测')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.axvline(x=90, color='black', linestyle='--', alpha=0.5, label='比赛结束')
    plt.tight_layout()
    plt.show()
    return model
# 示例数据
goal_times = [10, 22, 35, 48, 55, 63, 77, 82, 88, 90]
predict_goal_trend(goal_times)

综合使用案例

class MatchGoalAnalyzer:
    def __init__(self, match_data):
        """
        match_data: 包含多场比赛的数据
        格式: {"比赛1": {"进球时间": [], "对手": ""}, ...}
        """
        self.match_data = match_data
        self.all_goals = []
        for match_name, data in match_data.items():
            self.all_goals.extend(data['进球时间'])
    def analyze_all_matches(self):
        """分析所有比赛的综合趋势"""
        print("=" * 60)
        print("多场比赛综合进球趋势分析")
        print("=" * 60)
        # 统计分析
        total_matches = len(self.match_data)
        total_goals = len(self.all_goals)
        avg_goals = total_goals / total_matches
        print(f"总比赛场次: {total_matches}")
        print(f"总进球数: {total_goals}")
        print(f"平均每场进球: {avg_goals:.2f}")
        # 时间分布
        time_ranges = {
            '0-15分钟': (0, 15),
            '15-30分钟': (16, 30),
            '30-45分钟': (31, 45),
            '45-60分钟': (46, 60),
            '60-75分钟': (61, 75),
            '75-90分钟': (76, 90)
        }
        distribution = {key: 0 for key in time_ranges}
        for goal in self.all_goals:
            for period, (start, end) in time_ranges.items():
                if start <= goal <= end:
                    distribution[period] += 1
                    break
        # 计算增长趋势
        print("\n各时间段进球分布:")
        periods = list(distribution.keys())
        counts = list(distribution.values())
        # 计算各阶段增长率
        print("进球增长趋势:")
        for i in range(1, len(counts)):
            if counts[i-1] > 0:
                growth = (counts[i] - counts[i-1]) / counts[i-1] * 100
                print(f"{periods[i]}: 增长率 {growth:+.1f}%")
        # 可视化
        self.plot_distribution(distribution)
    def plot_distribution(self, distribution):
        """绘制分布图"""
        plt.figure(figsize=(12, 6))
        periods = list(distribution.keys())
        counts = list(distribution.values())
        # 条形图
        plt.subplot(1, 2, 1)
        plt.bar(periods, counts, color='lightblue')
        plt.xlabel('时间段')
        plt.ylabel('进球数')
        plt.title('各时间段进球分布')
        plt.xticks(rotation=45)
        # 折线图
        plt.subplot(1, 2, 2)
        plt.plot(periods, counts, 'o-', color='red', linewidth=2, markersize=8)
        plt.xlabel('时间段')
        plt.ylabel('进球数')
        plt.title('进球趋势变化')
        plt.xticks(rotation=45)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()
# 使用示例
match_data = {
    "比赛1": {"进球时间": [10, 25, 45, 60, 85], "对手": "A队"},
    "比赛2": {"进球时间": [5, 30, 42, 65, 78, 90], "对手": "B队"},
    "比赛3": {"进球时间": [15, 20, 35, 55, 70, 88], "对手": "C队"},
    "比赛4": {"进球时间": [8, 22, 48, 62, 80], "对手": "D队"}
}
analyzer = MatchGoalAnalyzer(match_data)
analyzer.analyze_all_matches()

使用说明

  1. 基础版本:适合简单分析单场比赛
  2. 滑动窗口版本:可以观察进球频率的变化趋势
  3. 预测版本:使用机器学习预测未来进球趋势
  4. 综合分析版本:适合分析多场比赛的综合表现

运行这些代码前需要安装:

pip install matplotlib pandas numpy scikit-learn

这些代码可以帮助你分析比赛中进球的分布规律,判断进球是集中在上半场还是下半场,以及整个比赛进程中的趋势变化。

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