相关疑难解决方法(0)

Pytorch ValueError:优化器得到一个空的参数列表

在尝试创建神经网络并使用 Pytorch 对其进行优化时,我得到了

ValueError:优化器得到一个空的参数列表

这是代码。

import torch.nn as nn
import torch.nn.functional as F
from os.path import dirname
from os import getcwd
from os.path import realpath
from sys import argv

class NetActor(nn.Module):

    def __init__(self, args, state_vector_size, action_vector_size, hidden_layer_size_list):
        super(NetActor, self).__init__()
        self.args = args

        self.state_vector_size = state_vector_size
        self.action_vector_size = action_vector_size
        self.layer_sizes = hidden_layer_size_list
        self.layer_sizes.append(action_vector_size)

        self.nn_layers = []
        self._create_net()

    def _create_net(self):
        prev_layer_size = self.state_vector_size
        for next_layer_size in self.layer_sizes:
            next_layer = nn.Linear(prev_layer_size, next_layer_size)
            prev_layer_size = next_layer_size
            self.nn_layers.append(next_layer)

    def forward(self, torch_state):
        activations = torch_state
        for …
Run Code Online (Sandbox Code Playgroud)

python machine-learning reinforcement-learning backpropagation pytorch

10
推荐指数
1
解决办法
9048
查看次数

如何在循环中为 pytorch 神经网络中的层创建变量名称

我正在 PyTorch 中实现一个简单的前馈神经 newtork。但是我想知道是否有更好的方法来向网络添加灵活的层数?也许通过在循环中命名它们,但我听说那是不可能的?

目前我正在这样做

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self, input_dim, output_dim, hidden_dim):
        super(Net, self).__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.hidden_dim = hidden_dim
        self.layer_dim = len(hidden_dim)
        self.fc1 = nn.Linear(self.input_dim, self.hidden_dim[0])
        i = 1
        if self.layer_dim > i:
            self.fc2 = nn.Linear(self.hidden_dim[i-1], self.hidden_dim[i])
            i += 1
        if self.layer_dim > i:
            self.fc3 = nn.Linear(self.hidden_dim[i-1], self.hidden_dim[i])
            i += 1
        if self.layer_dim > i:
            self.fc4 = nn.Linear(self.hidden_dim[i-1], self.hidden_dim[i])
            i += 1
        if self.layer_dim > i: …
Run Code Online (Sandbox Code Playgroud)

python neural-network torch pytorch

4
推荐指数
1
解决办法
2423
查看次数

ValueError:优化器得到一个空的参数列表

我创建了以下简单的线性类:

class Decoder(nn.Module):
    def __init__(self, K, h=()):
        super().__init__()
        h = (K,)+h+(K,)
        self.layers = [nn.Linear(h1,h2) for h1,h2 in zip(h, h[1:])]

    def forward(self, x):
        for layer in self.layers[:-1]:
            x = F.relu(layer(x))
        return self.layers[-1](x)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将参数放在优化器类中时,我得到了错误ValueError: optimizer got an empty parameter list

decoder = Decoder(4)
LR = 1e-3
opt = optim.Adam(decoder.parameters(), lr=LR)
Run Code Online (Sandbox Code Playgroud)

类定义有什么我做的明显错误吗?

pytorch

1
推荐指数
1
解决办法
1463
查看次数