如何在Sklearn中将预测与输入数据测试结合起来

时间:2019-05-08 15:32:55

标签: python pandas scikit-learn

我想将模型的预测与sklearn在Python中使用的输入数据结合起来。代码是

x_train, x_test, y_train, y_test = train_test_split(x_mat, y, test_size=test_size)
mdl = RandomForestRegressor(max_depth=max_depth, n_estimators=n_estimators, n_jobs=n_jobs)
mdl.fit(x_train, y_train)
y_predict = self.mdl.predict(x_test)

问题在于两个变量的格式都不同。对于输入数据y_test {Series},我有一个像这样的系列:

  

TS

     

2018-07-01T00:00:00Z 375.25

     

2018-12-23T00:00:00Z 306.13

     

2018-11-13T00:00:00Z 542.74

     

2018-12-11T00:00:00Z 556.73

但是预测y_predict {ndarray}是这样的数组:

  

[374.35747933 303.1865425 559.07108139 545.67544684]

我想获取一个数据框,例如:

  

TS

     

2018-07-01T00:00:00Z 375.25 374.35747933

     

2018-12-23T00:00:00Z 306.13 303.1865425

     

2018-11-13T00:00:00Z 542.74 559.07108139

     

2018-12-11T00:00:00Z 556.73 545.67544684

为了在视觉上一一比较和/或一次绘制输入和预测。

我想保留带有时间戳的索引,但是由于尝试了以下操作,恐怕这可能是另一个问题:

dataset = pd.concat([pd.Series(y_predict), y_test], axis=1, ignore_index = True)

但是获得的结果将一个序列放在另一个序列下。

预先感谢

1 个答案:

答案 0 :(得分:1)

为了保留时间戳索引,您可以将系列转换为数据帧并添加一列:

results = y_test.to_frame()
results['prediction'] = y_predict