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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import datetime
|
3 |
+
import os
|
4 |
+
import base64
|
5 |
+
from catboost import CatBoostClassifier, Pool
|
6 |
+
import streamlit as st
|
7 |
+
|
8 |
+
st.set_page_config(
|
9 |
+
page_title="Hockey Match Prediction",
|
10 |
+
page_icon="🏒",
|
11 |
+
layout="wide"
|
12 |
+
)
|
13 |
+
|
14 |
+
# Функция загрузки данных
|
15 |
+
@st.cache_data
|
16 |
+
def load_data():
|
17 |
+
df = pd.read_csv("/home/savr/rink_master/rink_master_47816_wteams.csv")
|
18 |
+
df['gameDate'] = pd.to_datetime(df['gameDate'])
|
19 |
+
|
20 |
+
# Извлечение года и месяца, и создание нового столбца Season
|
21 |
+
df["Year"] = df["gameDate"].dt.year
|
22 |
+
df["Month"] = df["gameDate"].dt.month
|
23 |
+
df["Season"] = df["Year"].astype(str) + "-" + (df["Year"] + 1).astype(str)
|
24 |
+
|
25 |
+
# Создание SeasonWeight и NormalizedWeight
|
26 |
+
seasons = df["Season"].unique()
|
27 |
+
season_weights = {season: i + 1 for i, season in enumerate(sorted(seasons))}
|
28 |
+
max_season_weight = max(season_weights.values())
|
29 |
+
min_season_weight = min(season_weights.values())
|
30 |
+
df["SeasonWeight"] = df["Season"].map(season_weights)
|
31 |
+
df["NormalizedWeight"] = (df["SeasonWeight"] - min_season_weight) / (
|
32 |
+
max_season_weight - min_season_weight
|
33 |
+
)
|
34 |
+
df["Weights"] = df.groupby("Season")["NormalizedWeight"].transform("mean")
|
35 |
+
|
36 |
+
|
37 |
+
return df
|
38 |
+
|
39 |
+
data = load_data()
|
40 |
+
|
41 |
+
|
42 |
+
# Определение результата
|
43 |
+
def determine_result(row):
|
44 |
+
if (
|
45 |
+
row["Win"] != 0
|
46 |
+
or row["regulationWins"] != 0
|
47 |
+
or row["regulationAndOtWins"] != 0
|
48 |
+
or row["shootoutWins"] != 0
|
49 |
+
):
|
50 |
+
return 1 # Победа
|
51 |
+
elif row["Loss"] != 0 or row["OTLoss"] != 0:
|
52 |
+
return 0 # Поражение
|
53 |
+
else:
|
54 |
+
return -1 # Неопределено
|
55 |
+
|
56 |
+
data["Result"] = data.apply(determine_result, axis=1)
|
57 |
+
|
58 |
+
# Маппинг команд на числовые значения
|
59 |
+
fullname_to_code = {
|
60 |
+
"New Jersey Devils": 1, "New York Islanders": 2, "New York Rangers": 3,
|
61 |
+
"Philadelphia Flyers": 4, "Pittsburgh Penguins": 5, "Boston Bruins": 6,
|
62 |
+
"Buffalo Sabres": 7, "Montréal Canadiens": 8, "Ottawa Senators": 9,
|
63 |
+
"Toronto Maple Leafs": 10, "Carolina Hurricanes": 11, "Florida Panthers": 12,
|
64 |
+
"Tampa Bay Lightning": 13, "Washington Capitals": 14, "Chicago Blackhawks": 15,
|
65 |
+
"Detroit Red Wings": 16, "Nashville Predators": 17, "St. Louis Blues": 18,
|
66 |
+
"Calgary Flames": 19, "Colorado Avalanche": 20, "Edmonton Oilers": 21,
|
67 |
+
"Vancouver Canucks": 22, "Anaheim Ducks": 23, "Dallas Stars": 24,
|
68 |
+
"Los Angeles Kings": 25, "San Jose Sharks": 26, "Columbus Blue Jackets": 27,
|
69 |
+
"Minnesota Wild": 28, "Winnipeg Jets": 29, "Arizona Coyotes": 30,
|
70 |
+
"Vegas Golden Knights": 31, "Seattle Kraken": 32,
|
71 |
+
}
|
72 |
+
|
73 |
+
data["Team"] = data["Team"].map(fullname_to_code)
|
74 |
+
data["Opponent"] = data["Opponent"].map(fullname_to_code)
|
75 |
+
|
76 |
+
# Разделение данных на обучающую и тестовую выборки
|
77 |
+
train = data[data["gameDate"] < "2023-10-10"]
|
78 |
+
test = data[data["gameDate"] >= "2023-10-10"]
|
79 |
+
|
80 |
+
# Определение колонок, которые будут удалены
|
81 |
+
features_to_drop = [
|
82 |
+
"Result", "gameDate", "gameID", "gamesPlayed", "Win", "Loss", "Tie",
|
83 |
+
"OTLoss", "points", "pointPct", "regulationWins", "regulationAndOtWins",
|
84 |
+
"shootoutWins", "goalsFor", "goalsAgainst", "goalsForPerGame",
|
85 |
+
"goalsAgainstPerGame", "powerPlayPct", "penaltyKillPct", "powerPlayNetPct",
|
86 |
+
"penaltyKillNetPct", "shotsForPerGame", "shotsAgainstPerGame",
|
87 |
+
"faceoffWinPct", "Year", "Month", "Season", "NonRegulationTime",
|
88 |
+
"SeasonWeight", "NormalizedWeight"
|
89 |
+
]
|
90 |
+
|
91 |
+
code_to_fullname = {v: k for k, v in fullname_to_code.items()} # Создание обратного маппинга
|
92 |
+
|
93 |
+
# Убедитесь, что колонки для удаления существуют в данных
|
94 |
+
features_to_drop = [col for col in features_to_drop if col in train.columns]
|
95 |
+
|
96 |
+
# Обновление признаков, включая Weight
|
97 |
+
X_train = train.drop(columns=features_to_drop)
|
98 |
+
y_train = train["Result"]
|
99 |
+
X_test = test.drop(columns=features_to_drop)
|
100 |
+
y_test = test["Result"]
|
101 |
+
|
102 |
+
|
103 |
+
# Функция для загрузки модели CatBoost
|
104 |
+
@st.cache_resource
|
105 |
+
def load_catboost_model(file_path):
|
106 |
+
try:
|
107 |
+
model = CatBoostClassifier()
|
108 |
+
model.load_model(file_path)
|
109 |
+
# st.write(f"Тип загруженной модели: {type(model)}") # Для отладки
|
110 |
+
return model
|
111 |
+
except Exception as e:
|
112 |
+
st.write(f"Ошибка при загрузке модели CatBoost: {e}")
|
113 |
+
return None
|
114 |
+
|
115 |
+
model_path = "/home/savr/rink_master/catboost_model.cb"
|
116 |
+
model = load_catboost_model(model_path)
|
117 |
+
|
118 |
+
# # Проверка признаков
|
119 |
+
# model_feature_names = model.feature_names_
|
120 |
+
# st.write("Признаки модели:", model_feature_names)
|
121 |
+
# st.write("Признаки в данных для обучения:", X_train.columns.tolist())
|
122 |
+
|
123 |
+
# Маппинг для homeRoad
|
124 |
+
home_road_mapping = {
|
125 |
+
1: "На выезде",
|
126 |
+
0: "Дома"
|
127 |
+
}
|
128 |
+
|
129 |
+
win_mapping = {
|
130 |
+
1: "Победа",
|
131 |
+
0: "Не победа: Поражение или Ничья"
|
132 |
+
}
|
133 |
+
|
134 |
+
|
135 |
+
# Функция для предсказания исхода
|
136 |
+
def predict_winner(row, model):
|
137 |
+
# print(f"Тип модели в predict_winner: {type(model)}") # Для отладки
|
138 |
+
try:
|
139 |
+
# Подготовка входных данных
|
140 |
+
features = pd.DataFrame([row], columns=X_train.columns).fillna(0)
|
141 |
+
|
142 |
+
# Создание объекта Pool для CatBoost
|
143 |
+
pool = Pool(data=features, feature_names=X_train.columns.tolist())
|
144 |
+
|
145 |
+
# Сделайте предсказание
|
146 |
+
prediction = model.predict(pool)
|
147 |
+
prediction_proba = model.predict_proba(pool)
|
148 |
+
# st.write(f"Предсказание: {prediction}, вероятность: {prediction_proba}") # Для отладки
|
149 |
+
|
150 |
+
# Верните результат и вероятность
|
151 |
+
result = 'Победа с вероятностью' if prediction[0] == 1 else 'Не победа: Поражение или Ничья с вероятностью'
|
152 |
+
probability = prediction_proba[0][1] if prediction[0] == 1 else prediction_proba[0][0]
|
153 |
+
|
154 |
+
return result, probability
|
155 |
+
|
156 |
+
except Exception as e:
|
157 |
+
print(f"Ошибка при предсказании: {e}")
|
158 |
+
return "Ошибка"
|
159 |
+
|
160 |
+
|
161 |
+
st.markdown(
|
162 |
+
"""
|
163 |
+
<style>
|
164 |
+
@import url('https://fonts.googleapis.com/css2?family=Anton:wght@400;700&display=swap');
|
165 |
+
|
166 |
+
.title {
|
167 |
+
font-size: 48px;
|
168 |
+
font-weight: 700;
|
169 |
+
color: #0A74DA; /* Темно-голубой цвет */
|
170 |
+
font-family: 'Anton', sans-serif; /* шрифт Anton */
|
171 |
+
text-transform: uppercase; /* все буквы заглавные */
|
172 |
+
text-shadow: 2px 2px 4px #000000; /* тень текста */
|
173 |
+
margin-bottom: 20px;
|
174 |
+
text-align: center; /* Центрирование текста */
|
175 |
+
}
|
176 |
+
|
177 |
+
.title-container {
|
178 |
+
background: rgba(255, 255, 255, 1.0); /* Белый фон */
|
179 |
+
padding: 10px;
|
180 |
+
border-radius: 10px;
|
181 |
+
margin-bottom: 20px;
|
182 |
+
display: inline-block;
|
183 |
+
width: 100%; /* Занимает всю ширину, чтобы текст был по центру */
|
184 |
+
}
|
185 |
+
|
186 |
+
.stApp {
|
187 |
+
display: flex;
|
188 |
+
justify-content: center;
|
189 |
+
align-items: center;
|
190 |
+
min-height: 100vh;
|
191 |
+
flex-direction: column;
|
192 |
+
}
|
193 |
+
|
194 |
+
.stMarkdown, .stTable, .stDataFrame, .stForm, .stTextInput, .stDateInput, .stSelectbox {
|
195 |
+
background: rgba(255, 255, 255, 1.0); /* Белый фон */
|
196 |
+
border-radius: 10px;
|
197 |
+
padding: 10px;
|
198 |
+
margin-bottom: 20px;
|
199 |
+
display: inline-block; /* Чтобы контейнеры не растягивались */
|
200 |
+
max-width: fit-content; /* Максимальная ширина по содержимому */
|
201 |
+
}
|
202 |
+
|
203 |
+
</style>
|
204 |
+
""",
|
205 |
+
unsafe_allow_html=True
|
206 |
+
)
|
207 |
+
|
208 |
+
|
209 |
+
st.markdown('<div class="title-container"><h1 class="title">Предсказание исходов хоккейных матчей NHL 🏒🥅🏆</h1></div>', unsafe_allow_html=True)
|
210 |
+
|
211 |
+
|
212 |
+
# Добавление навигации по страницам
|
213 |
+
st.sidebar.markdown("## Навигация")
|
214 |
+
page = st.sidebar.selectbox("Выберите страницу", ["Основная", "Графики"])
|
215 |
+
|
216 |
+
if page == "Основная":
|
217 |
+
st.sidebar.title("Поиск по фильтрам")
|
218 |
+
|
219 |
+
selected_date = st.sidebar.date_input("Выберите дату", value=datetime.date(2023, 10, 8), key="date_input")
|
220 |
+
selected_team = st.sidebar.selectbox("Выберите команду", options=["Все"] + list(fullname_to_code.keys()), key="team_select")
|
221 |
+
selected_opponent = st.sidebar.selectbox("Выберите оппонента", options=["Все"] + list(fullname_to_code.keys()), key="opponent_select")
|
222 |
+
selected_home_road = st.sidebar.selectbox("Где играет команда?", options=["Все", "Дома", "На выезде"], key="home_road_select")
|
223 |
+
|
224 |
+
# Фильтрация данных по выбранным критериям
|
225 |
+
filtered_data = data[data['gameDate'] == pd.to_datetime(selected_date)]
|
226 |
+
|
227 |
+
if selected_team != "Все":
|
228 |
+
filtered_data = filtered_data[filtered_data['Team'] == fullname_to_code[selected_team]]
|
229 |
+
|
230 |
+
if selected_opponent != "Все":
|
231 |
+
filtered_data = filtered_data[filtered_data['Opponent'] == fullname_to_code[selected_opponent]]
|
232 |
+
|
233 |
+
if selected_home_road != "Все":
|
234 |
+
filtered_data = filtered_data[filtered_data['homeRoad'] == (1 if selected_home_road == "Да" else 0)]
|
235 |
+
|
236 |
+
if not filtered_data.empty:
|
237 |
+
st.write(f"Игры на {selected_date}:")
|
238 |
+
|
239 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
240 |
+
col1.write("Команда")
|
241 |
+
col2.write("Оппонент")
|
242 |
+
col3.write("Где играет команда?")
|
243 |
+
col4.write("Актуальный исход матча")
|
244 |
+
col5.write("Предсказание")
|
245 |
+
|
246 |
+
for index, row in filtered_data.iterrows():
|
247 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
248 |
+
col1.write(code_to_fullname[row['Team']])
|
249 |
+
col2.write(code_to_fullname[row['Opponent']])
|
250 |
+
col3.write(home_road_mapping.get(row['homeRoad'], 'Неизвестно'))
|
251 |
+
col4.write(win_mapping.get(row['Win'], 'Нет'))
|
252 |
+
if col5.button('Предсказание', key=index):
|
253 |
+
row_dict = row.to_dict()
|
254 |
+
prediction, probability = predict_winner(row_dict, model)
|
255 |
+
st.write(f"Предсказание для игры {code_to_fullname[row['Team']]} vs {code_to_fullname[row['Opponent']]}: {prediction} {probability:.2f}")
|
256 |
+
else:
|
257 |
+
st.write("Нет игр на выбранную дату.")
|
258 |
+
|
259 |
+
# Установка фонового изображения
|
260 |
+
background_image_path = "7.jpeg"
|
261 |
+
|
262 |
+
if os.path.exists(background_image_path):
|
263 |
+
with open(background_image_path, "rb") as image_file:
|
264 |
+
encoded_image = base64.b64encode(image_file.read()).decode()
|
265 |
+
|
266 |
+
st.markdown(
|
267 |
+
f"""
|
268 |
+
<style>
|
269 |
+
.stApp {{
|
270 |
+
background-image: url("data:image/jpeg;base64,{encoded_image}");
|
271 |
+
background-size: cover;
|
272 |
+
background-repeat: no-repeat;
|
273 |
+
background-position: center center;
|
274 |
+
}}
|
275 |
+
.stSidebar {{
|
276 |
+
background: rgba(255, 255, 255, 0.8);
|
277 |
+
}}
|
278 |
+
.stButton {{
|
279 |
+
background-color: #0A74DA;
|
280 |
+
color: white;
|
281 |
+
}}
|
282 |
+
</style>
|
283 |
+
""",
|
284 |
+
unsafe_allow_html=True
|
285 |
+
)
|
286 |
+
else:
|
287 |
+
st.error(f"Изображение не найдено по пути: {background_image_path}")
|
288 |
+
|
289 |
+
elif page == "Графики":
|
290 |
+
st.title("Графики и Анализ")
|
291 |
+
|
292 |
+
# Импортирование библиотек для графиков
|
293 |
+
import matplotlib.pyplot as plt
|
294 |
+
import seaborn as sns
|
295 |
+
|
296 |
+
# Отображение локального изображения
|
297 |
+
image_path = "/home/savr/rink_master/graphs/1.png" # Укажите путь к вашему изображению
|
298 |
+
st.image(image_path, use_column_width=True)
|
299 |
+
|
300 |
+
# Отображение второго локального изображения
|
301 |
+
image_path2 = "/home/savr/rink_master/graphs/2.png" # Укажите путь ко второму изображению
|
302 |
+
st.image(image_path2, use_column_width=True)
|
303 |
+
|
304 |
+
image_path3 = "/home/savr/rink_master/graphs/3.png" # Укажите путь ко второму изображению
|
305 |
+
st.image(image_path3, use_column_width=True)
|
306 |
+
|
307 |
+
st.write("Процент побед в домашних играх: 54.55%")
|
308 |
+
st.write("Процент побед в выездных играх: 45.45%")
|
309 |
+
st.write("Домашняя арена увеличивает вероятность победы на: 9.10%")
|
310 |
+
|
311 |
+
image_path4 = "/home/savr/rink_master/graphs/4.png" # Укажите путь ко второму изображению
|
312 |
+
st.image(image_path4, use_column_width=True)
|
313 |
+
|
314 |
+
image_path5 = "/home/savr/rink_master/graphs/5.png" # Укажите путь ко второму изображению
|
315 |
+
st.image(image_path5, use_column_width=True)
|
rink_master_47816_wteams.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|