【问题标题】:scikit-learn: add clf.prediction() to different dataframescikit-learn:将 clf.prediction() 添加到不同的数据帧
【发布时间】:2016-04-25 19:07:37
【问题描述】:

我已经训练了我的 RandomForestClassifier(),现在希望将我的预测添加到我新导入的测试 DF 中,我称之为 df_test。

我已将我的特征列添加到 df_test 数据框,供 clf.predict 方法使用。

我无法弄清楚如何使用我的 clf.predict() 方法向 df_test 添加新列。

关于我的训练数据:

clf = RandomForestClassifier()
clf.fit(df3[features], df['rounded_score'])
pd.crosstab(clf.predict(df3[features]), df3['rounded_score'])

准备好我的测试数据:

df_test = pd.read_csv("test.csv")
df_test['match_ratio'] = df.apply(lambda x: fuzz.ratio(x['search_term'], x['product_title']), axis=1)
df_test['partial_match_ratio'] = df.apply(lambda x: fuzz.partial_ratio(x['search_term'], x['product_title']), axis=1)
df_test['tsort_match_ratio'] = df.apply(lambda x: fuzz.token_sort_ratio(x['search_term'], x['product_title']), axis=1)

我已经尝试了大约十几个迭代代码,如下所示:

df_test['prediction'] = df_test[something].apply(lambda x: clf.predict(x))

但是 predict 方法一直告诉我它正在寻找一个 numpy 数组。所以,我尝试了以下方法,它有效:

mat = df_test[['match_ratio', 'partial_match_ratio', 'tsort_match_ratio']].as_matrix()
for x in mat[:10]:
    print clf.predict(x)

但我不知道如何将这些数据作为新列放入我的 df_test 数据框中。我最后的考虑是将预测附加到一个常规的 python 列表中,然后以某种方式将其添加到数据框中……但这似乎有点混乱。

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    假设df_test[something] 包含特征,您可以附加一个包含预测写作的新列

    df_test['prediction']=clf.predict(df_test[something])
    

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 2017-08-30
      • 2016-11-26
      • 1970-01-01
      • 2017-02-16
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多