【问题标题】:Pytorch - extracting predicted values to an arrayPytorch - 将预测值提取到数组中
【发布时间】:2021-09-16 14:30:53
【问题描述】:

我是一名新的 pytorch 用户,对 Tensorflow/Keras 的体验适中。 pytorch 的例子很棒。我已经使用 Temporal Fusion Transform (https://pytorch-forecasting.readthedocs.io/en/latest/tutorials/stallion.html) 完成了需求预测实验室。

一切都说得通,但还没有弄清楚如何将笔记本第 20 节中的预测值保存到 numpy 数组中。

第 20 节, *new_raw_predictions, new_x = best_tft.predict(new_prediction_data, mode="raw", return_x=True)*

我看到张量中的值 print(new_raw_predictions) , 像这样 - *{'预测': 张量([[[3.4951e+00, 1.7341e+01, 2.7446e+01, ..., 6.3175e+01, 9.0240e+01, 1.2589e+02], [1.1698e+01, 2.3643e+01, 3.3291e+01, ..., 6.6374e+01, 9.1148e+01, 1.3173e+02],

我在这里看到过一些类似的问题,但似乎都没有。所有尝试都会导致类似的错误,因此我缺少有关 pytorch 和输出张量的基本信息;我总是得到'AttributeError:'dict'对象没有属性new_raw_predictions'

一些已尝试的示例: *new_raw_predictions.cpu().numpy() new_raw_predictions.detach().cpu().numpy() new_raw_predictions.numpy()*

目标是保存预测输出,以便我可以比较模型的更改。提前致谢!

【问题讨论】:

    标签: python numpy pytorch


    【解决方案1】:

    这完全取决于您如何创建模型,因为 pytorch 可以返回任何您指定的值。在您的情况下,它看起来像返回一个字典,其中“预测”是一个键。您可以使用上面提供的命令转换为 numpy,但只需进行一处更改:

    preds = new_raw_predictions['prediction'].detach().cpu().numpy()
    

    当然,如果不在 GPU 上,则无需使用 .detach().cpu(),只需 .numpy()

    【讨论】:

    • 成功了!!!谢谢。我没有用“python”的术语来思考。
    • 很高兴能帮上忙。您能否接受这个答案,以便其他人可以轻松找到它? :)
    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多