本文目录导读:

我来帮你设计一个利用友谊赛数据做预测的完整案例,这里我会构建一个足球友谊赛结果预测系统。
完整的友谊赛预测案例
数据准备
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import warnings
warnings.filterwarnings('ignore')
# 创建示例友谊赛数据
def create_friendly_match_data():
# 模拟过去5年的友谊赛数据
np.random.seed(42)
teams = ['巴西', '德国', '阿根廷', '法国', '西班牙', '英格兰',
'葡萄牙', '荷兰', '意大利', '比利时', '乌拉圭', '哥伦比亚']
data = []
for _ in range(2000): # 生成2000场友谊赛
team1 = np.random.choice(teams)
team2 = np.random.choice([t for t in teams if t != team1])
# 基于球队实力生成比分
team1_strength = np.random.randint(60, 95)
team2_strength = np.random.randint(60, 95)
# 生成比赛数据
match = {
'球队1': team1,
'球队2': team2,
'球队1_世界排名': np.random.randint(1, 50),
'球队2_世界排名': np.random.randint(1, 50),
'球队1_FIFA积分': team1_strength * 10 + np.random.randint(-20, 20),
'球队2_FIFA积分': team2_strength * 10 + np.random.randint(-20, 20),
'球队1_近10场胜率': np.random.uniform(0.3, 0.9),
'球队2_近10场胜率': np.random.uniform(0.3, 0.9),
'球队1_历史交锋胜率': np.random.uniform(0.2, 0.8),
'球队2_历史交锋胜率': np.random.uniform(0.2, 0.8),
'主客场': np.random.choice(['主场', '客场', '中立']),
'友谊赛类型': np.random.choice(['普通友谊赛', '杯赛热身赛', '国际友谊赛']),
'比赛时间': np.random.randint(1, 365), # 距离大赛的天数
'球队1_进球': np.random.poisson(1.5),
'球队2_进球': np.random.poisson(1.2)
}
data.append(match)
df = pd.DataFrame(data)
# 创建目标变量:比赛结果
df['结果'] = np.where(df['球队1_进球'] > df['球队2_进球'], '主胜',
np.where(df['球队1_进球'] == df['球队2_进球'], '平局', '客胜'))
return df
# 加载数据
match_data = create_friendly_match_data()
print("数据预览:")
print(match_data.head())
print(f"\n数据维度: {match_data.shape}")
特征工程
def engineer_features(df):
"""进行特征工程,创建更有意义的预测特征"""
# 创建特征副本
df_feat = df.copy()
# 计算实力差距特征
df_feat['积分差距'] = df_feat['球队1_FIFA积分'] - df_feat['球队2_FIFA积分']
df_feat['排名差距'] = df_feat['球队1_世界排名'] - df_feat['球队2_世界排名']
df_feat['胜率差距'] = df_feat['球队1_近10场胜率'] - df_feat['球队2_近10场胜率']
df_feat['交锋优势'] = df_feat['球队1_历史交锋胜率'] - df_feat['球队2_历史交锋胜率']
# 创建综合实力指标
df_feat['综合实力'] = (df_feat['球队1_FIFA积分'] + df_feat['球队1_近10场胜率']*100) / \
(df_feat['球队2_FIFA积分'] + df_feat['球队2_近10场胜率']*100)
# 主客场优势编码
home_advantage = {'主场': 1, '中立': 0.5, '客场': 0}
df_feat['主场优势'] = df_feat['主客场'].map(home_advantage)
# 友谊赛类型编码(临近大赛的友谊赛有更多参考价值)
type_weight = {'普通友谊赛': 0.3, '国际友谊赛': 0.5, '杯赛热身赛': 0.8}
df_feat['比赛权重'] = df_feat['友谊赛类型'].map(type_weight)
return df_feat
# 应用特征工程
featured_data = engineer_features(match_data)
print("特征工程完成!")
模型构建
def prepare_model_data(df):
"""准备模型训练数据"""
# 选择特征
features = [
'积分差距', '排名差距', '胜率差距', '交锋优势',
'综合实力', '主场优势', '比赛权重',
'球队1_世界排名', '球队2_世界排名',
'球队1_FIFA积分', '球队2_FIFA积分',
'球队1_近10场胜率', '球队2_近10场胜率'
]
X = df[features]
y = df['结果']
# 处理缺失值
X = X.fillna(X.mean())
# 标准化特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42, stratify=y
)
return X_train, X_test, y_train, y_test, scaler
# 准备数据
X_train, X_test, y_train, y_test, scaler = prepare_model_data(featured_data)
# 训练多个模型比较
def train_models(X_train, y_train):
"""训练多个机器学习模型"""
models = {
'随机森林': RandomForestClassifier(
n_estimators=200, max_depth=10, random_state=42
),
'梯度提升': GradientBoostingClassifier(
n_estimators=200, max_depth=5, random_state=42
),
}
trained_models = {}
for name, model in models.items():
model.fit(X_train, y_train)
trained_models[name] = model
return trained_models
# 训练模型
models = train_models(X_train, y_train)
print("模型训练完成!")
# 评估模型
def evaluate_models(models, X_test, y_test):
"""评估模型性能"""
results = {}
for name, model in models.items():
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
results[name] = acc
print(f"\n{name}模型评估:")
print(f"准确率: {acc:.4f}")
print("分类报告:")
print(classification_report(y_test, y_pred))
print("混淆矩阵:")
print(confusion_matrix(y_test, y_pred))
print("-" * 50)
return results
# 评估模型
evaluation_results = evaluate_models(models, X_test, y_test)
新比赛预测功能
def predict_new_match(model, scaler, team1_info, team2_info):
"""
预测新友谊赛结果
参数:
- model: 训练好的模型
- scaler: 标准化器
- team1_info: 球队1信息字典
- team2_info: 球队2信息字典
"""
# 构建特征向量
features = np.array([
team1_info['FIFA积分'] - team2_info['FIFA积分'], # 积分差距
team1_info['世界排名'] - team2_info['世界排名'], # 排名差距
team1_info['近10场胜率'] - team2_info['近10场胜率'], # 胜率差距
team1_info['历史交锋胜率'] - team2_info['历史交锋胜率'], # 交锋优势
(team1_info['FIFA积分'] + team1_info['近10场胜率']*100) /
(team2_info['FIFA积分'] + team2_info['近10场胜率']*100), # 综合实力
team1_info['主场优势'], # 主场优势
team1_info['比赛权重'], # 比赛权重
team1_info['世界排名'],
team2_info['世界排名'],
team1_info['FIFA积分'],
team2_info['FIFA积分'],
team1_info['近10场胜率'],
team2_info['近10场胜率']
]).reshape(1, -1)
# 标准化特征
features_scaled = scaler.transform(features)
# 预测概率
probabilities = model.predict_proba(features_scaled)[0]
return probabilities
# 模拟预测新比赛
def make_prediction():
"""进行一场新友谊赛的预测"""
print("="*60)
print("友谊赛预测系统演示")
print("="*60)
# 示例:预测巴西对阵德国
team1 = {
'world_rank': 5,
'fifa_points': 850,
'recent_win_rate': 0.75,
'head_to_head_win_rate': 0.6,
'home_advantage': 1,
'match_weight': 0.8
}
team2 = {
'world_rank': 3,
'fifa_points': 870,
'recent_win_rate': 0.8,
'head_to_head_win_rate': 0.55,
'home_advantage': 0.5,
'match_weight': 0.8
}
# 获取最佳模型(这里用随机森林)
best_model = models['随机森林']
# 预测
probabilities = predict_new_match(best_model, scaler, team1, team2)
# 输出结果
print(f"\n比赛预测:巴西 vs 德国")
print(f"巴西获胜概率: {probabilities[2]*100:.1f}%")
print(f"平局概率: {probabilities[0]*100:.1f}%")
print(f"德国获胜概率: {probabilities[1]*100:.1f}%")
# 预测最可能结果
outcomes = ['平局', '客胜', '主胜'] # 注意顺序需要与模型训练一致
predicted = outcomes[np.argmax(probabilities)]
print(f"\n预测结果: {predicted}")
return probabilities
# 执行预测
prediction = make_prediction()
模型调优
from sklearn.model_selection import GridSearchCV
def optimize_model(X_train, y_train):
"""网格搜索优化模型参数"""
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [5, 10, 15],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4]
}
rf = RandomForestClassifier(random_state=42)
grid_search = GridSearchCV(
rf, param_grid, cv=5, scoring='accuracy',
n_jobs=-1, verbose=1
)
grid_search.fit(X_train, y_train)
print("最佳参数:", grid_search.best_params_)
print("最佳得分:", grid_search.best_score_)
return grid_search.best_estimator_
# 模型优化(可选,计算量大)
# best_model = optimize_model(X_train, y_train)
特征重要性分析
def analyze_feature_importance(model, feature_names):
"""分析特征重要性"""
# 获取特征重要性
importance = model.feature_importances_
# 排序
indices = np.argsort(importance)[::-1]
print("\n特征重要性排名:")
print("-"*40)
for i in range(len(indices)):
print(f"{i+1}. {feature_names[indices[i]]}: {importance[indices[i]]:.4f}")
# 可视化
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.title('特征重要性分析')
plt.bar(range(len(indices)), importance[indices])
plt.xticks(range(len(indices)), [feature_names[i] for i in indices], rotation=45)
plt.tight_layout()
plt.show()
# 分析特征重要性
feature_names = [
'积分差距', '排名差距', '胜率差距', '交锋优势',
'综合实力', '主场优势', '比赛权重',
'球队1_世界排名', '球队2_世界排名',
'球队1_FIFA积分', '球队2_FIFA积分',
'球队1_近10场胜率', '球队2_近10场胜率'
]
analyze_feature_importance(models['随机森林'], feature_names)
批量预测演示
def batch_prediction_demo():
"""批量预测多场比赛"""
# 准备多场比赛数据
matches_to_predict = [
('法国', '阿根廷'),
('葡萄牙', '西班牙'),
('英格兰', '比利时'),
('荷兰', '意大利')
]
print("\n批量预测演示:")
print("="*60)
for team1_name, team2_name in matches_to_predict:
# 模拟球队数据
team1_info = {
'world_rank': np.random.randint(1, 20),
'fifa_points': np.random.randint(750, 900),
'recent_win_rate': np.random.uniform(0.5, 0.9),
'head_to_head_win_rate': np.random.uniform(0.4, 0.7),
'home_advantage': np.random.choice([0, 0.5, 1]),
'match_weight': 0.5
}
team2_info = {
'world_rank': np.random.randint(1, 20),
'fifa_points': np.random.randint(750, 900),
'recent_win_rate': np.random.uniform(0.5, 0.9),
'head_to_head_win_rate': np.random.uniform(0.4, 0.7),
'home_advantage': np.random.choice([0, 0.5, 1]),
'match_weight': 0.5
}
# 预测
prob = predict_new_match(models['随机森林'], scaler, team1_info, team2_info)
predicted = ['平局', '客胜', '主胜'][np.argmax(prob)]
print(f"{team1_name} vs {team2_name}:")
print(f" 预测结果: {predicted} (主胜:{prob[2]:.1%}, 平局:{prob[0]:.1%}, 客胜:{prob[1]:.1%})")
print("-"*60)
# 执行批量预测
batch_prediction_demo()
使用说明
- 数据要求:需要包含球队FIFA积分、世界排名、近期胜率、历史交锋记录等数据
- 模型选择:随机森林和梯度提升都是不错的起点
- 特征工程:创建实力差距、综合实力等衍生特征可以提升预测效果
- 定期更新:友谊赛数据需要定期更新以保持模型准确性
这个案例提供了一个完整的预测框架,你可以根据实际数据和需求进行调整和优化。