python+决策树2

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"
#修复参数,将Date列的值由字符串改为日期类型.
dataset = pd.read_csv(filename, parse_dates=["Date"])  #将Date列的值由字符串改为日期类型。
#定义表头即定义属性列。 
dataset.columns = ["Date","StartTime","VistorTeam","VisitorPTS","HomeTeam","HomePTS","ScoreType","OT?","Notes"]
#添加新特征,主场获胜与否(1表示主场获胜,0表示主场未获胜),作为预测的结果是否正确的标准。
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"
    #standings[ standings["Team"]== homeTeam ],首先在standings筛选出homeTeam,然后得到它的排名
    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
#加入2支球队上场比赛情况作为判断依据(思路:如果上场比赛A打赢B,则预测下场比赛A依然会打赢B)
last_match_winner = defaultdict(int)  #存放0或1,分别表示客场和主场胜利
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)) 

运行结果:
这里写图片描述

你可能感兴趣的:(python决策树,python数据挖掘)