import pandas as pd
from sklearn.model_selection._validation import cross_val_score
from sklearn.tree import DecisionTreeClassifier
import numpy as np
from collections import defaultdict
clf = DecisionTreeClassifier(random_state=14)
filename = "dicision_trees_sample.csv"
dataset = pd.read_csv(filename, parse_dates=["Date"])
dataset.columns = ["Date","StartTime","VistorTeam","VisitorPTS","HomeTeam","HomePTS","ScoreType","OT?","Notes"]
dataset["HomeWin"] = dataset["VisitorPTS"] < dataset["HomePTS"]
x_c = dataset["HomeWin"].values
dataset["HomeTeamRanksHiger"] = 0
standings_filename = "leagues_NBA_2013_standings_expanded-standings.csv"
standings = pd.read_csv(standings_filename)
for index, row in dataset.sort_values("Date").iterrows():
homeTeam = row["HomeTeam"]
visitorTeam = row["VistorTeam"]
if homeTeam == "New Orleans Pelicans":
homeTeam = "New Orleans Hornets"
elif visitorTeam == "New Orleans Pelicans":
visitorTeam = "New Orleans Hornets"
homeRank = standings[ standings["Team"]== homeTeam ]["Rk"].values[0]
visitorRank = standings[ standings["Team"]== visitorTeam]["Rk"].values[0]
row["HomeTeamRanksHiger"] = int(homeRank > visitorRank)
dataset.ix[index] = row
last_match_winner = defaultdict(int)
dataset["HomeTeamWonLast"] = 0
for index, row in dataset.sort_values("Date").iterrows():
homeTeam = row["HomeTeam"]
visitorTeam = row["VistorTeam"]
teams = tuple(sorted([homeTeam,visitorTeam]))
row["HomeTeamWonLast"] = 1 if last_match_winner[teams] == row["HomeTeam"] else 0
dataset.ix[index] = row
winner = row["HomeTeam"] if row["HomeWin"] else row["VistorTeam"]
last_match_winner[teams] = winner
x_lastwinner = dataset[["HomeTeamRanksHiger","HomeTeamWonLast"]].values
scores = cross_val_score(clf, x_lastwinner, x_c, scoring="accuracy")
print("上场2球队之间比赛结果+球队排名作为预测下场比赛这2支球队比赛结果的依据,Accuracy: {0:.1f}%".format(np.mean(scores) * 100))
运行结果: