IndentationError: ожидал блок с отступом с использованием исключения - PullRequest
1 голос
/ 16 октября 2019

Мой код: я пытался исследовать ошибку, используя исключение, и я нашел следующее

    try:
while((train_iter.epoch < max_epoch) and needStudy):
    train_batch = train_iter.next()
    x, t = concat_examples(train_batch)
    #print(t)    
    y = model(x)    
    loss = F.mean_squared_error(y, t)
    model.cleargrads()
    loss.backward()
    optimizer.update()
    if train_iter.is_new_epoch:
        print("epoch", train_iter.epoch, "loss=", loss.data, end=" ")
        loss_X.append(train_iter.epoch)
        loss_Y.append(loss.data)
except ValueError as e:
        raise Exception('Invalid json: {}'.format(e))

И я сталкиваюсь с ошибкой:

File "<ipython-input-393-be26bc8a85ab>", line 2
    while((train_iter.epoch < max_epoch) and needStudy):
        ^
IndentationError: expected an indented block

Любая идея?

Ниже приведен полный код:

try:
    while((train_iter.epoch < max_epoch) and needStudy):
        train_batch = train_iter.next()
        x, t = concat_examples(train_batch)
        #print(t)    
        y = model(x)    
        loss = F.mean_squared_error(y, t)
        model.cleargrads()
        loss.backward()
        optimizer.update()
        if train_iter.is_new_epoch:
            print("epoch", train_iter.epoch, "loss=", loss.data, end=" ")
            loss_X.append(train_iter.epoch)
            loss_Y.append(loss.data)
except ValueError as e:
        raise Exception('Invalid json: {}'.format(e))        
        while True:
            test_batch = test_iter.next()
            x_test, t_test = concat_examples(test_batch)
            y_test = model(x_test)
            loss_test = F.mean_squared_error(y_test, t_test)
            if test_iter.is_new_epoch:
                test_iter.epoch = 0
                test_iter.current_position = 0
                test_iter.is_new_epoch = False
                test_iter._pushed_position = None
                break
        print("test_loss=", loss_test.data)
        loss_Y_test.append(loss_test.data)
        study_loss = loss_test.data
        if study_loss < studyThreshold:
            needStudy = False
            print("loss is less than threshold value")

, и ошибка, которая показывает мне, когда я использовал try функция показала мне, ошибка из этого раздела.

KeyError: 10534

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-397-31208bd43353> in <module>
      1 try:
      2     while((train_iter.epoch < max_epoch) and needStudy):
----> 3         train_batch = train_iter.next()
      4         x, t = concat_examples(train_batch)
      5         #print(t)

Ответы [ 2 ]

0 голосов
/ 16 октября 2019

Код: (Исправлено отступ для блока try:... except:...)

try:
    while((train_iter.epoch < max_epoch) and needStudy):
        train_batch = train_iter.next()
        x, t = concat_examples(train_batch)
        #print(t)    
        y = model(x)    
        loss = F.mean_squared_error(y, t)
        model.cleargrads()
        loss.backward()
        optimizer.update()
        if train_iter.is_new_epoch:
            print("epoch", train_iter.epoch, "loss=", loss.data, end=" ")
            loss_X.append(train_iter.epoch)
            loss_Y.append(loss.data)
except Exception as e: # replaced with Exception to handle other errors
    raise Exception('Invalid json: {}'.format(e))
    while True:
        test_batch = test_iter.next()
        x_test, t_test = concat_examples(test_batch)
        y_test = model(x_test)
        loss_test = F.mean_squared_error(y_test, t_test)
        if test_iter.is_new_epoch:
            test_iter.epoch = 0
            test_iter.current_position = 0
            test_iter.is_new_epoch = False
            test_iter._pushed_position = None
            break
    print("test_loss=", loss_test.data)
    loss_Y_test.append(loss_test.data)
    study_loss = loss_test.data
    if study_loss < studyThreshold:
        needStudy = False
        print("loss is less than threshold value")
0 голосов
/ 16 октября 2019
try:
    while((train_iter.epoch < max_epoch) and needStudy):
        train_batch = train_iter.next()
        x, t = concat_examples(train_batch)
        #print(t)    
        y = model(x)    
        loss = F.mean_squared_error(y, t)
        model.cleargrads()
        loss.backward()
        optimizer.update()
        if train_iter.is_new_epoch:
            print("epoch", train_iter.epoch, "loss=", loss.data, end=" ")
            loss_X.append(train_iter.epoch)
            loss_Y.append(loss.data)
except ValueError as e:
    raise Exception('Invalid json: {}'.format(e))

Оператор while после оператора try не имеет правильного отступа

...