如何使用随机森林做出(是/否或1-0)决策?

时间:2017-05-04 22:53:15

标签: python pandas scikit-learn random-forest decision-tree

这是来自Kaggle的泰坦尼克竞赛(traintest csv文件)的数据集。每个文件都有乘客的特征,如身份证,性别,年龄等。火车文件有一个幸存的"具有0和1值的列。由于必须预测,测试文件缺少幸存列。 这是我使用随机森林的简单代码,为我提供了启动器的基准:

import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
import random
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import roc_curve, auc

train=pd.read_csv('train.csv')
test=pd.read_csv('test.csv')
train['Type']='Train' #Create a flag for Train and Test Data set
test['Type']='Test'
fullData = pd.concat([train,test],axis=0) #Combined both Train and Test Data set

ID_col = ['PassengerId']
target_col = ["Survived"]
cat_cols = ['Name','Ticket','Sex','Cabin','Embarked']
num_cols= ['Pclass','Age','SibSp','Parch','Fare']
other_col=['Type'] #Test and Train Data set identifier

num_cat_cols = num_cols+cat_cols # Combined numerical and Categorical variables
for var in num_cat_cols:
    if fullData[var].isnull().any()==True:
        fullData[var+'_NA']=fullData[var].isnull()*1 

#Impute numerical missing values with mean
fullData[num_cols] = fullData[num_cols].fillna(fullData[num_cols].mean(),inplace=True)
#Impute categorical missing values with -9999
fullData[cat_cols] = fullData[cat_cols].fillna(value = -9999)

#create label encoders for categorical features
for var in cat_cols:
 number = LabelEncoder()
 fullData[var] = number.fit_transform(fullData[var].astype('str'))

train=fullData[fullData['Type']=='Train']
test=fullData[fullData['Type']=='Test']

train['is_train'] = np.random.uniform(0, 1, len(train)) <= .75
Train, Validate = train[train['is_train']==True], train[train['is_train']==False]

features=list(set(list(fullData.columns))-set(ID_col)-set(target_col)-set(other_col))

x_train = Train[list(features)].values
y_train = Train["Survived"].values
x_validate = Validate[list(features)].values
y_validate = Validate["Survived"].values
x_test=test[list(features)].values

Train[list(features)]

#*************************
from sklearn import tree

random.seed(100)
rf = RandomForestClassifier(n_estimators=1000)
rf.fit(x_train, y_train)

status = rf.predict_proba(x_validate)
fpr, tpr, _ = roc_curve(y_validate, status[:,1]) #metrics. added by me
roc_auc = auc(fpr, tpr)
print(roc_auc)

final_status = rf.predict_proba(x_test)
test["Survived2"]=final_status[:,1]

test['my prediction']=np.where(test.Survived2 > 0.6, 1, 0)

test

如您所见,final_status给出了生存的概率。我想知道如何从中得到是/否(1或0)答案。我能想到的最简单的事情是说,如果概率大于0.6,那么这个人幸存下来并以其他方式死亡(&#39;我的预测&#39;列)但是一旦我提交了结果,预测就完全没有了

我感谢任何见解。感谢

2 个答案:

答案 0 :(得分:0)

将概率转换为二进制输出是正确的方法,但为什么选择&gt; .6而不是&gt; 0.5

此外,如果您在这种情况下遇到不好的结果,很可能是因为您没有在数据清理和特征提取方面做得很好。例如,标题(“Mr”,“Mrs”,......)可以为您提供性别指示,这是您的问题中需要考虑的一个非常重要的特征(我认为这是来自kaggle的巨大竞争)。 / p>

答案 1 :(得分:0)

我只需要使用类似的行:

out = rf.predict(x_test)

这就是我要找的0/1答案。