首页 > 解决方案 > 名为“TypeError:0-d 张量上的迭代”的错误

问题描述

我正在使用 PyTorch 处理 CNN 代码,我的代码如下:

import time
start_time=time.time()

epochs=10
train_losses=[]
test_losses=[]
train_correct=[]
test_correct=[]

for i in range(epochs):
    tsn_corr=[]
    tst_corr=[]
    
    for b, (X_train,y_train) in enumerate(train_loader):
        b+=1
        
        y_pred=model(X_train)
        loss=criterion(y_pred,y_train)
        
        #Tally the number of correct predictions
        
        predicted= torch.max(y_pred.data, 1)[1]
        batch_corr=(predicted==y_train).sum()
        tsn_corr += batch_corr
        
        #optimize paramters
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        #print interim results
        if b%600 == 0:
            print(f"epochs: {epochs}, batch: {b}, loss: {loss.item():10.8f}")
        
    loss=loss.detach().numpy()
    train_losses.append(loss)
    train_correct.append(tsn_corr)

当我运行此代码时,我收到此错误TypeError: iteration over a 0-d tensor

TypeError Traceback (most recent call last) <ipython-input-42-72616e5c4066> in <module> 22 predicted= torch.max(y_pred.data, 1)[1] 23 batch_corr=(predicted==y_train).sum() ---> 24 tsn_corr += batch_corr 25 26 #optimize paramters – 
Ali Mashoud
Aug 14 at 15:22  
~\Anaconda3\lib\site-packages\torch\tensor.py in iter__(self) 583 return handle_torch_function(Tensor.__iter, (self,), self) 584 if self.dim() == 0: --> 585 raise TypeError('iteration over a 0-d tensor') 586 if torch._C._get_tracing_state(): 587 warnings.warn('Iterating over a tensor might cause the trace to be incorrect. ' TypeError: iteration over a 0-d tensor.

有人可以解释一下我做错了什么以及代码有什么问题。

标签: pythonpytorch

解决方案


推荐阅读