使用torch时报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 3: invalid start byt

1 错误现象

  使用torch调用GPU时时出现以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 3: invalid start byte

2 原始代码

import torch

def test():
    x = torch.arange(2, 4, device='cuda')#直接创建
    print("直接创建:", x)
    y = torch.arange(2, 4)
    y = y.to('cuda', dtype=torch.double)#可以更改数据类型,使用y = y.cuda()亦可
    print("间接转换:", y)
    z = x + y
    print("转换回CPU:", z.to('cpu', dtype=torch.int))

if __name__ == '__main__':
    test()

3 问题解决

  出现该类错误的原因在于cuda未初始化,添加以下语句即可:

torch.cuda._initialized = True

  最终代码:

import torch

def test():
    torch.cuda._initialized = True#初始化
    x = torch.arange(2, 4, device='cuda')#直接创建
    print("直接创建:", x)
    y = torch.arange(2, 4)
    y = y.to('cuda', dtype=torch.double)#可以更改数据类型,使用y = y.cuda()亦可
    print("间接转换:", y)
    z = x + y
    print("转换回CPU:", z.to('cpu', dtype=torch.int))

if __name__ == '__main__':
    test()
原创文章 35 获赞 44 访问量 8632

猜你喜欢

转载自blog.csdn.net/weixin_44575152/article/details/103889812