【问题标题】:Defining a simple neural netwok in mxnet error在 mxnet 错误中定义一个简单的神经网络
【发布时间】:2019-08-30 04:40:23
【问题描述】:

我正在使用 MXnet 制作简单的 NN,但在 step() 方法中遇到了一些问题

x1.shape=(64, 1, 1000)
y1.shape=(64, 1, 10)
net =nm.Sequential()
net.add(nn.Dense(H,activation='relu'),nn.Dense(90,activation='relu'),nn.Dense(D_out))
for t in range(500):
    #y_pred = net(x1)

    #loss = loss_fn(y_pred, y)
    #for i in range(len(x1)):

    with autograd.record():
        output=net(x1)
        loss =loss_fn(output,y1)
    loss.backward()
    trainer.step(64)
    if t % 100 == 99:
        print(t, loss)
        #optimizer.zero_grad()

用户警告:参数dense30_weight 在上下文 cpu(0) 上的梯度 自从上次 step 以来一直没有被向后更新。这可能意味着 模型中的错误使其仅使用参数的子集 (块)用于此迭代。如果您故意只使用 子集,使用 ignore_stale_grad=True 调用步骤来抑制此警告 并跳过具有陈旧梯度的参数更新

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。您的代码不是 MCVE,并且您没有指定问题。

标签: machine-learning neural-network deep-learning mxnet gluon


【解决方案1】:

该错误表明您在训练器中传递了不在计算图中的参数。 您需要初始化模型的参数并定义训练器。与 Pytorch 不同,您不需要在 MXNet 中调用 zero_grad,因为默认情况下新的梯度是写入的,而不是累积的。以下代码展示了一个使用 MXNet 的 Gluon API 实现的简单神经网络:

# Define model
net = gluon.nn.Dense(1)
net.collect_params().initialize(mx.init.Normal(sigma=1.), ctx=model_ctx)
square_loss = gluon.loss.L2Loss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.0001})

# Create random input and labels
def real_fn(X):
    return 2 * X[:, 0] - 3.4 * X[:, 1] + 4.2

X = nd.random_normal(shape=(num_examples, num_inputs))
noise = 0.01 * nd.random_normal(shape=(num_examples,))
y = real_fn(X) + noise

# Define Dataloader
batch_size = 4
train_data = gluon.data.DataLoader(gluon.data.ArrayDataset(X, y), batch_size=batch_size, shuffle=True)
num_batches = num_examples / batch_size

for e in range(10):

    # Iterate over training batches
    for i, (data, label) in enumerate(train_data):

    # Load data on the CPU
        data = data.as_in_context(mx.cpu())
        label = label.as_in_context(mx.cpu())

        with autograd.record():
            output = net(data)
            loss = square_loss(output, label)

    # Backpropagation
        loss.backward()
        trainer.step(batch_size)

        cumulative_loss += nd.mean(loss).asscalar()

    print("Epoch %s, loss: %s" % (e, cumulative_loss / num_examples))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多