【问题标题】:how to present the prediction together with original data using RandomForestRegressor?如何使用 RandomForestRegressor 将预测与原始数据一起呈现?
【发布时间】:2020-10-31 06:35:51
【问题描述】:

我正在尝试使用 RandomForestRegressor 从 DataFrame 中的数据预测标签。

为此,我首先删除无用的列,以便回归器不会尝试使用它们,尤其是行的 ID,然后使用 get_dummy() 函数将字符串值更改为指标,然后将数据拆分为训练和测试样本.

# columns selection (let say there was also a column 'ID' so we drop this one)
features = features[['L', 'A', 'B']] 

# string to indicators
features = pd.get_dummies(features) 

# Saving labels
labels = np.array(features['L']) 

# Remove the labels from the features
features = features.drop('L', axis = 1) 

# Convert to numpy array
features = np.array(features)

# Divide into training and testing samples
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.33, random_state = 42)

# Instantiate model and fit
rf = RandomForestRegressor(n_estimators = 100, random_state = 42, max_depth = 8)
rf.fit(train_features, train_labels)

# predict
predictions = rf.predict(test_features)

所以在这个阶段我有一个样本数据看起来像

A   B_b1 B_b2
1   0    1
2   1    0

预测看起来像 大号 100 200

如果 ID 链接丢失,我如何在获得预测后将其放在原始数据旁边?我希望是这样的:

ID   A   B    L
11   1   b2   100
12   2   b1   200

我能想到复杂的方法(主要是因为从 pd.dataframe 到 np.array 的转换),但是最直接和可读(不是最有效)的方法是什么?谢谢!

【问题讨论】:

    标签: python pandas numpy data-mining prediction


    【解决方案1】:

    predictionstest_features 应该具有相同的长度,因此您可以将它们放在一个 Dataframe 中:

    results = pd.DataFrame(test_features, columns=["A", "B"])
    results["L"] = predictions 
    

    但是,我还要说您不需要将 features 转换为 np.array 的步骤,因为 train_test_splitrf.fit 都将接受 pandas.DataFrame 作为输入。

    【讨论】:

    • 谢谢托比,实际上仍然存在将字符串转换为指标列的假人部分.. 但是很好的建议,跳过转换为 numpy 数组。确实比较简单!
    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 2015-05-23
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2023-03-31
    • 2016-01-03
    相关资源
    最近更新 更多