python - 名为“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.
有人可以解释一下我做错了什么以及代码有什么问题。
解决方案
推荐阅读
- python - 加速完美掉期计算 - 避免循环
- php - 如何使用 PECL 安装 PHP 扩展(使用 Homebrew)
- python - 函数不更新全局变量
- c++ - 不使用双指针语法创建基于堆的二维数组?
- c# - 将具有 app.config 和 .settings 文件的应用程序移植到 .Net Core 后,如何防止“app.config”错误?
- html - 即使父元素的高度设置为“100vh”,子元素也不包含在视口高度中
- javascript - 尝试使用 ajax 在 html 按钮上单击 sendmail.php 页面上执行 php 脚本
- php - 如何在codeigniter的.htaccess文件中传递多个参数
- sql - 对子查询使用 NOT EXISTS
- ios - 无尽的“邀请”;在创建沙盒测试员帐户时