Pytorch 类型错误:Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor.

Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor

In the process of Pytorcht debugging, the data is transferred to the model for calculation. This error appears, indicating that there is a problem with your data format. Maybe the model is on the GPU and the parameter is the CPU type. Maybe the model is the CPU and the parameter is the GPU type. This is due to the use of .cuda() for conversion. Two methods can be solved.

1. Since FloatTensor is needed, force your model and data to be converted to cpu, and then convert the model and input of GPU to CPU.

    device1=torch.device("cpu")
    model_ft = model_ft.to(device1)#将模型转换为cpu版本。
    model_ft.train()
    inputs = inputs.to(device1)#将输入数据转换为CPU版本。
    labels = labels.to(device1)#将label转换为CPU版本。
    output = model_ft(inputs)
    _,preds = torch.max(output,1)

2. Convert the model and data to the GPU version. Since the parameter is cuda.FloatTensor, it means that the model parameter is of the cuda type. Forcing the input and model to be on the GPU is fine.

    device1=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model_ft = model_ft.to(device1)#将模型转换为GPU版本。
    model_ft.train()
    inputs = inputs.to(device1)#将输入数据转换为GPU版本。
    labels = labels.to(device1)#将label转换为GPU版本。
    output = model_ft(inputs)
    _,preds = torch.max(output,1)

 

 

 

Guess you like

Origin blog.csdn.net/qq_32998593/article/details/87939016