[Python] My d2l #@save is not working in jupyter notebook

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    Why is my train_ch3 function with #@save not accessible in other notebooks when using d2l?


    I am following the d2l (Dive into Deep Learning) framework and trying to save the train_ch3 function using the #@save annotation so that it can be accessed from other notebooks. However, even after adding the #@save annotation and ensuring I have imported the d2l package correctly, the function is not available when I try to call it from another notebook using from d2l import train_ch3.

    Other functions with the #@save annotation work fine, but this specific function does not seem to be recognized. Below is the code for my train_ch3 function:

    def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save
    """Train a model (defined in Chapter 3)"""
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
    legend=['train loss', 'train acc', 'test acc'])
    for epoch in range(num_epochs):
    train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
    test_acc = evaluate_accuracy(net, test_iter)
    animator.add(epoch + 1, train_metrics + (test_acc,))
    train_loss, train_acc = train_metrics
    assert train_loss < 0.5, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc


    Here is how I try to import and use the function in another notebook:

    from d2l import train_ch3


    But this results in the following error:

    ImportError: cannot import name 'train_ch3' from 'd2l' (unknown location)

    What I've checked so far:

    1. Other functions with #@save work: Functions like train_epoch_ch3 and evaluate_accuracy are accessible after adding #@save.
    2. d2l installation: I confirmed that d2l is installed and up-to-date (pip install --upgrade d2l).
    3. Notebook execution: I ensured that the cell defining train_ch3 has been executed before trying to use it in another notebook.
    My question:


    Why does the train_ch3 function fail to be recognized for import despite using the #@save annotation? Is there something specific about #@save usage or the d2l package that I might be missing?

    Any help or guidance would be greatly appreciated!

    Continue reading...

Compartilhe esta Página