【发布时间】: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