Exemplo n.º 1
0
 def setUp(self):
     """Initialization"""
     self.db_root = Config().data_dir
     self.repoCode = get_git_root()
     self.repoModel = path.join(
         self.repoCode,
         'ReinforcementLearning/NHL/playerstats/offVSdef/Automatic_classification/MODEL_perceptron_1layer_10units_relu'
     )
Exemplo n.º 2
0
    def setUp(self):
        """Initialization"""
        self.db_root = Config(
        ).data_dir  # This is the location of the Hockey database
        self.repoCode = get_git_root()

        self.repoModel = path.join(
            self.repoCode,
            'ReinforcementLearning/NHL/playerstats/offVSdef/Automatic_classification/MODEL_perceptron_1layer_10units_relu'
        )

        # Now lets get game data
        self.season = Season(
            db_root=self.db_root, repo_model=self.repoModel,
            year_begin=2012)  # Season.from_year_begin(2012) # '20122013'
        # Montreal received Ottawa on march 13, 2013, let's convert game date to game code
        gameId = self.season.get_game_id(home_team_abbr='MTL',
                                         game_date=datetime.date(year=2013,
                                                                 month=3,
                                                                 day=13))
        self.a_game = Game(self.season, gameId=gameId)
    graph          =   classifier['sess'].graph
    classifier['annX'] =   graph.get_tensor_by_name('Input_to_the_network-player_features:0')
    classifier['annY'] =   graph.get_tensor_by_name('prediction:0')
    saver.restore(classifier['sess'], tf.train.latest_checkpoint(path.join(repoModel, './')))
    return players_model, classifier




# ========
# LAUNCHER
# ========
# === Set pointers
# Pointers to the data
repoCode    =   get_git_root()
db_root = Config().data_dir #This is the location of the Hockey database
# db_root     =   '/Users/younes_zerouali/Documents/Stradigi/Databases/Hockey'
# db_root     =   '/Users/luisd/dev/NHL_stats/data'
repoPbP     =   path.join(db_root, 'PlayByPlay')
repoPSt     =   path.join(db_root, 'PlayerStats/player')
repoModel   =   path.join(repoCode, 'ReinforcementLearning/NHL/playerstats/offVSdef/Automatic_classification/MODEL_backup_trainedonallseasons_rankstatprediction')
repoModel   =   path.join(repoCode, 'ReinforcementLearning/NHL/playerstats/offVSdef/Automatic_classification/MODEL_perceptron_1layer_10units_relu')
repoSave    =   None #path.join(repoCode, 'ReinforcementLearning/NHL/playbyplay/data')

# === Pipeline
# Select a season
season      =   '20122013'

# List all games
HSS         =   HockeySS(repoPbP, repoPSt)
HSS.list_all_games()
if __name__ == '__main__':
    from Utils.base import get_logger
    import pandas as pd
    import matplotlib.pyplot as plt
    import os
    from ReinforcementLearning.NHL.config import Config

    common_logger = get_logger(name="common_logger",
                               debug_log_file_name="common_logger.log")
    print("Debug will be written in {}".format(
        common_logger.handlers[1].baseFilename))

    coaches_evaluator = Coach_Evaluator(common_logger)
    grades = coaches_evaluator.read_and_display_coaches_evals()

    standings_file_name = os.path.join(Config().data_dir,
                                       "NHLStandings2012-2013.csv")
    df = pd.DataFrame.from_csv(standings_file_name)
    # add column with abbreviation
    df['ABBREV'] = pd.Series(list(map(name2abbrev, df["TEAM"].values)),
                             index=df.index)
    df['GRADE'] = pd.Series(list(
        map(lambda abbrev: grades[abbrev], df["ABBREV"].values)),
                            index=df.index)
    df['WINS'] = pd.Series(list(
        map(lambda record: int(record.split("-")[0]), df["Overall"].values)),
                           index=df.index)
    df.plot(kind='scatter', x="GRADE", y="WINS")  # , 'rx')
    plt.show()
Exemplo n.º 5
0
    def evaluate_all_coaches(self, season_year_begin: int,
                             teams_opt: Optional[List[str]], n_games: int):
        from ReinforcementLearning.NHL.playbyplay.state_space_data import HockeySS
        """Initialization"""
        os.makedirs(self.base_dir, exist_ok=True)
        my_config = Config()
        self.alogger.debug("Data configured to be in '%s'" %
                           (my_config.data_dir))

        db_root = my_config.data_dir
        repoCode = get_git_root()

        repoModel = path.join(
            repoCode,
            'ReinforcementLearning/NHL/playerstats/offVSdef/Automatic_classification/MODEL_perceptron_1layer_10units_relu'
        )

        season = Season(self.alogger,
                        db_root=db_root,
                        year_begin=season_year_begin,
                        repo_model=repoModel)

        # Line translation table
        linedict = HockeySS(db_root)
        linedict.make_line_dictionary()
        linedict = linedict.line_dictionary

        # Load the Qvalues table
        Qvalues = \
        pickle.load(open(path.join(repoCode, 'ReinforcementLearning/NHL/playbyplay/data/stable/RL_action_values.p'), 'rb'))[
            'action_values']

        # Visualize it dimensions (period x differential x away line's code x home line's code)
        print('Q-table dimensions: ', Qvalues.shape)

        # for what teams will we run this calculation?
        calc_teams = season.get_teams() if teams_opt is None else teams_opt
        for a_team in calc_teams:
            season.alogger.debug("=============> calculating %s" % (a_team))
            seconds = get_teams_coach_performance(season,
                                                  team_abbr=a_team,
                                                  maybe_a_starting_date=None,
                                                  line_dict=linedict,
                                                  Qvalues=Qvalues,
                                                  how_many_games=n_games)
            season.alogger.debug(seconds)

            if seconds["does_not_match_optimal"] == seconds[
                    "matches_optimal"] == 0:
                season.alogger.info(
                    "[team: '%s'] No evidence for coach to be evaluated on." %
                    (a_team))
            else:
                total_secs = seconds['matches_optimal'] + seconds[
                    'does_not_match_optimal']
                season.alogger.info(
                    "['%s'] Home coach's score is %d (secs. optimal) / %d (secs. total) = %.2f (in [0,1])"
                    % (a_team, seconds['matches_optimal'], total_secs,
                       seconds['matches_optimal'] / total_secs))
            file_to_save = os.path.join(self.base_dir, a_team + ".pkl")
            self.alogger.debug("Saving data for '%s' in file %s" %
                               (a_team, file_to_save))
            with open(file_to_save, 'wb') as dict_file:
                pickle.dump(seconds, dict_file)
            self.alogger.debug("DONE")
Exemplo n.º 6
0
 def __init__(self, alogger: logging.Logger):
     self.alogger = alogger
     self.base_dir = os.path.join(Config().data_dir, "coaches_perf")
     self.alogger.debug("Read info from '%s'" % (self.base_dir))
from ReinforcementLearning.NHL.lines.coach import Coach_Evaluator
from ReinforcementLearning.NHL.lines.correlation_with_performance import name2abbrev

if __name__ == '__main__':
    from Utils.base import get_logger
    import pandas as pd
    import matplotlib.pyplot as plt
    import os
    from ReinforcementLearning.NHL.config import Config

    common_logger = get_logger(name="common_logger", debug_log_file_name="common_logger.log")
    print("Debug will be written in {}".format(common_logger.handlers[1].baseFilename))

    coaches_evaluator = Coach_Evaluator(common_logger)
    grades = coaches_evaluator.read_and_display_coaches_evals()

    attendance_file_name = os.path.join(Config().data_dir, "NHLAttendance2012-2013.csv")
    df = pd.DataFrame.from_csv(attendance_file_name)
    # add column with abbreviation
    df['ABBREV'] = pd.Series(list(map(name2abbrev, df["TEAM"].values)), index=df.index)
    df['GRADE'] = pd.Series(list(map(lambda abbrev: grades[abbrev], df["ABBREV"].values)), index=df.index)
    df.AVG = df.AVG.str.replace(",", "")
    df.AVG = df.AVG.astype(float)
    df.plot(kind='scatter', x="GRADE", y="AVG") # , 'rx')
    plt.show()