PyTorch。提供的尺寸数(0)必须大于或等于张量中的尺寸数(1)

问题描述 投票:0回答:1

我试图使用Pytorch将CPU模型转换为GPU,但我遇到了问题。我在Colab上运行这个,我确信Pytorch可以检测到GPU。这是一个深度Q网络(RL)。

我声明我的网络为。Q = Q_Network(input_size, hidden_size, output_size).to(device)

当我试图通过网络传递参数时,我遇到了一个问题(它期望的是cuda类型,但得到的是cpu类型),所以我添加了.to(device)。

batch = np.array(shuffled_memory[i:i+batch_size])
b_pobs = np.array(batch[:, 0].tolist(), dtype=np.float32).reshape(batch_size, -1)
b_pact = np.array(batch[:, 1].tolist(), dtype=np.int32)
b_reward = np.array(batch[:, 2].tolist(), dtype=np.int32)
b_obs = np.array(batch[:, 3].tolist(), dtype=np.float32).reshape(batch_size, -1)
b_done = np.array(batch[:, 4].tolist(), dtype=np.bool)

q = Q(torch.from_numpy(b_pobs).to(device))
q_ = Q_ast(torch.from_numpy(b_obs).to(device))

maxq = torch.max(q_.data,axis=1)
target = copy.deepcopy(q.data)

for j in range(batch_size):
    print(target[j, b_pact[j]].shape) # torch.Size([])
    target[j, b_pact[j]] = b_reward[j]+gamma*maxq[j]*(not b_done[j]) #I run into issues here

这就是错误的地方。

RuntimeError: expand(torch.cuda.FloatTensor{[50]}, size=[]): the number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1)

python numpy pytorch tensor
1个回答
1
投票

target[j, b_pact[j]] 是一个单元素的张量(一个标量,因此大小为...)。torch.Size([])). 如果你想给它分配任何东西,右手边只能是一个标量。不是这样的,因为其中一个项是一个1维的张量(矢量),即你的 maxq[j].

当指定一个尺寸时 dim (axis 被视为同义词)到 torch.max的命名元组,它将返回一个命名为 (values, indices),其中 values 包含最大值和 indices 每个最大值的位置(相当于 argmax)。

maxq[j] 并不是对最大值进行索引,而是对以下元组进行索引。(values, indices). 如果你只想得到值,你可以使用下面的一种方法从元组中得到值(所有这些方法都是等价的,你可以使用你喜欢的任何一种方法)。

# Destructure/unpack and ignore the indices
maxq, _ = torch.max(q_.data,axis=1)

# Access first element of the tuple
maxq = torch.max(q_.data,axis=1)[0]

# Access `values` of the named tuple
maxq  = torch.max(q_.data,axis=1).values
© www.soinside.com 2019 - 2024. All rights reserved.