Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
mzaninovic555 committed May 2, 2024
1 parent 23ba9ee commit 596b55c
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 42 deletions.
File renamed without changes.
20 changes: 0 additions & 20 deletions football_dataset.py

This file was deleted.

Empty file added model/__init__.py
Empty file.
39 changes: 39 additions & 0 deletions model/football_dataset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import pandas as pd
import torch
from sklearn import preprocessing
from torch.utils.data import Dataset

pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 30)
pd.set_option('display.width', 1000)


class FootballDataset(Dataset):
def __init__(self, csv_file):
self.data = pd.read_csv(csv_file)
self.data.drop(
columns=["game_id",
"date",
"competition_id",
"home_club_name",
"away_club_name",
"competition_type"],
inplace=True)
self.data.dropna(inplace=True)
# self.data.fillna(0, inplace=True)

# transform all except result columns
x_scaled = preprocessing.MinMaxScaler().fit_transform(self.data)

# concat scaled and result columns
self.data = pd.DataFrame(x_scaled)

def __len__(self):
return len(self.data)

def __getitem__(self, idx):
sample = self.data.iloc[idx]
features = sample[:-3].values.astype(dtype=float)
target = sample[-3:].values.astype(dtype=float)

return torch.tensor(features, dtype=torch.float32), torch.tensor(target, dtype=torch.float32)
58 changes: 58 additions & 0 deletions model/load_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import torch

from main import NeuralNetwork

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = torch.load(
"./models/football_predictor_2024_04_27_18_57_29_model.pt").to(device)
model.eval()

# current_position_distance
# home_goals_scored
# home_goals_conceded
# home_goal_difference
# away_goals_scored
# away_goals_conceded
# away_goal_difference
# home_last_5_wins
# home_last_5_draws
# home_last_5_losses
# away_last_5_wins
# away_last_5_draws
# away_last_5_losses
# home_season_wins
# home_season_draws
# home_season_losses
# away_season_wins
# away_season_draws
# away_season_losses

# home_win
# draw
# away_win

# milan - inter
# data = torch.tensor(
# [1, 63, 37, 24, 77, 17, 60, 3, 1, 1, 3, 2, 0, 21, 6, 6, 27, 5, 1],
# dtype=torch.float).to(device)

# milan - juve
# data = torch.tensor(
# [1, 47, 26, 21, 64, 39, 25, 1, 3, 1, 3, 1, 1, 18, 10, 5, 21, 6, 6],
# dtype=torch.float).to(device)

data = torch.tensor(
[1, 62, 20, 42, 58, 24, 34, 5, 0, 0, 5, 0, 0, 22, 5, 4, 22, 6, 4],
dtype=torch.float).to(device)

output = model(data)
print()
print(f"Prediction (home_win, draw, away_win): {output}")
print(
f"Prediction (home_win, draw, away_win): {torch.nn.functional.softmax(output, dim=0)}")

predicted = torch.argmax(output, dim=0)
predicted_one_hot = torch.nn.functional.one_hot(predicted,
num_classes=3)
print(f"Prediction one_hot (home_win, draw, away_win): {predicted_one_hot}")

27 changes: 5 additions & 22 deletions main.py → model/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@

writer = SummaryWriter()

dataset = FootballDataset('./data/onehotz.csv')
dataset = FootballDataset('./data/dataset.csv')

input_features = dataset.__getitem__(0)[0].size(dim=0)
output_features = dataset.__getitem__(0)[1].size(dim=0)

batch_size = 32
epochs = 60
batch_size = 64
epochs = 80
learning_rate = 0.003
dropout_rate = 0.25
dropout_rate = 0.5
hidden_layer_size = floor(input_features * 16)
hidden_layer_size2 = floor(input_features * 8)
hidden_layer_size3 = floor(input_features * 4)
Expand All @@ -38,16 +38,12 @@ def __init__(self):
super().__init__()

self.activation_function = nn.ReLU()
# self.hidden_func = nn.LeakyReLU()
# self.hidden_func = nn.Tanh()
# self.hidden_func = nn.Sigmoid()

self.dropout = nn.Dropout(dropout_rate)

self.sequential = nn.Sequential(
# input
nn.Linear(input_features, hidden_layer_size),
nn.BatchNorm1d(hidden_layer_size2),
self.activation_function,

# hidden 1
Expand Down Expand Up @@ -139,7 +135,6 @@ def train():

model.eval()

i = 0
valid_correct = 0
valid_total = 0
for data, target in validation_loader:
Expand All @@ -149,26 +144,14 @@ def train():
# Get predictions
output = model(data)

# Calculate loss
loss = criterion(output, target)

predicted = torch.argmax(output, dim=1)
predicted_one_hot = torch.nn.functional.one_hot(predicted,
num_classes=3)

valid_correct += (predicted_one_hot == target).all(dim=1).sum()
valid_total += target.size(0)
accuracy = (valid_correct / valid_total) * 100

if (i + 1) % 100 == 0:
print(
'Step [{}/{}], Loss: {:.4f}, Accuracy: {}'.format(
i, len(validation_loader), loss.item(),
accuracy))
i += 1

print(
f"Validation finished, total accuracy: {(valid_correct / valid_total) * 100}")
print(f"Validation finished, total accuracy: {(valid_correct / valid_total) * 100}")


if __name__ == '__main__':
Expand Down

0 comments on commit 596b55c

Please sign in to comment.