【问题标题】:TypeError: trace(): argument 'input' (position 1) must be Tensor, not methodTypeError: trace(): 参数“输入”(位置 1)必须是张量,而不是方法
【发布时间】:2021-04-02 19:45:20
【问题描述】:

我在启动脚本时遇到了这个奇怪的错误,我真的不知道为什么会出现这个错误,或者是什么原因造成的。如果你们中的一些人能帮助我解决这个错误,那就太好了:)

错误信息:

  File "c:/Users/supre/Documents/Python Programs/neuralnet/optimize_graph.py", line 11, in trace
    traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) 
TypeError: trace(): argument 'input' (position 1) must be Tensor, not method

这是我的代码:

import argparse
import torch
from model import SpeechRecognition
from collections import OrderedDict

def trace(model):
    model.eval()
    x = torch.rand(1, 81, 300)
    hidden = model._init_hidden(1)
    traced = torch.trace(model.forward)(xample_inputs=(x, hidden))
    return traced

def main(args):
    print("loading model from", args.model_checkpoint)
    checkpoint = torch.load(args.model_checkpoint, map_location=torch.device('cpu'))
    h_params = SpeechRecognition.hyper_parameters
    model = SpeechRecognition(**h_params)
    model_state_dict = checkpoint['state_dict']
    new_state_dict = OrderedDict()
    for k, v in model_state_dict.items():
        name = k.replace("model.", "") # remove `model.`
        new_state_dict[name] = v

    model.load_state_dict(new_state_dict)

    print("tracing model...")
    traced_model = trace(model)
    #print(type(traced_model))
    print("saving to", args.save_path)
    traced_model.save(args.save_path)
    print("Done!")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="testing the wakeword engine")
    parser.add_argument('--model_checkpoint', type=str, default='NameOfYourCheckpoint', required=False,
                        help='Checkpoint of model to optimize')
    parser.add_argument('--save_path', type=str, default='path/where/you/want/to/save/the/optimized/model', required=False,
                        help='path to save optmized model')

    args = parser.parse_args()
    main(args)

提前感谢您的每一个帮助

【问题讨论】:

  • 您是否有 SpeechRecognition 文档的链接,尤其是 forward?
  • @Accumulation 不,但我有一个回购链接。我应该给你回购链接吗?
  • @Acccumulation 能否请您将我添加到不和谐中,因为我可以告诉您更多有关该错误以及我认为它可能由什么引起的信息。名称:CodeForce1#8083
  • 获取文档是一个基本步骤。我不知道你如何在不知道它做什么的情况下使用一个模块。我在发表评论或答案之间摇摆不定。我认为如果你用forward()而不是forward,很可能会解决问题,但这最终是猜测。
  • 好的,谢谢,我会试试的:)

标签: python python-3.x machine-learning deep-learning pytorch


【解决方案1】:

在traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) 中,您正在传递一个方法,即model.forward,您应该使用类似这样的方法 traced = torch.trace(model.forward(x)) 如果你的模型已经有一个带参数的实例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多