RuntimeError: Could not infer dtype of numpy.int64

PyTorch中将numpy.int64转换为torch.tensor的解决方案
在实现强化学习代码时遇到了RuntimeError,原因是尝试将numpy.int64类型转换为torch.tensor时出错。解决方法是在创建torch.tensor时指定dtype为torch.float,例如:self.action_scale=torch.tensor(float(max_action), dtype=torch.float)。这确保了数据类型的正确转换,避免了运行时错误。
该文章已生成可运行项目,

RuntimeError: Could not infer dtype of numpy.int64

问题:再写强化学习代码时,遇到该错误,代码如下,对于传的参数max_action=2.0,使用
self.action_scale = torch.tensor(max_action)会报如上错误,主要是max_action变为了numpy.int64,所以不能用torch.tensor()

class Actor(nn.Module):
    # def __init__(self, action_dim, state_dim, log_std_min=-20, log_std_max=2, max_action=None):  # 这样会把min, max变为numpy.float
    def __init__(self, action_dim, state_dim, env, max_action=None):
        super(Actor, self).__init__()
        # self.min_log_std = log_std_min
        # self.max_log_std = log_std_max
        self.f1 = nn.Linear(state_dim, 200)
        self.f2 = nn.Linear(200, 200)
        self.mean = nn.Linear(200, action_dim)
        self.log_std = nn.Linear(200, action_dim)

        self.mean.weight.data.uniform_(-INIT_W, INIT_W)
        self.mean.bias.data.uniform_(-INIT_W, INIT_W)

        self.log_std.weight.data.uniform_(-INIT_W, INIT_W)
        self.log_std.bias.data.uniform_(-INIT_W, INIT_W)

        # action scaling
        if max_action == None:
            self.action_scale = torch.tensor(1.)
            self.action_bias = torch.tensor(0.)
        else:
            self.action_scale = torch.tensor(max_action)
            self.action_bias = torch.tensor(0.)

解决:使用torch.tensor()的时候加参数dtype=torch.float就可以。

self.action_scale = torch.tensor(float(max_action), dtype=torch.float)
self.action_bias = torch.tensor(0., dtype=torch.float)
本文章已经生成可运行项目
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wavehaha

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值