[英]I am getting Attribute error as 'int' object has no attribute 'to'
I am writing a python code in Kaggle notebook for Image Classification.我正在 Kaggle 笔记本中为图像分类编写 python 代码。 In the training part, I am getting an error
在训练部分,我收到一个错误
AttributeError Traceback (most recent call last)
<ipython-input-22-052723d8ce9d> in <module>
5 test_loss = 0.0
6 for images,label in enumerate(train_loader):
----> 7 images,label = images.to(cuda),label.to(cuda)
8 optimizer.zero_grad()
9
AttributeError: 'int' object has no attribute 'to'
This is the following code, (I am giving only 2 parts, pls tell if you need more)这是以下代码,(我只给出了 2 个部分,请告诉您是否需要更多)
train_loader = torch.utils.data.DataLoader(train_data,batch_size = 128,num_workers =0,shuffle =True)
test_loader = torch.utils.data.DataLoader(test_data,batch_size = 64,num_workers =0,shuffle =False)
epoch = 10
for e in range(epoch):
train_loss = 0.0
test_loss = 0.0
for images,label in enumerate(train_loader):
images,label = images.to(cuda),label.to(cuda)
optimizer.zero_grad()
output = model(images)
_,predict = torch.max(output.data, 1)
loss = criterion(output,labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_size += label.size(0)
train_success += (predict==label).sum().item()
print("train_accuracy is {.2f}".format(100*(train_success/train_size)) )
I don't know much about the environment you're working in, but this is what goes wrong:我对您工作的环境了解不多,但这就是问题所在:
for images, label in enumerate (train_loader):
Puts whatever is in train_loader into label
, while images
is given a number. for images, label in enumerate (train_loader):
将 train_loader 中的任何内容放入label
中,同时为images
指定一个数字。
Try this to see what I mean, and to see what goes wrong:试试这个看看我的意思,看看出了什么问题:
for images, label in enumerate(train_loader):
print(images)
return
And since images
is a number (int), there is no images.to()
method associated with images
由于
images
是一个数字 (int),因此没有images.to()
方法与images
相关联
I had the same problem and after doing what Ayam said,我遇到了同样的问题,在按照 Ayam 说的做之后,
I got this result after printing images and this clearly explaines why i got the error.我在打印图像后得到了这个结果,这清楚地解释了为什么我得到了错误。
I managed to resolve this by using我设法通过使用解决了这个问题
images, label in (train_loader)
instead of代替
images, label in enumerate(train_loader)
Ps When running the above code snippets, the for loop keep going on Ps 运行上述代码片段时,for循环一直在进行
ie when i used batch size = 4 I am getting more than 4 labels and images.即当我使用批量大小 = 4 时,我得到超过 4 个标签和图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.