将RandomForestClassifier Predict_Proba结果添加到原始数据帧

时间:2018-02-23 11:48:31

标签: python python-3.x pandas dataframe random-forest

我是一个新手,我的第一个真正的' ML算法。如果这是重复的道歉,但我无法在SO上找到答案。

我已获得以下数据框(df):

index    Feature1  Feature2  Feature3  Target
001       01         01        03        0
002       03         03        01        1
003       03         02        02        1

我的代码看起来像这样:

data = df[['Feature1', 'Feature2', 'Feature3']]
labels = df['Target']
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size = 0.8)

clf = RandomForestClassifier().fit(X_train, y_train)

prediction_of_probability = clf.predict_proba(X_test)

我正在努力解决的问题是如何将'prediction_of_probability'带回数据框df

我理解预测不适用于原始数据框中的所有项目。

提前感谢您帮助像我这样的新手!

3 个答案:

答案 0 :(得分:3)

您可以尝试保留列车的索引并进行测试,然后以这种方式将它们组合在一起:

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

data = df[['Feature1', 'Feature2', 'Feature3']]
labels = df['Target']
indices = df.index.values 

# use the indices instead the labels to save the order of the split.

X_train, X_test,indices_train,indices_test = train_test_split(data,indices, test_size=0.33, random_state=42)

y_train, y_test = labels[indices_train],  labels[indices_test]


clf = RandomForestClassifier().fit(X_train, y_train)

prediction_of_probability = clf.predict_proba(X_test)

然后您可以将概率放在新的df_new

>>> df_new = df.copy()
>>> df_new.loc[indices_test,'pred_test'] = prediction_of_probability # clf.predict_proba(X_test)
>>> print(df_new)

   Feature1  Feature2  Feature3  Target  pred_test
1         3         3         1       1        NaN
2         3         2         2       1        NaN
0         1         1         3       0        1.0

甚至对火车的预测:

>>> df_new.loc[indices_train,'pred_train'] = clf.predict_proba(X_train)
>>> print(df_new)

   Feature1  Feature2  Feature3  Target  pred_test  pred_train
1         3         3         1       1        NaN         1.0
2         3         2         2       1        NaN         1.0
0         1         1         3       0        1.0         NaN

或者如果你想混合训练和测试的概率,只需使用相同的列名(即pred)。

答案 1 :(得分:2)

你所做的就是训练模型。这意味着,通过您拥有的功能和标签,您可以为未来的数据训练模型。 为了测试模型的质量(例如选择特征),在X_test和y_test上测试模型。 在这种情况下,您没有未来的数据,所以您没有应用您的模型,您只是在训练它。您可以使用AUC或ROC曲线查看模型的质量。

无论如何,您可以通过以下方式将结果附加到数据框:

df_test = pd.DataFrame(X_test)
df_test['Target'] = y_test
df_test['prob_0'] = prediction_of_probability[:,0] 
df_test['prob_1'] = prediction_of_probability[:,1]

答案 2 :(得分:0)

你需要这样的东西:

# Create new dataframe to store test data.
df1 = pd.DataFrame(X_test)
df1['Target'] = y_test
df1['prob'] = prediction_of_probability[:,0]  

# Create another dataframe to store train data
df2 = pd.DataFrame(X_train)
df2['Target'] = y_train

# Append both dataframes
df = df1.append(df2).sort_index()